feat: optionally sort translation mappings by creation date

This commit is contained in:
muena
2026-10-19 06:49:34 +02:00
parent 03a793ad7c
commit a627d9147e
8 changed files with 218 additions and 62 deletions

View File

@@ -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<string, string> {
const createdAt: Record<string, string> = {};
const seen = new Set<string>();
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<T extends { placeholder: string; type: string }>(
rows: T[], createdAt: Record<string, string>,
): 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));
}

View File

@@ -151,6 +151,7 @@ export default function Command() {
title="Übersetzungstabelle anzeigen"
icon={Icon.List}
target={<TranslationTable title={session.name} mapping={session.mapping}
createdAtByKey={session.mappingCreatedAt}
removeDescription="Die gesamte Gruppe wird aus der Sitzung entfernt und künftig dort nicht mehr vorgeschlagen. Bereits kopierte oder eingefügte Texte werden nicht rückwirkend geändert."
onRemove={async (root) => {
const updated = await releaseSessionMappingGroup(session.id, root);

View File

@@ -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)} />)} />
<Action.Push title="Übersetzungstabelle anzeigen" icon={Icon.List}
target={<TranslationTable title={`${props.projectName} · ${new Date(run.createdAt).toLocaleString("de-AT")}`}
mapping={run.mapping} />} />
mapping={run.mapping}
createdAtByKey={projectMappingCreatedAt(props.entries.slice(index).map((entry) => entry.run), run.mapping)} />} />
<Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder}
onAction={() => showInFinder(runCopiesPath(run, directory))} />
<Action.CopyToClipboard title="Speicherpfad kopieren" content={runCopiesPath(run, directory)} />
@@ -439,6 +441,7 @@ export default function Command() {
earlierRuns={entries.slice(1)} />)} />
<Action.Push title="Übersetzungstabelle anzeigen" icon={Icon.List}
target={<TranslationTable title={run.projectName} mapping={run.mapping}
createdAtByKey={projectMappingCreatedAt(entries.map((entry) => entry.run), run.mapping)}
onAdd={async (input) => {
const updated = await addProjectMappingEntry(run.projectPath, input);
await refresh();

View File

@@ -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<string, string> {
const dates: Record<string, string> = {};
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<void> {
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<void> {
await saveSessions(
sessions.map((session) =>
session.id === id
? { ...session, mapping: {}, updatedAt: nowIso() }
? { ...session, mapping: {}, mappingCreatedAt: {}, updatedAt: nowIso() }
: session,
),
);

View File

@@ -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<string, string>;
};
type ManualEntry = { original: string; type: string; placeholder?: string };
const EMPTY_DATES: Record<string, string> = {};
function AddMappingForm(props: { onAdd: (input: ManualEntry) => Promise<PlaceholderMapping>;
onSaved: (mapping: PlaceholderMapping) => void }) {
@@ -55,6 +59,7 @@ function AddMappingForm(props: { onAdd: (input: ManualEntry) => Promise<Placehol
export function TranslationTable({
title,
mapping,
createdAtByKey = EMPTY_DATES,
onAdd,
onMerge,
onDetach,
@@ -63,6 +68,7 @@ export function TranslationTable({
}: {
title: string;
mapping: PlaceholderMapping;
createdAtByKey?: Record<string, string>;
onAdd?: (input: ManualEntry) => Promise<PlaceholderMapping>;
onMerge?: (source: string, target: string) => Promise<PlaceholderMapping>;
onDetach?: (key: string) => Promise<PlaceholderMapping>;
@@ -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<string, string> = {};
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<string, Map<string, string[]>>();
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<PlaceholderMapping>, success: string): Promise<boolean> {
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 <List.Item key={placeholder} icon={Icon.ArrowRight} title={placeholder}
subtitle={visibleMapping[placeholder].original}
keywords={[type, ...members.flatMap((key) => [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={<ActionPanel>
<Action.Push title="Gruppe und Varianten anzeigen" icon={Icon.Eye}
target={<List navigationTitle={`${type} · ${placeholder}`} searchBarPlaceholder="Variante suchen">
{orderedMembers.map((key) => <List.Item key={key} title={key}
subtitle={visibleMapping[key].original}
accessories={[
key === placeholder ? { text: "Hauptbegriff" } : { text: `→ ${placeholder}` },
...(sortOrder === "created-desc" ? [{ text: visibleDates[key]
? new Date(visibleDates[key]).toLocaleString("de-AT") : "Datum unbekannt" }] : []),
]}
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>}
{onRemove && <Action title="False Positive freigeben" icon={Icon.XMarkCircle}
onAction={() => remove(placeholder, members)} />}
<Action.CopyToClipboard title="Platzhalter kopieren" content={placeholder} />
<Action.CopyToClipboard title="Klartext kopieren" content={visibleMapping[placeholder].original} />
</ActionPanel>} />;
}
return (
<List
isLoading={busy}
navigationTitle={`Übersetzungstabelle · ${title}`}
searchBarPlaceholder="Platzhalter oder Klartext suchen"
searchBarAccessory={<List.Dropdown tooltip="Sortierung" value={sortOrder} onChange={(value) => setSortOrder(value as "category" | "created-desc")}>
<List.Dropdown.Item value="category" title="Kategorie und Platzhalter (Standard)" />
<List.Dropdown.Item value="created-desc" title="Anlagedatum · neueste zuerst" />
</List.Dropdown>}
>
<List.EmptyView
title="Keine Zuordnungen"
@@ -118,60 +190,18 @@ export function TranslationTable({
<List.Item icon={Icon.Plus} title="Begriff oder fehlenden Platzhalter hinzufügen"
subtitle="Neuer Eintrag für diese Übersetzungstabelle"
actions={<ActionPanel><Action title="Zuordnung hinzufügen" icon={Icon.Plus}
onAction={() => push(<AddMappingForm onAdd={onAdd} onSaved={setVisibleMapping} />)} /></ActionPanel>} />
onAction={() => push(<AddMappingForm onAdd={onAdd} onSaved={showMapping} />)} /></ActionPanel>} />
</List.Section>}
{[...groups]
{sortOrder === "category" ? [...groups]
.sort(([a], [b]) => a.localeCompare(b))
.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={visibleMapping[placeholder].original}
keywords={members.flatMap((key) => [key, visibleMapping[key].original])}
accessories={members.length > 1 ? [{ text: `${members.length} Zuordnungen` }] : []}
actions={
<ActionPanel>
<Action.Push
title="Gruppe und Varianten anzeigen"
icon={Icon.Eye}
target={
<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>}
{onRemove && <Action title="False Positive freigeben" icon={Icon.XMarkCircle}
onAction={() => remove(placeholder, members)} />}
<Action.CopyToClipboard
title="Platzhalter kopieren"
content={placeholder}
/>
<Action.CopyToClipboard
title="Klartext kopieren"
content={visibleMapping[placeholder].original}
/>
</ActionPanel>
}
/>
))}
{[...roots].map(([placeholder, members]) => renderRow(type, placeholder, members))}
</List.Section>
))}
)) : <List.Section title="Anlagedatum · neueste zuerst">
{sortMappingRowsByCreatedAt(rows, visibleDates)
.map(({ type, placeholder, members }) => renderRow(type, placeholder, members))}
</List.Section>}
</List>
);
}
@@ -184,19 +214,20 @@ export default function Command() {
const refresh = useCallback(async () => {
await Promise.all([listAllRuns(), listSessions()])
.then(([runs, savedSessions]) => {
const latest = new Map<string, TableSource>();
const history = new Map<string, ProjectRun[]>();
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() {
<TranslationTable
title={source.title}
mapping={source.mapping}
createdAtByKey={source.createdAtByKey}
onAdd={async (input) => {
const run = await addProjectMappingEntry(source.id, input);
await refresh();
@@ -290,6 +323,7 @@ export default function Command() {
<TranslationTable
title={source.title}
mapping={source.mapping}
createdAtByKey={source.createdAtByKey}
onAdd={async (input) => {
const session = await getSession(source.id);
if (!session) throw new Error("Sitzung nicht gefunden.");

View File

@@ -36,6 +36,7 @@ export type VelumSession = {
mapping: PlaceholderMapping;
entityTypes?: EntityType[];
excludedTerms?: Array<{ type: string; original: string }>;
mappingCreatedAt?: Record<string, string>;
};
export type QuickOutput = "copy" | "paste";