import { useState, useEffect } from 'react'; const Toolbar = () => { const [reports, setReports] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [isCollapsed, setIsCollapsed] = useState(true); // Helper to get the slug from the permalink const getSlug = () => { const canonicalLink = document.querySelector('link[rel="canonical"]'); if (canonicalLink) { const url = new URL(canonicalLink.href); const slug = url.pathname.split('/').filter(Boolean).pop(); // Extract the last part of the path return slug; } return null; }; useEffect(() => { const fetchReports = async () => { const slug = getSlug(); if (!slug) return; // Exit if slug is not available setLoading(true); try { const response = await fetch( `/wp-json/accessibility/v1/reports?slug=${slug}`, { method: 'GET', headers: { 'Content-Type': 'application/json', // eslint-disable-next-line no-undef 'X-WP-Nonce': accessibilityEnhancer.nonce, // Include the nonce passed via wp_localize_script }, } ); if (response.ok) { const data = await response.json(); if (data && Array.isArray(data.data)) { setReports(data.data); } else { setReports([]); } } else if (response.status === 401) { setError('Unauthorized: You do not have permission to view reports.'); } else { throw new Error(`Failed to fetch reports: ${response.status}`); } } catch (err) { setError(err.message); } finally { setLoading(false); } }; fetchReports(); }, []); const toggleCollapse = () => { setIsCollapsed(!isCollapsed); }; const increaseTextSize = () => { const root = document.documentElement; const currentSize = parseFloat(getComputedStyle(root).fontSize); root.style.fontSize = `${currentSize + 2}px`; }; const decreaseTextSize = () => { const root = document.documentElement; const currentSize = parseFloat(getComputedStyle(root).fontSize); root.style.fontSize = `${currentSize - 2}px`; }; const resetTextSize = () => { const root = document.documentElement; root.style.fontSize = '16px'; }; const setContrastMode = (mode) => { document.body.className = ''; if (mode) { document.body.classList.add(mode); } }; return (
{!isCollapsed && ( <>

Accessibility Toolbar

{!error && (

Accessibility Reports

{loading &&

Loading reports...

} {!loading && reports.length === 0 && (

No accessibility issues found for this page.

)} {!loading && reports.length > 0 && ( )}
)} )}
); }; export default Toolbar;