fix: retain rich formatting when restoring selected Teams text

This commit is contained in:
muena
2026-10-21 12:02:45 +02:00
parent 41b935a145
commit 5200fcde70
2 changed files with 78 additions and 22 deletions

View File

@@ -22,7 +22,7 @@ import { getActiveSessionId, getSession, listSessions } from "./sessions";
import type { DepseudonymizeResponse, VelumSession } from "./types"; import type { DepseudonymizeResponse, VelumSession } from "./types";
import { markdownCodeBlock, sessionSubtitle } from "./ui"; import { markdownCodeBlock, sessionSubtitle } from "./ui";
import { restoreRichHtml } from "./lib/rich-text"; import { restoreRichHtml } from "./lib/rich-text";
import { copyRichText } from "./rich-clipboard"; import { copyRichText, pasteRichText, readRichClipboardHtml } from "./rich-clipboard";
import { mappingForRestoration } from "./lib/mapping-groups"; import { mappingForRestoration } from "./lib/mapping-groups";
type FormValues = { type FormValues = {
@@ -55,25 +55,25 @@ export default function Command(
}> => { }> => {
if (props.initialSource === "selection") { if (props.initialSource === "selection") {
const selected = await getSelectedTextSafely(); const selected = await getSelectedTextSafely();
const clipboard = selected let html: string | undefined;
? await Clipboard.read().catch(() => undefined) if (selected) {
: undefined; for (const delay of [0, 150, 300]) {
if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
html = await readRichClipboardHtml();
if (html) break;
}
}
return { return {
text: selected, text: selected,
rich: rich: selected && html ? { text: selected, html } : undefined,
clipboard?.html && clipboard.text === selected
? { text: selected, html: clipboard.html }
: undefined,
}; };
} }
if (props.initialSource === "clipboard") { if (props.initialSource === "clipboard") {
const clipboard = await Clipboard.read(); const clipboard = await Clipboard.read();
const html = clipboard.html ?? await readRichClipboardHtml();
return { return {
text: clipboard.text, text: clipboard.text,
rich: rich: html && clipboard.text ? { text: clipboard.text, html } : undefined,
clipboard.html && clipboard.text
? { text: clipboard.text, html: clipboard.html }
: undefined,
}; };
} }
return {}; return {};
@@ -123,9 +123,10 @@ export default function Command(
return; return;
} }
setText(clipboardText); setText(clipboardText);
const html = clipboard.html ?? await readRichClipboardHtml();
setRichSource( setRichSource(
clipboard.html html
? { text: clipboardText, html: clipboard.html } ? { text: clipboardText, html }
: undefined, : undefined,
); );
} }
@@ -206,6 +207,9 @@ export default function Command(
targetSubtitle={targetSubtitle} targetSubtitle={targetSubtitle}
richHtml={richHtml} richHtml={richHtml}
showFormatStatus={Boolean(props.initialSource || richSource)} showFormatStatus={Boolean(props.initialSource || richSource)}
formatUnavailableReason={!richHtml && richSource?.text === input
? "Die Formatierung der Auswahl konnte nicht eindeutig mit dem wiederhergestellten Text abgeglichen werden."
: "Die Quellanwendung hat für diese Auswahl keine HTML- oder RTF-Formatierung bereitgestellt."}
/>, />,
); );
} catch (error) { } catch (error) {
@@ -280,12 +284,14 @@ function DepseudonymizeResult({
targetSubtitle, targetSubtitle,
richHtml, richHtml,
showFormatStatus, showFormatStatus,
formatUnavailableReason,
}: { }: {
result: DepseudonymizeResponse; result: DepseudonymizeResponse;
targetName: string; targetName: string;
targetSubtitle: string; targetSubtitle: string;
richHtml?: string; richHtml?: string;
showFormatStatus: boolean; showFormatStatus: boolean;
formatUnavailableReason: string;
}) { }) {
const markdown = [ const markdown = [
`# ${targetName}`, `# ${targetName}`,
@@ -298,7 +304,7 @@ function DepseudonymizeResult({
richHtml richHtml
? "Formatierung kann beim Kopieren oder Einfügen übernommen werden." ? "Formatierung kann beim Kopieren oder Einfügen übernommen werden."
: showFormatStatus : showFormatStatus
? "Formatierung war nicht verfügbar oder konnte nicht sicher zugeordnet werden; Klartext kann weiterhin kopiert werden." ? `${formatUnavailableReason} Klartext kann weiterhin kopiert werden.`
: "", : "",
].join("\n"); ].join("\n");
@@ -332,12 +338,17 @@ function DepseudonymizeResult({
<Action <Action
title="Mit Formatierung einfügen" title="Mit Formatierung einfügen"
icon={Icon.TextCursor} icon={Icon.TextCursor}
onAction={() => onAction={async () => {
Clipboard.paste({ try {
html: richHtml, await pasteRichText(richHtml, result.original_text);
text: 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.`,
});
}
}}
/> />
</> </>
)} )}

View File

@@ -1,4 +1,5 @@
import { execFile } from "node:child_process"; import { Clipboard, closeMainWindow } from "@raycast/api";
import { execFile, spawn } from "node:child_process";
import { promisify } from "node:util"; import { promisify } from "node:util";
const execFileAsync = promisify(execFile); const execFileAsync = promisify(execFile);
@@ -16,6 +17,42 @@ const RICH_COPY_SCRIPT = [
"pb.setStringForType(text, 'public.utf8-plain-text');", "pb.setStringForType(text, 'public.utf8-plain-text');",
].join("\n"); ].join("\n");
const RICH_READ_SCRIPT = [
"ObjC.import('AppKit');",
"const pb = $.NSPasteboard.generalPasteboard;",
"const html = pb.stringForType('public.html') || pb.stringForType('text/html');",
"const rtf = html ? null : pb.dataForType('public.rtf');",
"JSON.stringify({ html: html ? ObjC.unwrap(html) : null, rtf: rtf ? ObjC.unwrap(rtf.base64EncodedStringWithOptions(0)) : null });",
].join("\n");
async function htmlFromRtf(encoded: string): Promise<string | undefined> {
return new Promise((resolve) => {
const child = spawn("textutil", ["-convert", "html", "-stdin", "-stdout"]);
const chunks: Buffer[] = [];
child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk));
child.on("error", () => resolve(undefined));
child.on("close", (code) => resolve(code === 0 ? Buffer.concat(chunks).toString("utf8") : undefined));
child.stdin.on("error", () => undefined);
child.stdin.end(Buffer.from(encoded, "base64"));
});
}
/** Raycast's clipboard reader can omit HTML/RTF from app selections such as Teams. */
export async function readRichClipboardHtml(): Promise<string | undefined> {
const raycast = await Clipboard.read().catch(() => undefined);
if (raycast?.html) return raycast.html;
try {
const { stdout } = await execFileAsync("osascript", ["-l", "JavaScript", "-e", RICH_READ_SCRIPT],
{ maxBuffer: 16 * 1024 * 1024 });
const native = JSON.parse(stdout.trim()) as { html: string | null; rtf: string | null };
if (native.html) return native.html;
if (native.rtf) return await htmlFromRtf(native.rtf);
} catch {
// Plain text remains available even if macOS cannot expose the rich pasteboard types.
}
return undefined;
}
export async function copyRichText(html: string, text: string): Promise<void> { export async function copyRichText(html: string, text: string): Promise<void> {
await execFileAsync( await execFileAsync(
"osascript", "osascript",
@@ -25,3 +62,11 @@ export async function copyRichText(html: string, text: string): Promise<void> {
}, },
); );
} }
/** Paste the rich pasteboard data without Raycast replacing it with plain text. */
export async function pasteRichText(html: string, text: string): Promise<void> {
await copyRichText(html, text);
await closeMainWindow();
await new Promise((resolve) => setTimeout(resolve, 150));
await execFileAsync("osascript", ["-e", 'tell application "System Events" to keystroke "v" using command down']);
}