import { Action, ActionPanel, Clipboard, Detail, Form, Icon, showToast, Toast, useNavigation, } from "@raycast/api"; import { useEffect, useState } from "react"; import { getSelectedTextSafely } from "./selection"; import { canonicalProjectPath, listAllRuns, listRuns, restoreTextWithCount, } from "./lib/velum-project"; import { depseudonymize } from "./velum"; import { getActiveSessionId, getSession, listSessions } from "./sessions"; import type { DepseudonymizeResponse, VelumSession } from "./types"; import { markdownCodeBlock, sessionSubtitle } from "./ui"; import { restoreRichHtml } from "./lib/rich-text"; import { copyRichText, pasteRichText, readRichClipboardHtml } from "./rich-clipboard"; import { mappingForRestoration } from "./lib/mapping-groups"; type FormValues = { text: string; sessionId: string; }; const CHOOSE_TARGET = "choose-target"; type RichSource = { text: string; html: string }; export default function Command( props: { initialSource?: "selection" | "clipboard" } = {}, ) { const [text, setText] = useState(""); const [richSource, setRichSource] = useState(); const [sessions, setSessions] = useState([]); const [activeSessionId, setActiveSessionId] = useState(); const [projects, setProjects] = useState< Array<{ path: string; name: string }> >([]); const [targetId, setTargetId] = useState(CHOOSE_TARGET); const [isLoading, setIsLoading] = useState(true); const { push } = useNavigation(); useEffect(() => { async function load() { const initialText = (async (): Promise<{ text?: string | null; rich?: RichSource; }> => { if (props.initialSource === "selection") { const selected = await getSelectedTextSafely(); let html: string | undefined; if (selected) { for (const delay of [0, 150, 300]) { if (delay) await new Promise((resolve) => setTimeout(resolve, delay)); html = await readRichClipboardHtml(); if (html) break; } } return { text: selected, rich: selected && html ? { text: selected, html } : undefined, }; } if (props.initialSource === "clipboard") { const clipboard = await Clipboard.read(); const html = clipboard.html ?? await readRichClipboardHtml(); return { text: clipboard.text, rich: html && clipboard.text ? { text: clipboard.text, html } : undefined, }; } return {}; })(); const [loadedSessions, activeId, savedRuns, selected] = await Promise.all( [listSessions(), getActiveSessionId(), listAllRuns(), initialText], ); setSessions(loadedSessions); setActiveSessionId(activeId); const unique = new Map(); for (const { run } of savedRuns) { const path = canonicalProjectPath(run.projectPath); if (!unique.has(path)) unique.set(path, run.projectName); } setProjects([...unique].map(([path, name]) => ({ path, name }))); if (selected.text) { setText(selected.text); setRichSource(selected.rich); } else if (props.initialSource) await showToast({ style: Toast.Style.Failure, title: props.initialSource === "selection" ? "Kein markierter Text gefunden" : "Zwischenablage enthält keinen Text", }); setIsLoading(false); } load().catch(async (error: Error) => { setIsLoading(false); await showToast({ style: Toast.Style.Failure, title: "Zuordnungen nicht lesbar", message: error.message, }); }); }, []); async function loadClipboardText() { const clipboard = await Clipboard.read(); const clipboardText = clipboard.text; if (!clipboardText) { await showToast({ style: Toast.Style.Failure, title: "Zwischenablage enthält keinen Text", }); return; } setText(clipboardText); const html = clipboard.html ?? await readRichClipboardHtml(); setRichSource( html ? { text: clipboardText, html } : undefined, ); } async function handleSubmit(values: FormValues) { const input = values.text; if ( !input.trim() || !values.sessionId || values.sessionId === CHOOSE_TARGET ) { await showToast({ style: Toast.Style.Failure, title: "Projekt oder Sitzung wählen und Text eingeben", }); return; } const toast = await showToast({ style: Toast.Style.Animated, title: "Stelle wieder her…", }); try { let result: DepseudonymizeResponse; let richHtml: string | undefined; let targetName: string; let targetSubtitle: string; if (values.sessionId.startsWith("project:")) { 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, restorationMapping, saved.run.matchModes, ); result = { original_text: restored.text, replacements_made: restored.replacements, }; if (richSource?.text === input) { richHtml = restoreRichHtml( richSource.html, input, result.original_text, restorationMapping, saved.run.matchModes, ); } targetName = `Projekt ${saved.run.projectName}`; targetSubtitle = saved.run.projectPath; } else { const session = await getSession(values.sessionId); if (!session) throw new Error("Sitzung nicht gefunden."); const restorationMapping = mappingForRestoration(session.mapping); result = await depseudonymize(input, restorationMapping); if (richSource?.text === input) { richHtml = restoreRichHtml( richSource.html, input, result.original_text, restorationMapping, undefined, true, ); } targetName = session.name; targetSubtitle = sessionSubtitle(session); } toast.style = Toast.Style.Success; toast.title = "Wiederhergestellt"; toast.message = `${result.replacements_made} Ersetzungen`; push( , ); } catch (error) { toast.style = Toast.Style.Failure; toast.title = "Wiederherstellung fehlgeschlagen"; toast.message = error instanceof Error ? error.message : String(error); } } return (
} > {projects.map((project) => ( ))} {sessions.map((session) => ( ))} ); } function DepseudonymizeResult({ result, targetName, targetSubtitle, richHtml, showFormatStatus, formatUnavailableReason, }: { result: DepseudonymizeResponse; targetName: string; targetSubtitle: string; richHtml?: string; showFormatStatus: boolean; formatUnavailableReason: string; }) { const markdown = [ `# ${targetName}`, targetSubtitle, "", "## Wiederhergestellter Text", markdownCodeBlock(result.original_text), "", `Ersetzungen: ${result.replacements_made}`, richHtml ? "Formatierung kann beim Kopieren oder Einfügen übernommen werden." : showFormatStatus ? `${formatUnavailableReason} Klartext kann weiterhin kopiert werden.` : "", ].join("\n"); return ( {richHtml && ( <> { try { await copyRichText(richHtml, result.original_text); await showToast({ style: Toast.Style.Success, title: "Mit Formatierung kopiert", }); } catch (error) { await showToast({ style: Toast.Style.Failure, title: "Formatierter Text konnte nicht kopiert werden", message: error instanceof Error ? error.message : String(error), }); } }} /> { try { await pasteRichText(richHtml, result.original_text); } catch (error) { await showToast({ style: Toast.Style.Failure, title: "Formatierter Text konnte nicht eingefügt werden", message: `${error instanceof Error ? error.message : String(error)} · Der Text liegt formatiert in der Zwischenablage.`, }); } }} /> )} Clipboard.paste(result.original_text)} /> } /> ); }