import React, { useCallback, useEffect, useRef, useState } from 'react'; import { __, _n, sprintf } from '@wordpress/i18n'; import { api, env, moduleRunning } from '../api'; import { Card, Button, Badge, Notice, Bar, Segmented, Progress } from './ui'; /** * The Full Website Analyzer: how good is this site, page by page, as a whole. * * Built for ten pages and ten thousand alike. Every number is a server-side * aggregate from `/site-analyzer` (one response, two-minute cache); the only * list — the weakest pages — is paged on the server. Pressing the button runs * the existing bulk queue in slices from the browser, refilling itself page * by page, so a huge site finishes without a cron job or a long request, and * a run left half-done in another tab shows up here to be resumed. * * Two barometers because the two scores measure different things: GEO is * whether an answer engine can quote the page; SEO is whether Google can * rank it. The spread beside them exists because an average hides shape. */ const BANDS = ['0–19', '20–39', '40–59', '60–79', '80–100']; const BAND_TONE = ['var(--ars-serious)', 'var(--ars-serious)', 'var(--ars-accent)', 'var(--ars-brand)', 'var(--ars-good)']; const verdictOf = (pct) => (pct >= 80 ? __('Strong', 'ai-rank-suite') : pct >= 60 ? __('Solid', 'ai-rank-suite') : pct >= 40 ? __('Needs work', 'ai-rank-suite') : __('Weak', 'ai-rank-suite')); const colorOf = (pct) => (pct >= 80 ? 'var(--ars-good)' : pct >= 60 ? 'var(--ars-brand)' : pct >= 40 ? 'var(--ars-accent)' : 'var(--ars-serious)'); /** A needle on a graded arc, with the verdict spelled out. */ function Barometer({ value, label, sub, delta }) { const pct = Math.max(0, Math.min(100, Number(value) || 0)); const angle = -90 + (pct / 100) * 180; const C = Math.PI * 70; const color = colorOf(pct); return (
{pct} {typeof delta === 'number' && delta !== 0 && ( 0 ? 'var(--ars-good)' : 'var(--ars-serious)' }}> {delta > 0 ? '▲' : '▼'} {Math.abs(delta)} )} {label} {verdictOf(pct)} {sub && {sub}}
); } function Spread({ dist, label }) { const max = Math.max(1, ...dist); const total = dist.reduce((a, b) => a + b, 0); return (
{label} {/* The caption is the chart's whole meaning, and it used to be nowhere: five numbers over five bars, and the reader had to work out that the columns are score ranges and the numbers are pages. One line says it. */} {__('How many pages fall in each score range', 'ai-rank-suite')}
{dist.map((n, i) => (
{n.toLocaleString()} {/* An empty range is drawn as a hairline in a neutral tone, not as a 3%-tall stub in the band's own colour — a red sliver under "0" reads as "a few bad pages", which is the opposite of the truth. */} {BANDS[i]} {total > 0 ? `${Math.round((n / total) * 100)}%` : '—'}
))}
); } /** Per-type / per-language rows: the same table twice. */ function BreakdownTable({ rows, keyField, labelField, onPick, active }) { return (
{__('Entries', 'ai-rank-suite')} {__('Scored', 'ai-rank-suite')} {__('GEO', 'ai-rank-suite')} {__('SEO', 'ai-rank-suite')} {__('Under 40', 'ai-rank-suite')}
{rows.map((r) => ( ))}
); } /** * "de_DE" is a machine's word for a language. The browser knows the human * one in the reader's own locale, so a German admin reads "Deutsch (de_DE)" * and a code nobody recognises still shows its code rather than nothing. */ function languageName(code, fallback) { const tag = String(code || '').replace('_', '-'); try { const name = new Intl.DisplayNames([document.documentElement.lang || 'en'], { type: 'language' }).of(tag); if (name && name.toLowerCase() !== tag.toLowerCase()) { return `${name} (${code})`; } } catch (e) { /* Intl.DisplayNames is missing or the tag is not one: fall through. */ } return fallback || code; } function Weakest({ postType, lang }) { const [metric, setMetric] = useState('geo'); const [page, setPage] = useState(1); const [data, setData] = useState(null); useEffect(() => { setPage(1); }, [postType, lang, metric]); useEffect(() => { const q = new URLSearchParams({ metric, page: String(page), per_page: '25' }); if (postType) q.set('post_type', postType); if (lang) q.set('lang', lang); api.get(`/site-analyzer/weakest?${q}`).then(setData).catch(() => setData({ items: [], pagination: { pages: 0, total: 0 } })); }, [postType, lang, metric, page]); if (!data) return null; return (
{__('Weakest pages', 'ai-rank-suite')}
{data.items.length === 0 ? ( {__('No scored pages in this scope yet.', 'ai-rank-suite')} ) : (
{data.items.map((it) => (
{it.title || `#${it.id}`} {it.type} {it.geo} {it.seo} {__('Edit', 'ai-rank-suite')} ↗
))}
)} {data.pagination.pages > 1 && (
{__('Page', 'ai-rank-suite')} {page} {__('of', 'ai-rank-suite')} {data.pagination.pages} · {data.pagination.total.toLocaleString()} {__('pages', 'ai-rank-suite')}
)}
); } const fmtSecs = (s) => (s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)} min` : `${(s / 3600).toFixed(1)} h`); export default function SiteAnalyzer({ onRefresh }) { const [board, setBoard] = useState(null); const [status, setStatus] = useState(null); const [scope, setScope] = useState('missing'); const [postType, setPostType] = useState(''); const [lang, setLang] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [tab, setTab] = useState('overview'); const running = useRef(false); const alive = useRef(true); const [startedHere, setStartedHere] = useState(false); // The parent's refresh callback lives in a ref, never in a dependency // list. It is an inline arrow on the dashboard — a new function on every // render — and having it in `load`'s deps made load re-run on every // parent state change, which called onRefresh, which set parent state… // an infinite request loop that hammered /dashboard/kpis and // /score/content until the host reset the connections and every screen // read "Load failed". It is only called after a run finishes. const refreshRef = useRef(onRefresh); refreshRef.current = onRefresh; const load = useCallback(async () => { const q = new URLSearchParams(); if (postType) q.set('post_type', postType); if (lang) q.set('lang', lang); try { setBoard(await api.get(`/site-analyzer${q.toString() ? `?${q}` : ''}`)); } catch (e) { setError(e.message); } }, [postType, lang]); useEffect(() => { load(); }, [load]); useEffect(() => { if (moduleRunning('bulk')) api.get('/bulk/status').then(setStatus).catch(() => {}); return () => { alive.current = false; }; }, []); const pump = useCallback(async () => { if (running.current) return; running.current = true; try { let s = await api.post('/bulk/tick'); setStatus(s); let n = 0; while (s.state === 'running' && alive.current) { s = await api.post('/bulk/tick'); setStatus(s); // Refresh the board every ~40 slices so the barometers move // during a long run, without hammering the aggregate query. if (++n % 40 === 0) await load(); } await load(); if (refreshRef.current) refreshRef.current(); } catch (e) { setError(e.message); } finally { running.current = false; setBusy(false); } }, [load]); /* * The queue is a paid module; scoring is not. * * /bulk/start lives in the Bulk module, which the free edition does not * ship, so this button answered "no route matched the URL and request * method" on every free install — on the screen whose entire purpose is * scoring the site. The analyzer itself is local and free, so where there * is no queue we drive the per-post route directly. Slower, and it needs * the tab to stay open; it works, which the alternative did not. */ const HAS_BULK = !Array.isArray(env.modules) || env.modules.includes('bulk'); const runWithoutQueue = async () => { setBusy(true); setError(null); setStartedHere(true); const seen = new Set(); let pageNo = 1; try { for (;;) { const rows = await api.get( 'all' === scope ? `/content?type=any&per_page=50&page=${pageNo}` : '/content?type=any&filter=unscored&per_page=50&page=1' ); if (!Array.isArray(rows) || rows.length === 0) break; const fresh = rows.filter((r) => !seen.has(r.id)); // Scored rows leave the "unscored" filter, so that scope always // asks for page one. A pass with nothing new left in it means // the remaining rows cannot be scored — stop rather than spin. if (fresh.length === 0 && 'all' !== scope) break; for (const r of fresh) { seen.add(r.id); await api.post(`/content/${r.id}/analyze`); } if ('all' === scope) pageNo += 1; await load(); } await load(); if (refreshRef.current) refreshRef.current(); } catch (e) { setError(e.message); } finally { setBusy(false); } }; const start = async () => { if (!HAS_BULK) { runWithoutQueue(); return; } setBusy(true); setError(null); try { setStartedHere(true); setStatus(await api.post('/bulk/start', { action: 'analyze', scope })); pump(); } catch (e) { setError(e.message); setBusy(false); } }; const cancel = async () => { try { setStatus(await api.post('/bulk/cancel', {})); } catch (e) { setError(e.message); } }; const isRunning = status?.state === 'running'; const isAnalyzeRun = isRunning && status?.action === 'analyze'; const resumable = isAnalyzeRun && !running.current; const b = board; // One point per day the analyzer was read; each series is the same days. const samples = b?.samples || []; const day = (d) => d.day.slice(5).replace('-', '/'); const trend = samples.map((d) => ({ date: day(d), label: day(d), value: d.geo })); const trendSeo = samples.map((d) => ({ date: day(d), label: day(d), value: d.seo })); const first = (arr) => (arr.length > 1 ? arr[0].value : null); const last = (arr) => (arr.length ? arr[arr.length - 1].value : null); const deltaGeo = trend.length > 1 ? last(trend) - first(trend) : null; const deltaSeo = trendSeo.length > 1 ? last(trendSeo) - first(trendSeo) : null; const coverage = b && b.total > 0 ? Math.round((100 * b.analyzed) / b.total) : 0; // Every published page already carries a score: the only work left is a // re-score, so that is what the button does. const nothingUnscored = !!b && (b.total || 0) > 0 && (b.unscored || 0) === 0; useEffect(() => { if (nothingUnscored && scope !== 'all') { setScope('all'); } }, [nothingUnscored, scope]); const coldAreas = (b?.areas || []).filter((a) => a.pages > 0 && a.average !== null).sort((x, y) => x.average - y.average).slice(0, 4); return ( {__('Stop', 'ai-rank-suite')} ) : (
{/* With nothing left unscored, "Unscored only" is a button that cannot work: it returned a red error saying every page already has this. The choice is only offered while it has something to do. */} {nothingUnscored ? null : ( )} {resumable ? ( ) : ( )}
) } > {error && {error}} {isRunning && !isAnalyzeRun && ( {__('Another bulk job is running', 'ai-rank-suite')} ({status.action}). {__('The analyzer waits until it finishes.', 'ai-rank-suite')} )} {(isAnalyzeRun || (startedHere && status?.state === 'done' && status?.action === 'analyze')) && (
{isAnalyzeRun ? __('Scoring pages…', 'ai-rank-suite') : __('Finished', 'ai-rank-suite')} {(status.done || 0).toLocaleString()} {__('of', 'ai-rank-suite')} {(status.total || 0).toLocaleString()} {status.failed ? ` · ${status.failed} ${__('failed', 'ai-rank-suite')}` : ''} {isAnalyzeRun && b?.estimate?.per_post_ms && status.remaining ? ` · ~${fmtSecs(Math.ceil((status.remaining * b.estimate.per_post_ms) / 1000))} ${__('left', 'ai-rank-suite')}` : ''} } total={100} percent={status.progress ?? 0} />
)} {/* Scope: post type and language push into SQL. * * These were two chip rows. A site with ten post types and * fourteen languages — the size this plugin is built for — wrapped * them into four lines of pills before the first number appeared, * and a language chip read "de_DE" rather than "Deutsch". Two * selects hold any number of entries in one line and name the * languages. */} {b && (b.types.length > 1 || b.languages.length > 1) && (
{b.types.length > 1 && ( )} {b.languages.length > 1 && ( )}
)} {!b ? ( {__('Loading…', 'ai-rank-suite')} ) : b.analyzed === 0 ? (
{b.total.toLocaleString()} {__('published pages, none scored yet', 'ai-rank-suite')} {__('The analysis runs on your own server, costs nothing, and can be stopped at any time. Every page gets a AI score for AI search and an SEO score for Google.', 'ai-rank-suite')} {b.estimate.seconds > 0 ? ` ${__('Estimated', 'ai-rank-suite')}: ~${fmtSecs(b.estimate.seconds)}.` : ''}
) : (
{/* One sentence, not five translated fragments glued together: German puts the verb elsewhere, so "of" + "pages scored" + "unscored, ~" could never read as German however well each word was translated. */} {sprintf( /* translators: 1: scored entries, 2: total, 3: what is counted (post type or "entries"), 4: coverage percentage. */ __('%1$s of %2$s %3$s scored (%4$s%%)', 'ai-rank-suite'), b.analyzed.toLocaleString(), b.total.toLocaleString(), postType ? ((b.types || []).find((t) => t.id === postType)?.label || __('entries', 'ai-rank-suite')) : __('entries', 'ai-rank-suite'), coverage )} {b.unscored > 0 && b.estimate.seconds > 0 ? ' · ' + sprintf( /* translators: 1: unscored pages, 2: estimated time. */ __('%1$s unscored, about %2$s', 'ai-rank-suite'), b.unscored.toLocaleString(), fmtSecs(b.estimate.seconds) ) : ''} {b.weak.geo > 0 ? {b.weak.geo.toLocaleString()} {__('GEO under 40', 'ai-rank-suite')} : {__('No GEO page under 40', 'ai-rank-suite')}} {b.strong.geo > 0 && {b.strong.geo.toLocaleString()} {__('GEO 80+', 'ai-rank-suite')}}
{/* * The movement charts live on the dashboard now, as three * full-width cards beside the audit's. Repeating them inside * this card put six "over time" charts on one screen, three * of them saying the same thing at a third of the size. */} 0 ? [{ id: 'langs', label: __('By language', 'ai-rank-suite') }] : []), { id: 'pages', label: __('Weakest pages', 'ai-rank-suite') }, ]} /> {tab === 'overview' && (
{__('Coldest areas across the site', 'ai-rank-suite')} {coldAreas.length === 0 ? ( {__('Area scores appear after the first analysis.', 'ai-rank-suite')} ) : (
{coldAreas.map((a) => (
{a.label} {a.average}
{a.critical.toLocaleString()} {__('critical', 'ai-rank-suite')} · {a.weak.toLocaleString()} {__('weak', 'ai-rank-suite')} · {a.good.toLocaleString()} {__('good', 'ai-rank-suite')} · {a.pages.toLocaleString()} {__('pages', 'ai-rank-suite')} {a.hint && {a.hint}}
))}
)} {__('The same fix repeated across pages beats a perfect single page: start with the coldest area, and the autopilot or "Let AI do" can apply it site-wide.', 'ai-rank-suite')}
)} {tab === 'types' && } {tab === 'langs' && (b.by_lang.length > 1 && b.by_lang.every((l) => l.total === b.by_lang[0].total && l.avg_geo === b.by_lang[0].avg_geo && l.avg_seo === b.by_lang[0].avg_seo) ? (

{sprintf( /* translators: %d: number of languages. */ __('Your translation plugin translates per request, so every entry exists in all %d languages and every language mirrors the source content — a per-language table would repeat the same line %d times. Scores are shown for the source content above.', 'ai-rank-suite'), b.by_lang.length, b.by_lang.length )}

) : ( ))} {tab === 'pages' && }
)}
); }