返回 CodeWhale
page-actions.tsx
根目录 / web / components / docs-preview / page-actions.tsx
1 "use client";
2
3 import { useEffect, useRef, useState } from "react";
4 import { Icon } from "@/components/icon";
5
6 export function DocsPreviewPageActions({ markdownHref, sourceHref, labels }: { markdownHref: string; sourceHref: string; labels: { copyPage: string; copied: string; viewMarkdown: string; source: string } }) {
7 const [copiedHref, setCopiedHref] = useState<string | null>(null);
8 const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
9 const copied = copiedHref === markdownHref;
10
11 useEffect(
12 () => () => {
13 if (timer.current) clearTimeout(timer.current);
14 },
15 [],
16 );
17
18 const copy = async () => {
19 if (typeof navigator === "undefined" || !navigator.clipboard) return;
20 try {
21 const response = await fetch(markdownHref);
22 if (!response.ok) return;
23 await navigator.clipboard.writeText(await response.text());
24 setCopiedHref(markdownHref);
25 if (timer.current) clearTimeout(timer.current);
26 timer.current = setTimeout(() => {
27 setCopiedHref((current) => (current === markdownHref ? null : current));
28 }, 1400);
29 } catch {
30 setCopiedHref(null);
31 }
32 };
33
34 return (
35 <div className="dp-actions">
36 <button type="button" className="btn btn-sm btn-secondary" onClick={copy} data-copied={copied}>
37 <Icon name={copied ? "check" : "copy"} className="icon" />
38 <span>{copied ? labels.copied : labels.copyPage}</span>
39 </button>
40 <a className="btn btn-sm btn-ghost" href={markdownHref}>
41 <Icon name="terminal" className="icon" />
42 <span>{labels.viewMarkdown}</span>
43 </a>
44 <a className="btn btn-sm btn-ghost" href={sourceHref} target="_blank" rel="noreferrer">
45 <Icon name="github" className="icon" />
46 <span>{labels.source}</span>
47 </a>
48 <span className="sr-only" aria-live="polite">{copied ? labels.copied : ""}</span>
49 </div>
50 );
51 }
52
52 lines Plain Text