"use client"; import React, { useState } from "react"; import { useField, useDocumentInfo, useForm } from "@payloadcms/ui"; export function AiFieldButton({ path, field }: { path: string; field: any }) { const [isGenerating, setIsGenerating] = useState(false); const [instructions, setInstructions] = useState(""); const [showInstructions, setShowInstructions] = useState(false); // Payload hooks const { value, setValue } = useField({ path }); const { title } = useDocumentInfo(); const { fields } = useForm(); const extractText = (lexicalRoot: any): string => { if (!lexicalRoot) return ""; let text = ""; const iterate = (node: any) => { if (node.text) text += node.text + " "; if (node.children) node.children.forEach(iterate); }; iterate(lexicalRoot); return text; }; const handleGenerate = async (e: React.MouseEvent) => { e.preventDefault(); const lexicalValue = fields?.content?.value as any; const legacyValue = fields?.legacyMdx?.value as string; let draftContent = legacyValue || ""; if (!draftContent && lexicalValue?.root) { draftContent = extractText(lexicalValue.root); } setIsGenerating(true); try { // Field name is passed as a label usually, fallback to path const fieldName = typeof field?.label === "string" ? field.label : path; const fieldDescription = typeof field?.admin?.description === "string" ? field.admin.description : ""; const resData = await fetch("/api/api/mintel-ai/generate-single-field", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ documentTitle: (title as string) || "", documentContent: draftContent, fieldName, fieldDescription, instructions, }), }); const res = await resData.json(); if (res.success && res.text) { setValue(res.text); } else { alert("Fehler: " + res.error); } } catch (e: any) { console.error(e) alert("Fehler bei der Generierung."); } finally { setIsGenerating(false); setShowInstructions(false); } }; return (
{showInstructions && (