import React, { useEffect, useState } from 'react'; import { __, _n, sprintf } from '@wordpress/i18n'; import { api } from '../api'; import { usableTabs } from '../App'; import { Card, Button, Switch, Badge, Notice, MetricGrid, LineChart, Tabs, Panel, PageState, PageSkeleton } from '../components/ui'; import MatomoPanel from '../components/MatomoPanel'; import ConsentPanel from '../components/ConsentPanel'; function Ga4() { const [data, setData] = useState(null); const [report, setReport] = useState(null); const [properties, setProperties] = useState(null); const [days, setDays] = useState(28); const [busy, setBusy] = useState(false); const [saved, setSaved] = useState(false); const [error, setError] = useState(null); /* * Up here with the rest, not down beside the function that uses it. * * It was declared after `if (!data) return`, so the first render — before * /settings/analytics answers — ran six hooks and the second ran seven. * React counts them and refuses: "Rendered more hooks than during the * previous render" (#310). The whole Measure screen went to the error * boundary the moment the settings arrived, which is to say always. */ const [picked, setPicked] = useState(null); // The raw ids are a repair tool, not the way in. Hidden once a property is // configured, the way Search Console hides its property picker. const [editIds, setEditIds] = useState(false); useEffect(() => { api.get('/settings/analytics').then(setData).catch((e) => setError(e.message)); }, []); useEffect(() => { if (!data?.settings?.property_id) return; setReport(null); api.get(`/analytics/report?days=${days}`).then(setReport).catch((e) => setError(e.message)); }, [data?.settings?.property_id, days]); if (!data) return ; const s = data.settings; const update = (patch) => setData({ ...data, settings: { ...s, ...patch } }); const save = async () => { setBusy(true); setError(null); try { setData(await api.put('/settings/analytics', s)); setSaved(true); setTimeout(() => setSaved(false), 2200); } catch (e) { setError(e.message); } finally { setBusy(false); } }; const loadProperties = async () => { setBusy(true); setError(null); try { const r = await api.get('/analytics/properties'); setProperties(r.properties); } catch (e) { setError(e.message); } finally { setBusy(false); } }; /* * Find this site's own property, rather than listing every property the * account can see. The first real account this met had fifty-five, and a * flat list of fifty-five buttons is not a choice, it is a haystack. The * server matches on the data stream's URL — the only field that actually * says which site a property measures — and hands back the measurement id * with it, so both fields fill from one click. */ /* * Finding the property IS connecting it. * * /gsc/auto-configure writes the property and measurement id on the server * — the same call the Google callback makes, which is why Search Console * needs no second step. This screen used to drop the answer into local * state and then say "Save to keep it", so the one flow that is automatic * everywhere else ended in a form the customer had to submit. Now it * re-reads the saved settings, and the panel switches to its connected * state on its own. */ const autoPick = async () => { setBusy(true); setError(null); setPicked(null); try { const r = await api.post('/gsc/auto-configure', {}); setPicked(r); if (r.ga4_property) { setData(await api.get('/settings/analytics')); setEditIds(false); } } catch (e) { setError(e.message); } finally { setBusy(false); } }; /* * Sign-in first, own credentials second. * * /gsc/connect-url builds an OAuth URL from the site's own Google Cloud * credentials and answers 400 airanksuite_gsc_no_credentials when there are none * — which is every customer who has not opened the Cloud console, i.e. * almost all of them. /gsc/signin-url is the one-click path through the * vendor's connect service, and it is what the Search Console screen has * always offered first. Falling back the other way round means the button * works for both kinds of customer. */ const connectGoogle = async () => { setBusy(true); setError(null); try { let url = ''; try { url = (await api.get('/gsc/signin-url')).url || ''; } catch (e) { url = (await api.get('/gsc/connect-url')).url || ''; } if (!url) throw new Error(__('Google sign-in is not available on this site.', 'ai-rank-suite')); window.location.href = url; } catch (e) { setError(e.message); setBusy(false); } }; const fmt = (n) => (n >= 10000 ? `${(n / 1000).toFixed(1)}k` : String(n)); return (
{error && {error}} {report && ( <>
{report.pages.length > 0 && (
{report.pages.map((p) => ( ))}
{__('Path', 'ai-rank-suite')} {__('Pageviews', 'ai-rank-suite')} {__('Users', 'ai-rank-suite')}
{p.path} {p.pageviews} {p.users}
)} )} {saved && ✓ {__('Saved', 'ai-rank-suite')}} {/* "Tracking on" beside an off switch reads as a status claim, not a control label. Every other module toggle in the product states the current state — Active, Enabled — so this one does too. */} update({ enabled: v })} label={s.enabled ? __('Tracking on', 'ai-rank-suite') : __('Tracking off', 'ai-rank-suite')} />
} >
{/* Three states, one at a time — the same shape as the Search Console panel. Configured: a sentence saying what it is connected to. Connected to Google but no property yet: one button. Not connected: the button that connects, rather than a note telling somebody to go and find another screen. */} {!data.connected ? (
{__('Not connected to Google', 'ai-rank-suite')}

{__('One sign-in covers Search Console and Analytics. Nothing is typed in by hand.', 'ai-rank-suite')}

) : !s.property_id ? (
{__('Google is connected — no property picked yet', 'ai-rank-suite')}

{__('Matches your domain against the data streams in your Google account and saves the match.', 'ai-rank-suite')}

) : (
{sprintf( /* translators: %s: GA4 property id. */ __('Connected to property %s', 'ai-rank-suite'), s.property_id )}

{s.measurement_id ? sprintf( /* translators: %s: GA4 measurement id. */ __('Reports read through your Google sign-in. Tracking tag: %s', 'ai-rank-suite'), s.measurement_id ) : __('Reports read through your Google sign-in. No tracking tag set — reporting works without one.', 'ai-rank-suite')}

)} {(editIds || (data.connected && !s.property_id && properties)) && (
update({ measurement_id: e.target.value })} />
update({ property_id: e.target.value })} />
)} {picked && !picked.ga4_property && ( {__('No property in this Google account points at this site. Use “List all” and pick one, or create a web data stream for this domain in Analytics first.', 'ai-rank-suite')} )} {properties && (
{properties.length === 0 &&

{__('No GA4 properties found for this account.', 'ai-rank-suite')}

} {properties.map((p) => ( ))}
)} update({ anonymize_ip: v })} label={__('Anonymize IP addresses', 'ai-rank-suite')} /> update({ exclude_loggedin: v })} label={__('Do not track logged-in users of these roles', 'ai-rank-suite')} /> {/* The role checkboxes hung loose under the toggle they belong to, at the same indent, in a different control language. A tonal panel indented under the switch says "these are its options". */} {s.exclude_loggedin && (
{data.roles.map((r) => ( ))}
)}

{__('Consent for all analytics tags lives under the “GDPR / Consent” tab — categories, EU/US behaviour and Google Consent Mode v2.', 'ai-rank-suite')}

); } function Reports() { const [data, setData] = useState(null); const [busy, setBusy] = useState(false); const [saved, setSaved] = useState(false); const [sent, setSent] = useState(null); const [error, setError] = useState(null); useEffect(() => { api.get('/settings/reports').then(setData).catch((e) => setError(e.message)); }, []); if (!data) return ; const s = data.settings; const update = (patch) => setData({ ...data, settings: { ...s, ...patch } }); const save = async () => { setBusy(true); setError(null); try { setData(await api.put('/settings/reports', s)); setSaved(true); setTimeout(() => setSaved(false), 2200); } catch (e) { setError(e.message); } finally { setBusy(false); } }; const sendNow = async () => { setBusy(true); setError(null); try { const r = await api.post('/reports/send'); setSent(r); } catch (e) { setError(e.message); } finally { setBusy(false); } }; return (
{error && {error}} {saved && ✓ {__('Saved', 'ai-rank-suite')}} update({ enabled: v })} label={__('Enabled', 'ai-rank-suite')} />
} >
update({ recipients: e.target.value })} />
{__('White label', 'ai-rank-suite')}
update({ brand_name: e.target.value })} />
update({ from_name: e.target.value })} />
update({ logo_url: e.target.value })} />
update({ accent: e.target.value })} />
update({ white_label: v })} label={__('Replace the plugin footer with your brand', 'ai-rank-suite')} />
{__('Preview data ↗', 'ai-rank-suite')} {sent && ✓ {sprintf(_n('Sent to %d recipient', 'Sent to %d recipients', sent.sent, 'ai-rank-suite'), sent.sent)}}
{data.next_run > 0 && (

{sprintf(__('Next report: %s', 'ai-rank-suite'), new Date(data.next_run * 1000).toLocaleString())} {data.sent_at > 0 && sprintf(__(' · last sent %s', 'ai-rank-suite'), new Date(data.sent_at * 1000).toLocaleString())}

)}
); } function Speed() { const [data, setData] = useState(null); const [key, setKey] = useState(''); const [busy, setBusy] = useState(false); const [saved, setSaved] = useState(false); const [error, setError] = useState(null); // Every hook above the early return, always. See Ga4() for the crash this // rule exists to prevent. const [measuring, setMeasuring] = useState(false); useEffect(() => { api.get('/settings/pagespeed').then(setData).catch((e) => setError(e.message)); }, []); if (!data) return ; const save = async () => { setBusy(true); setError(null); try { setData(await api.put('/settings/pagespeed', { strategy: data.settings.strategy, api_key: key })); setKey(''); setSaved(true); setTimeout(() => setSaved(false), 2200); } catch (e) { setError(e.message); } finally { setBusy(false); } }; /* * The screen measures something. * * It used to be a form that stored an API key and a strategy, and every * number it configured appeared somewhere else — inside one page's * analysis panel. So a customer set it up, pressed Save, and the screen * called "PageSpeed Insights" never showed a speed. It measures the front * page on demand now and keeps the last reading. */ const measure = async () => { setMeasuring(true); setError(null); try { const r = await api.post('/pagespeed/home', {}); setData({ ...data, home: r.result }); } catch (e) { setError(e.message); } finally { setMeasuring(false); } }; const home = data.home; const band = (n) => (n >= 90 ? 'good' : n >= 50 ? 'warn' : 'bad'); return (
{error && {error}} {__('Measure now', 'ai-rank-suite')} } > {home ? (
{home.score ?? '—'} {sprintf( /* translators: %s: mobile or desktop. */ __('Performance score, measured as %s', 'ai-rank-suite'), 'desktop' === home.strategy ? __('desktop', 'ai-rank-suite') : __('mobile', 'ai-rank-suite') )} {data.home_url}
) : (

{__('Nothing measured yet. “Measure now” asks Google to load your front page and report what a visitor would wait for.', 'ai-rank-suite')}

)}
✓ {__('Saved', 'ai-rank-suite')}} >
setKey(e.target.value)} />

{__('Works without a key at low volume. Each measurement takes up to a minute — Google runs a real Lighthouse test.', 'ai-rank-suite')}

); } /** * Microsoft Clarity. * * The tag has shipped since the analytics module existed, but its one field * sat inside the Google Analytics panel — so the tab strip listed five tools * and Clarity was not one of them, and people concluded it was missing. It is * its own product with its own account; it gets its own tab. */ function ClarityTab() { const [data, setData] = useState(null); const [draft, setDraft] = useState(null); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); useEffect(() => { api.get('/settings/analytics').then(setData).catch((e) => setError(e.message)); }, []); if (!data) return ; const s = data.settings || {}; const id = (s.clarity_id || '').trim(); const value = draft === null ? s.clarity_id || '' : draft; // The whole settings object goes back, as every other panel here does: // the endpoint replaces what it is given. const save = async (patch) => { setSaving(true); setError(null); try { setData(await api.put('/settings/analytics', { ...s, ...patch })); } catch (e) { setError(e.message); } finally { setSaving(false); } }; return (
{error && {error}} {__('Tag is live', 'ai-rank-suite')} : {__('Not set up', 'ai-rank-suite')} } >
setDraft(e.target.value)} style={{ flex: 1 }} /> {draft !== null && ( )}
{__('In Clarity: Settings → Overview → Project ID. Ten characters, letters and digits.', 'ai-rank-suite')}
{id && (
{__('Open this project in Clarity ↗', 'ai-rank-suite')}
)}
  • {__('Loads only for visitors — logged-in users and the excluded roles never see it, so your own clicks stay out of the recordings.', 'ai-rank-suite')}
  • {__('Waits for consent where consent is required: with the cookie bar on, the tag is held until the visitor accepts the analytics category.', 'ai-rank-suite')}
  • {__('Loads asynchronously from clarity.ms and blocks nothing on the page.', 'ai-rank-suite')}
  • {__('Records interactions, not form values — Clarity masks input content by default.', 'ai-rank-suite')}
); } export default function Analytics({ tab = 'ga4', onTab }) { const views = { ga4: Ga4, matomo: MatomoTab, clarity: ClarityTab, consent: ConsentPanel, reports: Reports, speed: Speed }; const View = views[tab] || Ga4; return (
{/* Scheduled reports are their own Pro module. */} {(() => { const { tabs: anTabs, active: anActive } = usableTabs( [ { id: 'ga4', label: __('Google Analytics', 'ai-rank-suite') }, { id: 'matomo', label: __('Matomo', 'ai-rank-suite') }, { id: 'clarity', label: __('Clarity', 'ai-rank-suite') }, { id: 'consent', label: __('GDPR / Consent', 'ai-rank-suite') }, { id: 'reports', label: __('Reports', 'ai-rank-suite'), needs: 'reports' }, { id: 'speed', label: __('PageSpeed', 'ai-rank-suite') }, ], tab ); if (anActive !== tab) { setTimeout(() => onTab(anActive), 0); } return ; })()}
); } /** * What the plugin keeps in the site's own database, and the controls over * it: how long, refresh now, delete. Sits folded at the bottom of every * analytics tab because it is about all of them at once — and because on a * good day nobody needs to open it. */ function LocalData() { const [data, setData] = useState(null); const [retention, setRetention] = useState(''); const [busy, setBusy] = useState(false); const [saved, setSaved] = useState(false); const [syncError, setSyncError] = useState(null); const [error, setError] = useState(null); useEffect(() => { // A 403 here just means "not an administrator" — then there is no // panel to show, not an error to report. api.get('/analytics/database') .then((d) => { setData(d); setRetention(d.retention_days); }) .catch(() => {}); }, []); if (!data) return ; const ranks = data.tables.find((t) => t.key === 'ranks'); const mentions = data.tables.find((t) => t.key === 'mentions'); const num = (n) => (n == null ? '—' : n); const size = (b) => (b == null ? '—' : b >= 1048576 ? `${(b / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(b / 1024))} KB`); const run = async (fn) => { setBusy(true); setError(null); try { await fn(); } catch (e) { setError(e.message); } finally { setBusy(false); } }; const save = () => run(async () => { const days = Math.min(365, Math.max(30, Number(retention) || 90)); const d = await api.put('/analytics/database', { retention_days: days }); setData(d); setRetention(d.retention_days); setSaved(true); setTimeout(() => setSaved(false), 2200); }); const refresh = () => run(async () => { setSyncError(null); const d = await api.post('/analytics/database/refresh'); setData(d); if (d.sync_error) setSyncError(d.sync_error); }); const purge = (target) => run(async () => setData(await api.post('/analytics/database/purge', { target }))); return (
{error && {error}} {syncError && {sprintf(__('Caches were cleared, but the rank sync reported: %s', 'ai-rank-suite'), syncError)}}
setRetention(e.target.value)} />
{saved && ✓ {__('Saved', 'ai-rank-suite')}}
); } /** * The Matomo tab owns its settings round-trip, because the analytics settings * blob is shared with GA4 and a partial PUT would wipe whichever half was not * on screen. */ function MatomoTab() { const [settings, setSettings] = useState(null); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); useEffect(() => { api .get('/settings/analytics') .then((d) => setSettings(d.settings)) .catch((e) => setError(e.message)); }, []); if (error) return {error}; if (!settings) return {__('Loading…', 'ai-rank-suite')}; const save = async (next) => { setSaving(true); try { // The whole blob, merged — GA4's fields live in the same option and // sending only the Matomo half would clear them. const d = await api.put('/settings/analytics', { ...settings, ...next }); setSettings(d.settings); } finally { setSaving(false); } }; return ; }