import React, { useEffect, useRef, useState } from 'react'; import { __, sprintf, _n } from '@wordpress/i18n'; import { api } from '../api'; import { Card, Button, Badge, Notice, Tabs, Switch, ChipBar } from '../components/ui'; import DataGrid, { useServerQuery } from '../components/DataGrid'; export default function Redirects() { const [tab, setTab] = useState('redirects'); const [notFound, setNotFound] = useState(null); const [settings, setSettings] = useState(null); // #/links/redirects?from=/old-path arrives from the link checker with the // broken path already in the form — the row's "Redirect" button used to // land here empty, and the path had to be retyped. const [form, setForm] = useState(() => { const q = (window.location.hash.split('?')[1] || ''); const from = new URLSearchParams(q).get('from') || ''; return { source: from, target: from ? '/' : '', type: 301, regex: false }; }); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [csvBusy, setCsvBusy] = useState(''); const [csvProgress, setCsvProgress] = useState(''); const [csvReport, setCsvReport] = useState(null); const csvRef = useRef(null); // The redirects list is server-paged: with thousands of rows only the // current page ever reaches the browser, and search/sort run in SQL. const grid = useServerQuery('/redirects', { orderby: 'created_at', order: 'desc' }); useEffect(() => { api.get('/404s').then(setNotFound).catch(() => {}); api.get('/settings/redirects').then(setSettings).catch(() => {}); }, []); const add = async () => { setBusy(true); setError(null); try { await api.post('/redirects', form); setForm({ source: '', target: '', type: 301, regex: false }); grid.refresh(); } catch (e) { setError(e.message); } finally { setBusy(false); } }; const remove = async (id) => { try { await api.del(`/redirects/${id}`); grid.refresh(); } catch (e) { setError(e.message); } }; const fixNotFound = (path) => { setForm({ source: path, target: '/', type: 301 }); setTab('redirects'); window.scrollTo({ top: 0, behavior: 'smooth' }); }; const saveSetting = async (patch) => { const next = { ...settings, ...patch }; setSettings(next); try { await api.put('/settings/redirects', next); } catch (e) { setError(e.message); } }; /** * A migration arrives as a spreadsheet. The import previews first — a * three-thousand-row file that turns out to have the columns the wrong way * round should say so before it writes anything. */ /* * A file is applied a slice at a time. * * The server takes two thousand rows per request and answers with where to * carry on, because fifty thousand SELECT-and-write pairs do not fit in one * PHP time limit and a timeout used to leave half a migration in place with * nothing on screen saying which half. The totals here are the sum of the * slices, so the report reads the same as it always did. */ const importSlices = async (content, format, opts, onProgress) => { const total = { created: 0, updated: 0, skipped: 0, errors: [], total: 0 }; let offset = 0; for (let guard = 0; guard < 200; guard += 1) { // eslint-disable-next-line no-await-in-loop const part = await api.post('/redirects/import', { content, format, ...opts, offset }); total.created += Number(part.created || 0); total.updated += Number(part.updated || 0); total.skipped += Number(part.skipped || 0); total.errors = total.errors.concat(part.errors || []); total.total = Number(part.total || 0); offset = Number(part.offset || 0); onProgress?.(offset, total.total); if (!Number(part.remaining)) break; } return total; }; const importCsv = async (file) => { setCsvBusy('import'); setError(null); try { const content = await file.text(); const format = /\.json$/i.test(file.name) ? 'json' : 'csv'; const preview = await importSlices(content, format, { dry_run: true }, (done, all) => setCsvProgress(all > 0 ? `Checking ${done.toLocaleString()} of ${all.toLocaleString()} rows…` : '')); setCsvProgress(''); const question = sprintf( /* translators: 1: rules to add, 2: rules to update, 3: rows that were refused. */ __('%1$s to add, %2$s to update, %3$s refused. Import them?', 'ai-rank-suite'), Number(preview.created).toLocaleString(), Number(preview.updated).toLocaleString(), Number((preview.errors || []).length).toLocaleString() ); if (!window.confirm(question)) { setCsvReport({ ...preview, preview: true }); return; } const result = await importSlices(content, format, { overwrite: preview.updated > 0 }, (done, all) => setCsvProgress(all > 0 ? `Imported ${done.toLocaleString()} of ${all.toLocaleString()} rows…` : '')); setCsvProgress(''); setCsvReport(result); grid.reload?.(); } catch (e) { setError(e.message); } finally { setCsvBusy(''); setCsvProgress(''); if (csvRef.current) csvRef.current.value = ''; } }; const exportCsv = async () => { setCsvBusy('export'); try { const { csv } = await api.get('/redirects/export'); const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8' })); a.download = `ai-rank-suite-redirects-${new Date().toISOString().slice(0, 10)}.csv`; a.click(); URL.revokeObjectURL(a.href); } catch (e) { setError(e.message); } finally { setCsvBusy(''); } }; return (
{__('No 404s logged yet.', 'ai-rank-suite')}
{__('From now on, every request to a path that does not exist on this site is recorded here with how often it was hit and when it was last seen: a visitor following a stale link, a crawler still asking for a page you deleted, a typo in somebody else\'s link to you. Each one is a lost visit until it has a redirect, and the Redirects tab is where it gets one. Old entries are pruned after the number of days set under Settings, Data.', 'ai-rank-suite')}
| {__('Path', 'ai-rank-suite')} | {__('Hits', 'ai-rank-suite')} | {__('Last seen', 'ai-rank-suite')} | |
|---|---|---|---|
| {n.path} | {n.hits} | {n.last_hit} |