Files
buzz-sheet/components/public/guide-image-export.tsx
T
gunshiz dc7f61aa6e
CI / Verify (push) Failing after 1m19s
CI / Build immutable images and deploy (push) Has been skipped
fix : overhual unnatural text
2026-09-14 18:27:20 +07:00

162 lines
4.8 KiB
TypeScript

"use client";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { DownloadIcon } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
const EXPORT_WIDTH = 1200;
function withoutNotesFileName(fileName: string): string {
return /\.[^.]+$/u.test(fileName)
? fileName.replace(/(\.[^.]+)$/u, "-without-notes$1")
: `${fileName}-without-notes`;
}
function downloadFileName(value: string): string {
return value.replace(/[\\/:*?"<>|]/gu, "-");
}
export function GuideImageExport({
children,
fileName,
width = EXPORT_WIDTH,
height,
format = "png",
disabled = false,
allowWithoutNotes = true,
captureClassName,
buttonLabel = "ส่งออกภาพ",
}: {
children: ReactNode;
fileName: string;
width?: number;
height?: number;
format?: "png" | "webp";
disabled?: boolean;
allowWithoutNotes?: boolean;
captureClassName?: string;
buttonLabel?: string;
}) {
const captureRef = useRef<HTMLDivElement>(null);
const [captureMode, setCaptureMode] = useState<
"with-notes" | "without-notes" | null
>(null);
const capturing = captureMode !== null;
useEffect(() => {
if (!capturing) return;
let cancelled = false;
async function capture() {
try {
const node = captureRef.current;
if (!node) throw new Error("Capture target is unavailable");
if (captureMode === "without-notes") {
node.querySelectorAll<HTMLElement>("[data-export-note]").forEach((note) => {
note.style.display = "none";
});
// A note can be the only remaining content in the artifact right column.
const right = node.querySelector<HTMLElement>(".artifact-export-right");
if (right) {
const sections = right.querySelectorAll<HTMLElement>(
"[data-artifact-export-section]",
);
const hasVisibleSection = Array.from(sections).some(
(section) => getComputedStyle(section).display !== "none",
);
if (!hasVisibleSection) right.style.display = "none";
}
}
const { domToBlob, waitUntilLoad } = await import("modern-screenshot");
await Promise.all([document.fonts.ready, waitUntilLoad(node)]);
const blob = await domToBlob(node, {
backgroundColor: getComputedStyle(node).backgroundColor,
type: `image/${format}`,
scale: 1,
width,
height,
});
if (cancelled) return;
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.download = downloadFileName(
captureMode === "without-notes"
? withoutNotesFileName(fileName)
: fileName,
);
link.href = url;
document.body.append(link);
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 0);
} catch {
if (!cancelled) toast.error("ส่งออกภาพไม่สำเร็จ กรุณาลองอีกครั้ง");
} finally {
if (!cancelled) setCaptureMode(null);
}
}
void capture();
return () => {
cancelled = true;
};
}, [capturing, captureMode, fileName, format, height, width]);
return (
<>
<div className="flex flex-wrap gap-2">
{(["with-notes", "without-notes"] as const).filter((mode) => allowWithoutNotes || mode === "with-notes").map((mode) => (
<Button
key={mode}
type="button"
variant="outline"
size="sm"
disabled={capturing || disabled}
onClick={() => setCaptureMode(mode)}
>
{captureMode === mode ? (
<Spinner data-icon="inline-start" />
) : (
<DownloadIcon data-icon="inline-start" />
)}
{captureMode === mode
? "กำลังส่งออก…"
: mode === "without-notes"
? "ส่งออกภาพโดยไม่รวมโน้ต"
: buttonLabel}
</Button>
))}
</div>
{capturing
? createPortal(
<div
aria-hidden="true"
className="pointer-events-none fixed top-0 -left-[10000px]"
>
<div
ref={captureRef}
className={cn(
"bg-background p-10 text-foreground",
captureClassName,
)}
style={{ width, height }}
>
{children}
</div>
</div>,
document.body,
)
: null}
</>
);
}