import { useEffect, useState } from 'react'; import apiFetch from '@wordpress/api-fetch'; import { Button } from '../../components/ui/button'; import { Input } from '../../components/ui/input'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '../../components/ui/select'; import { FieldHeader } from './fields'; interface PostRedirectState { path: string; redirect: { id: number; url_to: string; header_code: number; active: boolean; sources: number; } | null; } const CODES = [ { value: '301', label: '301 Moved for good' }, { value: '302', label: '302 Moved for now' }, { value: '307', label: '307 Moved for now, same method' }, { value: '410', label: '410 Gone for good' }, { value: '451', label: '451 Taken down for legal reasons' }, ]; const gone = (code: string): boolean => code === '410' || code === '451'; /** * Advanced → Redirect: where the page's address sends visitors instead of * the page, kept in the Redirects module like any other rule, so it shows * and can be changed there too. */ export const PostRedirect = ({ postId, appUrl, }: { postId: number; appUrl: string; }): JSX.Element => { const [state, setState] = useState(null); const [code, setCode] = useState('301'); const [destination, setDestination] = useState(''); const [editing, setEditing] = useState(false); const [busy, setBusy] = useState(false); const [confirming, setConfirming] = useState(false); const [message, setMessage] = useState(''); const path = `/recomaze/v1/seo/redirects/post/${postId}`; const show = (next: PostRedirectState): void => { setState(next); setCode(String(next.redirect?.header_code ?? 301)); setDestination(next.redirect?.url_to ?? ''); setEditing(false); setConfirming(false); }; useEffect(() => { apiFetch({ path }) .then(show) .catch(() => setState(null)); }, [path]); const send = async (method: 'POST' | 'DELETE'): Promise => { setBusy(true); setMessage(''); try { show( await apiFetch({ path, method, data: method === 'POST' ? { url_to: destination.trim(), header_code: Number(code) } : undefined, }) ); } catch (reason) { setMessage((reason as Error).message); } finally { setBusy(false); } }; if (!state) { return <>; } const current = state.redirect; return (
{!current && !editing ? ( ) : current && !editing ? (

{state.path}{' '} {gone(String(current.header_code)) ? `answers ${current.header_code}: the page is gone.` : `sends visitors to ${current.url_to} (${current.header_code}).`} {!current.active && ' The rule is switched off.'}

{confirming ? (

{current.sources > 1 ? `Stop redirecting ${state.path}? Its address shows the page again; the rule keeps its other addresses.` : `Remove the redirect? ${state.path} shows the page again, to visitors and search engines.`}

) : (
{appUrl !== '' && ( In Redirects )}
)}
) : (

From {state.path}

{!gone(code) && ( setDestination(event.target.value)} /> )}
)} {message &&

{message}

}
); };