"use client"; import React, { useState, useEffect } from "react"; import { useForm, useDocumentInfo } from "@payloadcms/ui"; import { Button } from "@payloadcms/ui"; export function OptimizeButton() { const [isOptimizing, setIsOptimizing] = useState(false); const [instructions, setInstructions] = useState(""); useEffect(() => { if (!isOptimizing) return; const handleBeforeUnload = (e: BeforeUnloadEvent) => { e.preventDefault(); e.returnValue = "Lexical Block-Optimierung läuft noch (dies dauert bis zu 45 Sekunden). Wenn Sie neu laden, bricht der Vorgang ab!"; }; window.addEventListener("beforeunload", handleBeforeUnload); return () => window.removeEventListener("beforeunload", handleBeforeUnload); }, [isOptimizing]); const { fields, setModified, replaceState } = useForm(); const { title } = useDocumentInfo(); const handleOptimize = async () => { // ... gathering draftContent logic const lexicalValue = fields?.content?.value as any; const legacyValue = fields?.legacyMdx?.value as string; let draftContent = legacyValue || ""; 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; }; if (!draftContent && lexicalValue?.root) { draftContent = extractText(lexicalValue.root); } if (!draftContent || draftContent.trim().length < 50) { alert( "Der Entwurf ist zu kurz. Bitte tippe zuerst ein paar Stichpunkte oder einen Rohling ein.", ); return; } setIsOptimizing(true); try { // 2. We inject the title so the AI knows what it's writing about const payloadText = `---\ntitle: "${title}"\n---\n\n${draftContent}`; const res = await fetch("/api/api/mintel-ai/optimize", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ draftContent: payloadText, instructions }), }); const response = await res.json(); if (response.success && response.lexicalAST) { // 3. Inject the new Lexical AST directly into the field form state // We use Payload's useForm hook replacing the value of the 'content' field. replaceState({ ...fields, content: { ...fields.content, value: response.lexicalAST, initialValue: response.lexicalAST, }, }); setModified(true); alert( "🎉 Artikel wurde erfolgreich von der AI optimiert und mit Lexical Components angereichert.", ); } else { alert("❌ Fehler: " + response.error); } } catch (error) { console.error("Optimization failed:", error); alert("Ein unerwarteter Fehler ist aufgetreten."); } finally { setIsOptimizing(false); } }; return (

AI Post Optimizer

Lass Mintel AI deinen Text-Rohentwurf analysieren und automatisch in einen voll formatierten Lexical Artikel mit passenden B2B Komponenten (MemeCards, Mermaids) umwandeln.