forked from r.muellner/velum-raycast
373 lines
17 KiB
TypeScript
373 lines
17 KiB
TypeScript
import {
|
|
Action,
|
|
ActionPanel,
|
|
Alert,
|
|
confirmAlert,
|
|
Form,
|
|
Icon,
|
|
List,
|
|
showToast,
|
|
Toast,
|
|
useNavigation,
|
|
} from "@raycast/api";
|
|
import { useCallback, useEffect, useState } from "react";
|
|
import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry, updateProjectMapping } from "./lib/velum-project";
|
|
import { detachMappingGroup, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups";
|
|
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 }) {
|
|
const { pop } = useNavigation();
|
|
const [busy, setBusy] = useState(false);
|
|
async function save(values: { original: string; type: string; placeholder: string }) {
|
|
setBusy(true);
|
|
try {
|
|
const type = values.type.trim() || /^([A-ZÄÖÜ][A-ZÄÖÜ0-9_]*)_\d+$/iu.exec(values.placeholder.trim())?.[1] || "BEGRIFF";
|
|
const mapping = await props.onAdd({ ...values, type });
|
|
props.onSaved(mapping);
|
|
await showToast({ style: Toast.Style.Success, title: "Zuordnung gespeichert" });
|
|
pop();
|
|
} catch (error) {
|
|
await showToast({ style: Toast.Style.Failure, title: "Zuordnung nicht gespeichert",
|
|
message: (error as Error).message });
|
|
} finally { setBusy(false); }
|
|
}
|
|
return <Form isLoading={busy} navigationTitle="Zuordnung ergänzen"
|
|
actions={<ActionPanel><Action.SubmitForm title="Zuordnung speichern" onSubmit={save} /></ActionPanel>}>
|
|
<Form.Description text="Der Eintrag wird zur Wiederherstellung verwendet. Für eine garantierte Maskierung bei künftigen Projektläufen zusätzlich eine Projektregel anlegen." />
|
|
<Form.TextField id="original" title="Klartext-Begriff" placeholder="Originalwert" />
|
|
<Form.TextField id="type" title="Kategorie (optional)" placeholder="Aus Platzhalter ableiten; sonst BEGRIFF" />
|
|
<Form.TextField id="placeholder" title="Platzhalter (optional)" placeholder="z. B. PERSON_61; leer = nächste freie Nummer" />
|
|
</Form>;
|
|
}
|
|
|
|
export function TranslationTable({
|
|
title,
|
|
mapping,
|
|
createdAtByKey = EMPTY_DATES,
|
|
onAdd,
|
|
onMerge,
|
|
onDetach,
|
|
onRemove,
|
|
removeDescription,
|
|
}: {
|
|
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>;
|
|
onRemove?: (root: string) => Promise<PlaceholderMapping>;
|
|
removeDescription?: string;
|
|
}) {
|
|
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); 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";
|
|
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);
|
|
}
|
|
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 {
|
|
showMapping(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); }
|
|
}
|
|
async function remove(root: string, members: string[]) {
|
|
if (!onRemove || !(await confirmAlert({
|
|
title: `${members.length} Zuordnung${members.length === 1 ? "" : "en"} als False Positive freigeben?`,
|
|
message: removeDescription ?? "Diese Zuordnungen werden entfernt und als Ausnahmen gespeichert.",
|
|
primaryAction: { title: "Freigeben", style: Alert.ActionStyle.Destructive },
|
|
}))) return;
|
|
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"
|
|
description="Für diesen Stand sind noch keine Übersetzungen gespeichert."
|
|
/>
|
|
{onAdd && <List.Section title="Pflege">
|
|
<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={showMapping} />)} /></ActionPanel>} />
|
|
</List.Section>}
|
|
{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]) => 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>
|
|
);
|
|
}
|
|
|
|
export default function Command() {
|
|
const [projects, setProjects] = useState<TableSource[]>([]);
|
|
const [sessions, setSessions] = useState<TableSource[]>([]);
|
|
const [busy, setBusy] = useState(true);
|
|
|
|
const refresh = useCallback(async () => {
|
|
await Promise.all([listAllRuns(), listSessions()])
|
|
.then(([runs, savedSessions]) => {
|
|
const history = new Map<string, ProjectRun[]>();
|
|
for (const { run } of runs) {
|
|
const path = canonicalProjectPath(run.projectPath);
|
|
if (!history.has(path)) history.set(path, []);
|
|
history.get(path)!.push(run);
|
|
}
|
|
setProjects(
|
|
[...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) => ({
|
|
id: session.id,
|
|
title: session.name,
|
|
subtitle: `${Object.keys(session.mapping).length} Zuordnungen · ${new Date(session.updatedAt).toLocaleString("de-AT")}`,
|
|
mapping: session.mapping,
|
|
createdAtByKey: session.mappingCreatedAt ?? {},
|
|
})),
|
|
);
|
|
});
|
|
}, []);
|
|
useEffect(() => {
|
|
refresh().catch((error: Error) => showToast({ style: Toast.Style.Failure,
|
|
title: "Übersetzungstabellen nicht lesbar", message: error.message }))
|
|
.finally(() => setBusy(false));
|
|
}, [refresh]);
|
|
|
|
return (
|
|
<List
|
|
isLoading={busy}
|
|
navigationTitle="Übersetzungstabellen"
|
|
searchBarPlaceholder="Projekt oder Sitzung suchen"
|
|
>
|
|
<List.EmptyView
|
|
title="Keine Tabellen"
|
|
description="Pseudonymisiere zuerst Text oder Projektdateien."
|
|
/>
|
|
<List.Section title="Projekte">
|
|
{projects.map((source) => (
|
|
<List.Item
|
|
key={source.id}
|
|
icon={Icon.Folder}
|
|
title={source.title}
|
|
subtitle={source.subtitle}
|
|
accessories={[
|
|
{ text: `${Object.keys(source.mapping).length} Zuordnungen` },
|
|
]}
|
|
actions={
|
|
<ActionPanel>
|
|
<Action.Push
|
|
title="Übersetzungstabelle anzeigen"
|
|
icon={Icon.List}
|
|
target={
|
|
<TranslationTable
|
|
title={source.title}
|
|
mapping={source.mapping}
|
|
createdAtByKey={source.createdAtByKey}
|
|
onAdd={async (input) => {
|
|
const run = await addProjectMappingEntry(source.id, input);
|
|
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;
|
|
}}
|
|
removeDescription="Die gesamte Gruppe wird als Projektausnahme gespeichert. Auch zwischenzeitlich bearbeitete Projektdateien werden anhand ihres aktuellen Stands korrigiert und vorher gesichert."
|
|
onRemove={async (root) => {
|
|
const revised = await releaseProjectMapping(source.id, root);
|
|
await refresh();
|
|
return revised.run.mapping;
|
|
}}
|
|
/>
|
|
}
|
|
/>
|
|
</ActionPanel>
|
|
}
|
|
/>
|
|
))}
|
|
</List.Section>
|
|
<List.Section title="Sitzungen">
|
|
{sessions.map((source) => (
|
|
<List.Item
|
|
key={source.id}
|
|
icon={Icon.Person}
|
|
title={source.title}
|
|
subtitle={source.subtitle}
|
|
actions={
|
|
<ActionPanel>
|
|
<Action.Push
|
|
title="Übersetzungstabelle anzeigen"
|
|
icon={Icon.List}
|
|
target={
|
|
<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.");
|
|
const normalized = Object.fromEntries(Object.entries(session.mapping)
|
|
.map(([key, entry]) => [key.replace(/^<|>$/g, ""), entry]));
|
|
const { placeholder, entry } = prepareManualMappingEntry(normalized, [], input);
|
|
const bracketed = Object.keys(session.mapping).some((key) => key.startsWith("<"));
|
|
const key = bracketed ? `<${placeholder}>` : placeholder;
|
|
const updated = await updateSessionMapping(session.id,
|
|
{ ...session.mapping, [key]: entry }, session.entityTypes);
|
|
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;
|
|
}}
|
|
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(source.id, root);
|
|
await refresh();
|
|
return updated.mapping;
|
|
}}
|
|
/>
|
|
}
|
|
/>
|
|
</ActionPanel>
|
|
}
|
|
/>
|
|
))}
|
|
</List.Section>
|
|
</List>
|
|
);
|
|
}
|