fix: 修复复制功能,向主页面发送信息;修复user的信息离复制按钮太远的问题;

This commit is contained in:
肖应宇 2026-03-23 13:34:49 +08:00
parent fc1f38a545
commit 8dac856258
8 changed files with 79 additions and 15 deletions

View File

@ -549,7 +549,7 @@ export default function ChatPage() {
</DevDialog> </DevDialog>
{/* MARK: 开发测试iframe 通信功能测试面板 */} {/* MARK: 开发测试iframe 通信功能测试面板 */}
{/* <IframeTestPanel /> */} <IframeTestPanel />
</div> </div>
</ThreadContext.Provider> </ThreadContext.Provider>
); );

View File

@ -1,7 +1,7 @@
"use client"; "use client";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils"; import { cn, copyToClipboard } from "@/lib/utils";
import { CheckIcon, CopyIcon } from "lucide-react"; import { CheckIcon, CopyIcon } from "lucide-react";
import { import {
type ComponentProps, type ComponentProps,
@ -146,14 +146,9 @@ export const CodeBlockCopyButton = ({
const [isCopied, setIsCopied] = useState(false); const [isCopied, setIsCopied] = useState(false);
const { code } = useContext(CodeBlockContext); const { code } = useContext(CodeBlockContext);
const copyToClipboard = async () => { const handleCopy = async () => {
if (typeof window === "undefined" || !navigator?.clipboard?.writeText) {
onError?.(new Error("Clipboard API not available"));
return;
}
try { try {
await navigator.clipboard.writeText(code); await copyToClipboard(code);
setIsCopied(true); setIsCopied(true);
onCopy?.(); onCopy?.();
setTimeout(() => setIsCopied(false), timeout); setTimeout(() => setIsCopied(false), timeout);
@ -167,7 +162,7 @@ export const CodeBlockCopyButton = ({
return ( return (
<Button <Button
className={cn("shrink-0", className)} className={cn("shrink-0", className)}
onClick={copyToClipboard} onClick={handleCopy}
size="icon" size="icon"
variant="ghost" variant="ghost"
{...props} {...props}

View File

@ -29,7 +29,7 @@ export const Message = ({ className, from, ...props }: MessageProps) => (
className={cn( className={cn(
"group flex w-full flex-col gap-2 rounded-[10px] p-[20px]", "group flex w-full flex-col gap-2 rounded-[10px] p-[20px]",
from === "user" from === "user"
? "is-user ml-auto justify-end px-0" ? "is-user ml-auto justify-end px-0 pb-0"
: "is-assistant bg-[#ffffff]", : "is-assistant bg-[#ffffff]",
className, className,
)} )}

View File

@ -48,7 +48,7 @@ import { installSkill } from "@/core/skills/api";
import { streamdownPlugins } from "@/core/streamdown"; import { streamdownPlugins } from "@/core/streamdown";
import { checkCodeFile, getFileName } from "@/core/utils/files"; import { checkCodeFile, getFileName } from "@/core/utils/files";
import { env } from "@/env"; import { env } from "@/env";
import { cn } from "@/lib/utils"; import { cn, copyToClipboard } from "@/lib/utils";
import { CitationLink } from "../citations/citation-link"; import { CitationLink } from "../citations/citation-link";
import { Tooltip } from "../tooltip"; import { Tooltip } from "../tooltip";
@ -240,7 +240,7 @@ export function ArtifactFileDetail({
disabled={!content} disabled={!content}
onClick={async () => { onClick={async () => {
try { try {
await navigator.clipboard.writeText(displayContent ?? ""); await copyToClipboard(displayContent ?? "");
toast.success(t.clipboard.copiedToClipboard); toast.success(t.clipboard.copiedToClipboard);
} catch (error) { } catch (error) {
toast.error("Failed to copy to clipboard"); toast.error("Failed to copy to clipboard");

View File

@ -3,6 +3,7 @@ import { useCallback, useState, type ComponentProps } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useI18n } from "@/core/i18n/hooks"; import { useI18n } from "@/core/i18n/hooks";
import { copyToClipboard } from "@/lib/utils";
import { Tooltip } from "./tooltip"; import { Tooltip } from "./tooltip";
@ -15,7 +16,7 @@ export function CopyButton({
const { t } = useI18n(); const { t } = useI18n();
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
const handleCopy = useCallback(() => { const handleCopy = useCallback(() => {
void navigator.clipboard.writeText(clipboardData); void copyToClipboard(clipboardData);
setCopied(true); setCopied(true);
setTimeout(() => setCopied(false), 2000); setTimeout(() => setCopied(false), 2000);
}, [clipboardData]); }, [clipboardData]);

View File

@ -5,6 +5,7 @@ import { useState } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useIframeSkill } from "@/hooks/use-iframe-skill"; import { useIframeSkill } from "@/hooks/use-iframe-skill";
import { copyToClipboard } from "@/lib/utils";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
/** /**
@ -55,6 +56,15 @@ export function IframeTestPanel() {
iframeSkill.clearSkill(); iframeSkill.clearSkill();
addLog("clearSkill 已调用postMessage → skill_id=0"); addLog("clearSkill 已调用postMessage → skill_id=0");
} }
function handleTestClipboardCopy() {
const testText = "测试复制内容 - " + new Date().toISOString();
copyToClipboard(testText);
addLog(`copyToClipboard → "${testText.slice(0, 30)}..."`);
}
// 检测是否在 iframe 中
const isInIframe = typeof window !== "undefined" && window.self !== window.top;
if (!open) { if (!open) {
return ( return (
<button <button
@ -204,6 +214,40 @@ export function IframeTestPanel() {
</div> </div>
</div> </div>
{/* 场景 4剪贴板复制iframe 通信) */}
<div>
<div className="mb-1 flex items-center justify-between">
<span className="text-xs font-semibold text-gray-500">
iframe
</span>
<span
className={cn(
"rounded px-1.5 py-0.5 text-[10px] font-medium",
isInIframe
? "bg-violet-100 text-violet-700"
: "bg-gray-100 text-gray-500",
)}
>
{isInIframe ? "iframe 模式" : "独立页面"}
</span>
</div>
<div className="flex flex-col gap-2">
<Button
size="sm"
className="w-full bg-blue-50 text-xs text-blue-700 hover:bg-blue-100"
variant="ghost"
onClick={handleTestClipboardCopy}
>
📋
</Button>
<div className="rounded bg-gray-100 px-2 py-1.5 text-[10px] text-gray-600">
{isInIframe
? "将通过 postMessage 请求父页面复制"
: "将直接调用 navigator.clipboard"}
</div>
</div>
</div>
{/* 日志 */} {/* 日志 */}
{log.length > 0 && ( {log.length > 0 && (
<div className="rounded-lg bg-gray-900 p-2"> <div className="rounded-lg bg-gray-900 p-2">

View File

@ -39,6 +39,7 @@ import {
} from "@/core/threads/hooks"; } from "@/core/threads/hooks";
import { pathOfThread, titleOfThread } from "@/core/threads/utils"; import { pathOfThread, titleOfThread } from "@/core/threads/utils";
import { env } from "@/env"; import { env } from "@/env";
import { copyToClipboard } from "@/lib/utils";
export function RecentChatList() { export function RecentChatList() {
const { t } = useI18n(); const { t } = useI18n();
@ -102,7 +103,7 @@ export function RecentChatList() {
const baseUrl = isLocalhost ? VERCEL_URL : window.location.origin; const baseUrl = isLocalhost ? VERCEL_URL : window.location.origin;
const shareUrl = `${baseUrl}/workspace/chats/${threadId}`; const shareUrl = `${baseUrl}/workspace/chats/${threadId}`;
try { try {
await navigator.clipboard.writeText(shareUrl); await copyToClipboard(shareUrl);
toast.success(t.clipboard.linkCopied); toast.success(t.clipboard.linkCopied);
} catch { } catch {
toast.error(t.clipboard.failedToCopyToClipboard); toast.error(t.clipboard.failedToCopyToClipboard);

View File

@ -10,3 +10,26 @@ export const externalLinkClass =
"text-primary underline underline-offset-2 hover:no-underline"; "text-primary underline underline-offset-2 hover:no-underline";
/** Link style without underline by default (e.g. for streaming/loading). */ /** Link style without underline by default (e.g. for streaming/loading). */
export const externalLinkClassNoUnderline = "text-primary hover:underline"; export const externalLinkClassNoUnderline = "text-primary hover:underline";
/**
* Copy text to clipboard, using postMessage when in iframe.
* In iframe context, sends message to parent window to handle clipboard operation.
*/
export async function copyToClipboard(text: string): Promise<void> {
const isInIframe = window.self !== window.top;
const message = {
type: "copyToClipboard",
data: text,
};
if (isInIframe && window.parent) {
// Request parent window to copy
window.parent.postMessage(message, "*");
console.log("[copyToClipboard] iframe mode → postMessage to parent", message);
return;
}
// Direct clipboard access when not in iframe
console.log("[copyToClipboard] direct mode", message);
await navigator.clipboard.writeText(text);
}