import { __, _n, sprintf } from '@wordpress/i18n'; import React, { useEffect, useRef, useState } from 'react'; import { api } from '../api'; import { Card, Button, Badge, Notice, MetricGrid, ChipBar, PageState, SegmentBar, Progress } from '../components/ui'; import ScreenVerdict from '../components/ScreenVerdict'; import FirstRun from '../components/FirstRun'; import DataGrid, { useServerQuery } from '../components/DataGrid'; function StatusBadge({ status }) { if (status === 0) return unreachable; if (status >= 500) return {status}; if (status >= 400) return {status}; if (status >= 300) return {status} redirect; return {status}; } export default function LinkChecker() { const [report, setReport] = useState(null); const [scanning, setScanning] = useState(false); /* * Where the results actually are. * * The verdict at the top offers "Show broken links", and its only effect * was to set a filter on a table far below the fold. Nothing moved on the * screen the reader was looking at, which is indistinguishable from a * button that does nothing — and that is how it was reported. Filtering * without going there is only half the action. */ const resultsRef = useRef(null); const showOnly = (value) => { grid.setFilter('status', value); // After the filter, so the grid has re-rendered by the time we move. window.requestAnimationFrame(() => { resultsRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }); }); }; const [error, setError] = useState(null); const [rechecking, setRechecking] = useState(null); const stop = useRef(false); // The full found-links table, server-paged: at fifty thousand links the // browser holds one page, and the old 500-row report cap is gone. const grid = useServerQuery('/linkcheck/links', { orderby: 'status', order: 'desc', filters: { status: 'issues' }, }); const load = () => api.get('/linkcheck/report').then(setReport).catch((e) => setError(e.message)); useEffect(() => { load(); return () => { stop.current = true; }; }, []); const scan = async () => { setScanning(true); setError(null); stop.current = false; try { await api.post('/linkcheck/start'); let job = await api.post('/linkcheck/tick'); while (job.state === 'running' && !stop.current) { if (job.busy || job.error) await new Promise((r) => setTimeout(r, 2000)); job = await api.post('/linkcheck/tick'); // Refresh the report every few ticks so numbers move live. if ((job.checked || 0) % 24 < 8) await load(); setReport((r) => (r ? { ...r, job } : r)); } await load(); grid.refresh(); } catch (e) { setError(e.message); } finally { setScanning(false); } }; const recheck = async (url) => { setRechecking(url); try { setReport(await api.post('/linkcheck/recheck', { url })); grid.refresh(); } catch (e) { setError(e.message); } finally { setRechecking(null); } }; if (!report) return ; const { totals, job } = report; const bad = totals.broken + totals.unreachable; const destinations = report.by_destination || []; const hosts = report.hosts || []; // The path of an internal URL, for the redirect form. const pathOf = (url) => { try { const u = new URL(url, window.location.origin); return u.pathname + u.search; } catch (e) { return url; } }; const toRedirect = (url) => { window.location.hash = `/links/redirects?from=${encodeURIComponent(pathOf(url))}`; }; // No completed scan → no verdict, whatever partial rows exist. const verdict = !report?.snapshot || totals.total === 0 ? null : bad > 0 ? { tone: 'bad', text: sprintf( /* translators: 1: broken links, 2: links checked. */ _n('%1$s of %2$s links is broken.', '%1$s of %2$s links are broken.', bad, 'ai-rank-suite'), bad.toLocaleString(), totals.total.toLocaleString() ) + (destinations.length ? ' ' + sprintf( _n('%s distinct destination.', '%s distinct destinations.', destinations.length, 'ai-rank-suite'), destinations.length === 20 ? '20+' : destinations.length ) : ''), why: __('A dead link is a trust signal pointing the wrong way, for readers and for crawlers. Fix by destination: one redirect or one edited URL clears every page that points there.', 'ai-rank-suite'), action: __('Show broken links', 'ai-rank-suite'), onAction: () => showOnly('broken'), } : totals.redirected > 0 ? { tone: 'warning', text: sprintf(__('No broken links, but %s still go through a redirect hop.', 'ai-rank-suite'), totals.redirected.toLocaleString()), why: __('Each hop costs crawl budget and a few hundred milliseconds. Update them to the final URL when you touch the page.', 'ai-rank-suite'), action: __('Show redirected', 'ai-rank-suite'), onAction: () => showOnly('redirected'), } : { tone: 'good', text: sprintf(__('All %s links are healthy.', 'ai-rank-suite'), totals.total.toLocaleString()), why: __('Scan again after a publishing sprint or a domain change.', 'ai-rank-suite'), }; // Progress is the current phase's own ratio — never a blend of two // phases, which once showed "176/255 · 85%". Phase 1 reads pages, phase 2 // checks the unique destinations; each is reported on its own scale. const snapshot = report?.snapshot || null; const live = report?.running || null; const phaseDone = job.phase === 'extract' ? job.done_posts || 0 : job.checked || 0; const phaseTotal = job.phase === 'extract' ? job.total_posts || 0 : job.total_urls || 0; const progress = job.state === 'running' ? Math.min(100, Math.round((100 * phaseDone) / Math.max(1, phaseTotal))) : null; /* * Every destination checked, and the run not closed yet. * * The scan needs one more tick after the last destination to find nothing * left and write its results, and that tick can be slow — it follows a * batch of HTTP requests, or waits on cron if the tab was closed. What the * reader saw meanwhile was a full bar over the words "checking * destinations 215 / 215", which is indistinguishable from a scan that has * hung. It says what it is doing instead. */ const finishing = job.state === 'running' && phaseTotal > 0 && phaseDone >= phaseTotal; return (
{error && {error}} {/* A running job contains partial extraction/check data. Never turn that partial table into a final health verdict. */} {verdict && !scanning && job.state !== 'running' && } {!report?.snapshot && !scanning && job.state !== 'running' && ( )} {(report?.snapshot || scanning || job.state === 'running') && ( {scanning ? __('Scanning…', 'ai-rank-suite') : totals.total > 0 ? __('Scan again', 'ai-rank-suite') : __('Start scan', 'ai-rank-suite')} } > {progress !== null && (
{/* The numbers below belong to the run in progress and are kept apart from the published snapshot on purpose — a half-checked table is not a health verdict. */} {live && (

{/* * Say which population each number counts. * The bar above counts unique destinations and * this line counts link occurrences, so a page * could read "215 / 215" beside "403 checked" * and look like two answers to one question. * A site links to the same page many times; * that is the whole reason the scan de-duplicates. */} {sprintf(__('This run so far: %1$s links found across your pages, %2$s of them checked, %3$s broken. The bar above counts unique destinations, which is fewer — the same page is often linked many times.', 'ai-rank-suite'), live.found.toLocaleString(), live.checked.toLocaleString(), live.broken.toLocaleString())}{' '} {snapshot ? __('The figures below are still the last completed scan.', 'ai-rank-suite') : __('Nothing is published yet — results appear when this scan completes.', 'ai-rank-suite')} {' '} {/* * This used to promise that closing the tab * pauses the scan, because it did: the browser * was the only thing ticking it, and a run * abandoned at 84 of 215 destinations stayed * there. Cron carries it now, so the tab is * the fast way rather than the only way. */} {__('Leaving this tab open is the quickest way to finish it. Close it and the scan carries on in the background, more slowly.', 'ai-rank-suite')}

)}
)} {snapshot && !scanning && job.state !== 'running' && (

{snapshot.pages ? sprintf(__('Showing the scan completed %1$s over %2$s pages.', 'ai-rank-suite'), new Date((snapshot.finished_at || 0) * 1000).toLocaleString(), snapshot.pages.toLocaleString()) : sprintf(__('Showing the scan completed %s.', 'ai-rank-suite'), new Date((snapshot.finished_at || 0) * 1000).toLocaleString())}

)} {job.state === 'cancelled' && !scanning && (

{snapshot ? __('Last scan was cancelled — the previous completed scan is still shown below.', 'ai-rank-suite') : __('Last scan was cancelled; nothing has been published yet.', 'ai-rank-suite')}

)} {job.state === 'idle' && (

{__('No scan yet — run the first one to see the health of every link on your site.', 'ai-rank-suite')}

)}
)} {/* The four headline numbers in one bordered grid. Only broken links get an accent — a grid where every cell has a colour says nothing. */} {report?.snapshot && totals.total > 0 && ( 0 ? 'var(--ars-c-red-ink)' : undefined, }, ]} /> )} {report?.snapshot && totals.total > 0 && (
)} {(destinations.length > 0 || hosts.length > 0) && (
0 && hosts.length > 0 ? ' lg:grid-cols-2' : ''}`}> {destinations.length > 0 && (
{destinations.map((d) => (
{d.url} {d.pages.toLocaleString()} {d.pages === 1 ? 'page' : 'pages'} {d.internal ? '' : ' · external'} {d.internal && ( )}
))}
)} {hosts.length > 0 && (
{hosts.map((h) => ( ))}
{__('Host', 'ai-rank-suite')} {__('Links', 'ai-rank-suite')} {__('Redirected', 'ai-rank-suite')} {__('Broken', 'ai-rank-suite')}
{h.host} {h.links.toLocaleString()} {h.redirected || '—'} {h.broken || '—'}
)}
)} {report?.snapshot && totals.total > 0 && (
grid.setFilter('status', v)} options={[ { id: 'issues', label: __('Issues', 'ai-rank-suite') }, { id: 'broken', label: __('Broken', 'ai-rank-suite') }, { id: 'redirected', label: __('Redirected', 'ai-rank-suite') }, { id: 'healthy', label: __('Healthy', 'ai-rank-suite') }, { id: '', label: __('All', 'ai-rank-suite') }, ]} /> grid.setFilter('internal', v)} options={[ { id: '', label: __('All', 'ai-rank-suite') }, { id: 'internal', label: __('Internal', 'ai-rank-suite') }, { id: 'external', label: __('External', 'ai-rank-suite') }, ]} /> } columns={[ { id: 'status', label: __('Status', 'ai-rank-suite'), sortable: true, render: (i) => , }, { id: 'url', label: __('Link', 'ai-rank-suite'), sortable: true, render: (i) => (
{i.url}
anchor: “{i.anchor}” {i.redirect && ( <> {' '} → {i.redirect} )}
), }, { id: 'post_title', label: __('Found on', 'ai-rank-suite'), render: (i) => ( {i.post_title || `#${i.post_id}`} ), }, ]} rowActions={(i) => (
{i.internal && (i.status >= 400 || i.status === 0) && ( )}
)} empty={{ title: __('Nothing in this filter', 'ai-rank-suite'), children: __('Every checked link matching this filter is healthy.', 'ai-rank-suite'), }} />
)} {report?.snapshot && totals.total > 0 && (totals.broken + totals.unreachable + totals.redirected) === 0 && ( {__('Every checked link is healthy — nothing to fix.', 'ai-rank-suite')} )}
); }