import React, { useCallback, useEffect, useRef, useState } from 'react'; import { __, _n, sprintf } from '@wordpress/i18n'; import { createPortal } from 'react-dom'; import { api, env, moduleRunning } from '../api'; /* * Everything that spends an AI call needs the AI module to be in this build. * The free edition ships without it, and every one of these buttons called an * /ai/ route regardless — producing "no route matched the URL and request * method" where a description was supposed to appear. A button that can only * fail should not be on the screen. */ const HAS_AI = !Array.isArray(env.modules) || env.modules.includes('ai'); const HAS_BULK = !Array.isArray(env.modules) || env.modules.includes('bulk'); import { Card, Button, Badge, Bar, ScorePill, StatusBadge, Switch, LengthMeter, FilterBar, ChipBar, ScoreRing } from '../components/ui'; import { IconExternal, IconRefresh, IconX, IconSparkle, IconCode } from '../components/icons'; import SchemaEditor from '../components/SchemaEditor'; import KeywordEditor from '../components/KeywordEditor'; import SnippetPreview from '../components/SnippetPreview'; import AdvancedSeo from '../components/AdvancedSeo'; import CheckList from '../components/CheckList'; import HeadTab from '../components/HeadTab'; import ReportTab from '../components/ReportTab'; import AiReview from '../components/AiReview'; import AiTools from '../components/AiTools'; /** * The fields the drawer's Save writes. * * Comparing against this is how "you have unsaved changes" stays honest: a * dirty flag set by every keystroke would fire on a keystroke that was undone, * and one set by nothing at all is what lets people close the panel and lose * the description they just wrote. */ const snapshot = (it) => JSON.stringify({ seo_title: it?.seo_title || '', seo_desc: it?.seo_desc || '', exclude: !!it?.exclude, robots: it?.robots || [], keywords: it?.keywords || {}, canonical: it?.canonical || '', breadcrumb_title: it?.breadcrumb_title || '', previews: it?.previews || {}, social: it?.social || {}, }); function Drawer({ id, onClose, onChanged, onNavigate, position }) { const [item, setItem] = useState(null); const [busy, setBusy] = useState(false); const [aiBusy, setAiBusy] = useState(null); // Concrete rewrite suggestions from the coach, shown where they were asked for. const [coach, setCoach] = useState(null); const [saved, setSaved] = useState(false); const [error, setError] = useState(null); const [faqs, setFaqs] = useState([]); const [faqSaved, setFaqSaved] = useState(false); const [schema, setSchema] = useState(null); const [schemaSaved, setSchemaSaved] = useState(false); const [tab, setTab] = useState('optimize'); const [maxed, setMaxed] = useState(false); // The head plan is fetched with the record rather than when the tab is // opened, so the tab can carry a count before anybody has looked at it. const [head, setHead] = useState(null); // A snapshot of the fields the footer's Save writes, taken every time the // server hands us a fresh record. Anything diverging from it is unsaved. const [clean, setClean] = useState(null); const bodyRef = useRef(null); useEffect(() => { setItem(null); setFaqs([]); setSchema(null); setHead(null); setTab('optimize'); api .get(`/content/${id}`) .then((next) => { setItem(next); setClean(snapshot(next)); }) .catch((e) => setError(e.message)); api.get(`/schema/post/${id}`).then(setSchema).catch(() => {}); api.get(`/content/${id}/head`).then(setHead).catch(() => {}); // Saved FAQs must come back when the page is reopened — otherwise the // panel looks empty and the next generation silently replaces them. api.get(`/ai/faq/${id}`).then((r) => setFaqs(r.items || [])).catch(() => {}); }, [id]); const dirty = clean !== null && item !== null && snapshot(item) !== clean; // One confirm, in one place, rather than at each exit — leaving by Escape, // by the X, by the scrim and by Alt+arrow are the same decision. const confirmLeave = () => !dirty || // eslint-disable-next-line no-alert window.confirm(__('You have unsaved changes on this page. Leave without saving?', 'ai-rank-suite')); const close = () => { if (confirmLeave()) onClose(); }; const step = (delta) => { if (!onNavigate || !position) return; const target = position.index + delta; if (target < 0 || target >= position.total) return; if (confirmLeave()) onNavigate(target); }; // Escape closes the sheet; every tab switch returns the body to the top so // the reader never lands mid-section. useEffect(() => { const onKey = (e) => { if (e.key === 'Escape') { close(); return; } // Alt+↑/↓ moves to the previous or next page in the list without // closing — reviewing forty pages should not mean forty round trips // through the table. if (e.altKey && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) { e.preventDefault(); step(e.key === 'ArrowDown' ? 1 : -1); } }; document.addEventListener('keydown', onKey); return () => document.removeEventListener('keydown', onKey); // eslint-disable-next-line react-hooks/exhaustive-deps }, [dirty, position?.index, position?.total]); useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = 0; }, [tab]); const saveSchema = async () => { setAiBusy('schema'); setError(null); try { const next = await api.put(`/schema/post/${id}`, { items: schema.items }); setSchema(next); setSchemaSaved(true); setTimeout(() => setSchemaSaved(false), 2200); } catch (e) { setError(e.message); } finally { setAiBusy(null); } }; // Title suggestions come back as a list; the drawer applies the first and // keeps the rest available in the full editor rather than opening a picker // inside a picker. /* * Is the AI module in this build at all? * * The free edition ships without it, and these two buttons called * /ai/titles and /ai/describe regardless — so pressing "Write with AI" on * the free edition produced "no route matched the URL and request method" * next to the field it was supposed to fill. The fields themselves were * always editable; the button beside them was not. */ const aiTitle = async () => { setAiBusy('title'); setError(null); try { const r = await api.post(`/ai/titles/${id}`); const first = (r.titles || [])[0]; if (first) setItem((it) => ({ ...it, seo_title: first })); } catch (e) { setError(e.message); } finally { setAiBusy(null); } }; const aiDescribe = async () => { setAiBusy('desc'); setError(null); try { const r = await api.post(`/ai/describe/${id}`); setItem((it) => ({ ...it, seo_desc: r.meta_description })); } catch (e) { setError(e.message); } finally { setAiBusy(null); } }; /** * "Fix with AI" on a single failing check. * * The three title checks and the keyword-in-title one all have the same * remedy — a better title — so they route to the title generator; the ones * about the opening and the body route to the coach, which is already * grounded in the failing checks. A check with no route does nothing rather * than pretending: an AI button that produces a shrug is worse than no * button. */ const fixCheck = async (check) => { const titleFixes = ['title_number', 'title_sentiment', 'title_power', 'kw_title_start']; setAiBusy(check.id); setError(null); try { if (titleFixes.includes(check.id)) { const r = await api.post(`/ai/titles/${id}`); const first = (r.titles || [])[0]; if (first) { setItem((it) => ({ ...it, seo_title: first })); setTab('optimize'); } return; } const r = await api.post(`/ai/improve/${id}`); setCoach({ check: check.id, suggestions: r.suggestions || r.improvements || [] }); } catch (e) { setError(e.message); } finally { setAiBusy(null); } }; const aiFaq = async () => { setAiBusy('faq'); setError(null); try { const r = await api.post(`/ai/faq/${id}`); setFaqs(r.items || []); } catch (e) { setError(e.message); } finally { setAiBusy(null); } }; const saveFaq = async () => { setAiBusy('faq-save'); try { await api.put(`/ai/faq/${id}`, { items: faqs }); setFaqSaved(true); setTimeout(() => setFaqSaved(false), 2200); } catch (e) { setError(e.message); } finally { setAiBusy(null); } }; /** * An AI proposal was applied, or undone. * * Unlike the fields above, this path has already written to the database: * /ai/suggest/{id}/apply calls update_post_meta itself and returns the * values it stored. So there is nothing to save, and two things that were * being missed. * * The list was never told. It merged the drawer's changes only when the * footer's Save ran, so applying a proposal updated the drawer and left the * row behind it showing the old T/D/K dots and the old title — a change * that had genuinely been made looked like it had not, which is exactly * how it was reported. * * And the drawer went on believing it was dirty, because `clean` was never * moved to the new values. Closing it then warned about losing changes that * were already stored, and pressing Save wrote the same strings again. * * Re-reading the row rather than merging the two fields is deliberate: the * list renders has_title, has_desc and the scores, and none of those are in * the apply response. Patching in seo_title alone would leave the dots * wrong, which is the same bug one layer down. */ const applied = async (v) => { // Show the new text at once; the round trip below is for the rest. setItem((it) => ({ ...it, ...v })); try { /* * Everything the change touched, not only the field it was written * into. * * A new SEO title changes what the page emits in its head, and it * changes what the audit should say about the title — so the Head * tab and the checks both go stale the moment it is applied. The * first version of this reloaded only the item, which left the Head * tab showing the previous title and looked exactly like a change * that had not been adopted. Schema is reloaded too, because a * rewrite alters the body that schema is generated from. * * The item is awaited because the drawer's clean snapshot and the * list row both depend on it; the other two are allowed to fail * without taking the apply down with them. */ const next = await api.get(`/content/${id}`); setItem(next); setClean(snapshot(next)); onChanged(next); api.get(`/content/${id}/head`).then(setHead).catch(() => {}); api.get(`/schema/post/${id}`).then(setSchema).catch(() => {}); } catch { // The write already succeeded, so a failed re-read must not look // like a failed apply. The drawer keeps the new text and the list // catches up when it next loads. } }; const run = async (fn) => { setBusy(true); setError(null); try { const next = await fn(); setItem(next); setClean(snapshot(next)); onChanged(next); } catch (e) { setError(e.message); } finally { setBusy(false); } }; // Everything the drawer can edit goes in one payload — a partial save was // silently dropping keywords and robots directives. const save = () => run(async () => { const next = await api.put(`/content/${id}/meta`, { seo_title: item.seo_title, seo_desc: item.seo_desc, exclude: item.exclude, robots: item.robots || [], keywords: item.keywords || {}, canonical: item.canonical || '', slug: item.slug || '', breadcrumb_title: item.breadcrumb_title || '', previews: item.previews || {}, social: item.social || {}, }); setSaved(true); setTimeout(() => setSaved(false), 2200); return next; }); const groups = [ { id: 'geo', label: __('GEO — AI readiness', 'ai-rank-suite') }, { id: 'keyword', label: __('Focus keyword', 'ai-rank-suite') }, { id: 'seo', label: __('SEO — classic search', 'ai-rank-suite') }, ]; const failing = item ? item.checks.filter((c) => c.status !== 'pass').length : 0; const headIssues = head ? head.issues.filter((i) => i.level !== 'info').length : 0; const wide = tab === 'schema' || tab === 'keywords'; const TABS = [ { id: 'optimize', label: __('Optimize', 'ai-rank-suite') }, { id: 'report', label: __('Full report', 'ai-rank-suite') }, { id: 'preview', label: __('Preview', 'ai-rank-suite') }, { id: 'head', label: __('Head', 'ai-rank-suite'), count: headIssues, tone: 'quiet' }, { id: 'keywords', label: __('Keywords', 'ai-rank-suite') }, { id: 'schema', label: __('Schema', 'ai-rank-suite') }, { id: 'faq', label: __('FAQ', 'ai-rank-suite'), count: faqs.length || 0, tone: 'quiet' }, { id: 'advanced', label: __('Advanced', 'ai-rank-suite') }, { id: 'checks', label: __('Checks', 'ai-rank-suite'), count: failing }, ]; // Rendered into #airanksuite-root rather than in place. A fixed-position panel must // answer to the viewport, and any ancestor with a transform, filter or // containment silently takes that job away from it. Portalling to the app // root keeps the CSS custom properties (they are declared on #airanksuite-root) // while putting the sheet out of reach of whatever the page does next. return createPortal( <> {position.index + 1}/{position.total} )} {dirty && ( {__('Unsaved', 'ai-rank-suite')} )}
{TABS.map((t) => ( ))}
{tab === 'optimize' && (
{/* The reviewed path: propose, compare, edit, apply, undo. The "Write with AI" buttons below stay for a quick single field. */} { // Hand the proposal to the schema editor as a new item; // saving is the editor's own button, so nothing is // written until the reviewer says so there. setSchema((sc) => ({ ...(sc || {}), items: [...((sc && sc.items) || []), entry] })); setTab('schema'); }} onTranslate={(t) => setItem((it) => ({ ...it, seo_title: t.title, seo_desc: t.description }))} // Rewrite, alt text and links write straight to the page, // so the same re-read the proposal path uses applies here. onServerEdit={() => applied({})} />
{HAS_AI && ( )}
setItem({ ...item, seo_title: e.target.value })} />
{HAS_AI && ( )}