mirror of
https://github.com/snowykami/neo-blog.git
synced 2025-09-26 11:06:23 +00:00
feat: 添加代码块复制功能,支持剪贴板操作并提供用户反馈
This commit is contained in:
@ -1,97 +1,95 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import copyToClipboard from '@/lib/clipboard';
|
||||||
|
|
||||||
function extractText(node: React.ReactNode): string {
|
function extractText(node: React.ReactNode): string {
|
||||||
if (typeof node === "string") return node;
|
if (typeof node === "string") return node;
|
||||||
if (Array.isArray(node)) return node.map(extractText).join("");
|
if (Array.isArray(node)) return node.map(extractText).join("");
|
||||||
if (
|
if (
|
||||||
React.isValidElement(node) &&
|
React.isValidElement(node) &&
|
||||||
node.props &&
|
node.props &&
|
||||||
typeof node.props === "object" &&
|
typeof node.props === "object" &&
|
||||||
"children" in node.props
|
"children" in node.props
|
||||||
) {
|
) {
|
||||||
return extractText(node.props.children as React.ReactNode);
|
return extractText(node.props.children as React.ReactNode);
|
||||||
}
|
}
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CodeBlock(props: React.ComponentPropsWithoutRef<"pre">) {
|
export default function CodeBlock(props: React.ComponentPropsWithoutRef<"pre">) {
|
||||||
let className: string | undefined = undefined;
|
const t = useTranslations('CodeBlock');
|
||||||
const child = props.children as React.ReactElement<{ className?: string; children?: React.ReactNode }> | undefined;
|
let className: string | undefined = undefined;
|
||||||
if (
|
const child = props.children as React.ReactElement<{ className?: string; children?: React.ReactNode }> | undefined;
|
||||||
child &&
|
if (
|
||||||
typeof child === "object" &&
|
child &&
|
||||||
"props" in child &&
|
typeof child === "object" &&
|
||||||
child.props.className
|
"props" in child &&
|
||||||
) {
|
child.props.className
|
||||||
className = child.props.className as string | undefined;
|
) {
|
||||||
}
|
className = child.props.className as string | undefined;
|
||||||
let language = "";
|
}
|
||||||
if (className) {
|
let language = "";
|
||||||
const match = className.match(/language-(\w+)/);
|
if (className) {
|
||||||
if (match) {
|
const match = className.match(/language-(\w+)/);
|
||||||
language = match[1];
|
if (match) {
|
||||||
}
|
language = match[1];
|
||||||
}
|
|
||||||
let codeContent = "";
|
|
||||||
if (
|
|
||||||
child &&
|
|
||||||
typeof child === "object" &&
|
|
||||||
"props" in child
|
|
||||||
) {
|
|
||||||
codeContent = extractText(child.props.children);
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
let codeContent = "";
|
||||||
|
if (
|
||||||
|
child &&
|
||||||
|
typeof child === "object" &&
|
||||||
|
"props" in child
|
||||||
|
) {
|
||||||
|
codeContent = extractText(child.props.children);
|
||||||
|
}
|
||||||
|
|
||||||
function handleCopy(e: React.MouseEvent<HTMLButtonElement>) {
|
async function handleCopy(e: React.MouseEvent<HTMLButtonElement>) {
|
||||||
if (typeof window !== "undefined" && window.navigator?.clipboard) {
|
try {
|
||||||
window.navigator.clipboard.writeText(codeContent);
|
const ok = await copyToClipboard(codeContent);
|
||||||
} else {
|
if (ok) toast.success(t("copy_success"));
|
||||||
const textarea = document.createElement("textarea");
|
else toast.error(t("copy_failed") || 'Copy failed');
|
||||||
textarea.value = codeContent;
|
} catch (err) {
|
||||||
document.body.appendChild(textarea);
|
console.error('copy failed', err);
|
||||||
textarea.select();
|
toast.error(t("copy_failed") || 'Copy failed');
|
||||||
document.execCommand("copy");
|
|
||||||
document.body.removeChild(textarea);
|
|
||||||
}
|
|
||||||
toast.success("已经复制", {
|
|
||||||
description: "代码已复制到剪贴板",
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative my-6 rounded-lg overflow-hidden bg-[#f5f5f7] dark:bg-[#23272f] border border-gray-200 dark:border-gray-700 shadow-sm group">
|
<div className="relative my-6 rounded-2xl overflow-hidden bg-[#f5f5f7] dark:bg-[#23272f] border border-gray-200 dark:border-gray-700 shadow-sm group">
|
||||||
<div className="flex items-center h-8 px-3 bg-[#e5e7eb] dark:bg-[#23272f] border-b border-gray-200 dark:border-gray-700 relative">
|
<div className="flex items-center h-8 px-3 bg-[#e5e7eb] dark:bg-[#23272f] border-b border-gray-200 dark:border-gray-700 relative">
|
||||||
<span className="w-3 h-3 rounded-full bg-red-400 mr-2" />
|
<span className="w-3.5 h-3.5 rounded-full bg-red-400 mr-2" />
|
||||||
<span className="w-3 h-3 rounded-full bg-yellow-400 mr-2" />
|
<span className="w-3.5 h-3.5 rounded-full bg-yellow-400 mr-2" />
|
||||||
<span className="w-3 h-3 rounded-full bg-green-400" />
|
<span className="w-3.5 h-3.5 rounded-full bg-green-400" />
|
||||||
{language && (
|
{language && (
|
||||||
<span className="absolute left-1/2 -translate-x-1/2 text-xs text-gray-500 dark:text-gray-400 font-mono">
|
<span className="absolute left-1/2 -translate-x-1/2 text-xs text-gray-500 dark:text-gray-400 font-mono">
|
||||||
{language}
|
{language}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<div
|
<div
|
||||||
className="absolute right-3 top-1/2 -translate-y-1/2 flex space-x-2
|
className="absolute right-3 top-1/2 -translate-y-1/2 flex space-x-2
|
||||||
opacity-100
|
opacity-100
|
||||||
group-hover:opacity-100
|
group-hover:opacity-100
|
||||||
sm:opacity-0 sm:group-hover:opacity-100
|
sm:opacity-0 sm:group-hover:opacity-100
|
||||||
transition-opacity"
|
transition-opacity"
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="px-2 py-1 rounded text-xs bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 border border-gray-300 dark:border-gray-600"
|
className="px-2 py-1 rounded text-xs bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 border border-gray-300 dark:border-gray-600"
|
||||||
title="复制代码"
|
title="复制代码"
|
||||||
onClick={handleCopy}
|
onClick={handleCopy}
|
||||||
tabIndex={-1}
|
tabIndex={-1}
|
||||||
>
|
>
|
||||||
复制
|
{t("copy")}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<pre
|
|
||||||
className="overflow-x-auto bg-transparent text-sm text-gray-800 dark:text-gray-100"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
</div>
|
||||||
|
<pre
|
||||||
|
className="overflow-x-auto bg-transparent text-sm text-gray-800 dark:text-gray-100"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
65
web/src/lib/clipboard.ts
Normal file
65
web/src/lib/clipboard.ts
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
/**
|
||||||
|
* copyToClipboard
|
||||||
|
* - 优先使用 navigator.clipboard.writeText(异步)
|
||||||
|
* - 如果不可用或失败,使用隐藏的 textarea + document.execCommand('copy') 回退
|
||||||
|
* - 尝试在回退时恢复原始 selection
|
||||||
|
*
|
||||||
|
* 返回 Promise<boolean>,表示是否成功复制
|
||||||
|
*/
|
||||||
|
export async function copyToClipboard(text: string): Promise<boolean> {
|
||||||
|
// 优先使用现代 Clipboard API
|
||||||
|
try {
|
||||||
|
if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// 忽略并回退到老方法
|
||||||
|
// console.warn('navigator.clipboard.writeText failed, falling back to execCommand', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回退到 textarea + execCommand 方案(在许多旧浏览器上可用)
|
||||||
|
if (typeof document === 'undefined') return false;
|
||||||
|
|
||||||
|
const textarea = document.createElement('textarea');
|
||||||
|
textarea.value = text;
|
||||||
|
// 防止页面滚动,把元素放到不可见但可选中的位置
|
||||||
|
textarea.setAttribute('readonly', '');
|
||||||
|
textarea.style.position = 'fixed';
|
||||||
|
textarea.style.left = '-9999px';
|
||||||
|
textarea.style.top = '0';
|
||||||
|
textarea.style.opacity = '0';
|
||||||
|
document.body.appendChild(textarea);
|
||||||
|
|
||||||
|
// 保存当前 selection(以便恢复)
|
||||||
|
const selection = document.getSelection();
|
||||||
|
let originalRange: Range | null = null;
|
||||||
|
if (selection && selection.rangeCount > 0) {
|
||||||
|
originalRange = selection.getRangeAt(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea.select();
|
||||||
|
textarea.setSelectionRange(0, textarea.value.length);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 使用 any 绕开 TypeScript 中关于 execCommand 的弃用声明
|
||||||
|
const successful = (document as any).execCommand('copy');
|
||||||
|
// 清理并恢复 selection
|
||||||
|
document.body.removeChild(textarea);
|
||||||
|
if (selection) {
|
||||||
|
selection.removeAllRanges();
|
||||||
|
if (originalRange) selection.addRange(originalRange);
|
||||||
|
}
|
||||||
|
return Boolean(successful);
|
||||||
|
} catch (err) {
|
||||||
|
// 清理并恢复 selection
|
||||||
|
document.body.removeChild(textarea);
|
||||||
|
if (selection) {
|
||||||
|
selection.removeAllRanges();
|
||||||
|
if (originalRange) selection.addRange(originalRange);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default copyToClipboard;
|
@ -16,6 +16,11 @@
|
|||||||
"error": "验证失败",
|
"error": "验证失败",
|
||||||
"success": "恭喜呀,你是个人!"
|
"success": "恭喜呀,你是个人!"
|
||||||
},
|
},
|
||||||
|
"CodeBlock": {
|
||||||
|
"copy": "复制",
|
||||||
|
"copy_success": "已经复制到剪贴板",
|
||||||
|
"copy_failed": "复制失败,请手动复制"
|
||||||
|
},
|
||||||
"Comment": {
|
"Comment": {
|
||||||
"collapse_replies": "收起",
|
"collapse_replies": "收起",
|
||||||
"comment": "评论",
|
"comment": "评论",
|
||||||
@ -56,7 +61,11 @@
|
|||||||
},
|
},
|
||||||
"Login": {
|
"Login": {
|
||||||
"captcha_error": "验证错误,请重试。",
|
"captcha_error": "验证错误,请重试。",
|
||||||
|
"fetch_captcha_config_failed": "获取验证码失败,请稍后重试。",
|
||||||
|
"fetch_oidc_configs_failed": "获取第三方身份提供者配置失败。",
|
||||||
"logging": "正在登录...",
|
"logging": "正在登录...",
|
||||||
|
"login_success": "登录成功!",
|
||||||
|
"login_failed": "登录失败",
|
||||||
"welcome": "欢迎回来",
|
"welcome": "欢迎回来",
|
||||||
"with_oidc": "使用第三方身份提供者",
|
"with_oidc": "使用第三方身份提供者",
|
||||||
"or_continue_with_local_account": "或使用用户名和密码",
|
"or_continue_with_local_account": "或使用用户名和密码",
|
||||||
@ -69,7 +78,6 @@
|
|||||||
"by_logging_in_you_agree_to_our": "登录即表示你同意我们的",
|
"by_logging_in_you_agree_to_our": "登录即表示你同意我们的",
|
||||||
"terms_of_service": "服务条款",
|
"terms_of_service": "服务条款",
|
||||||
"and": "和",
|
"and": "和",
|
||||||
"privacy_policy": "隐私政策",
|
"privacy_policy": "隐私政策"
|
||||||
"login_failed": "登录失败,请检查你的凭据。"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
Reference in New Issue
Block a user