Accessibility: reader view and full palette swaps; version v1.12.1-accessibility
- Reading mode is now a reader view (ReaderView.tsx): the page renders hidden and its headings, paragraphs, links and described pictures are written out in one column, with no header, backdrop or footer. - Color blind modes swap all three color families (teal, green, amber); palette hexes in components and CSS are now var(--pal-<family>-<shade>) so the modes reach them. - CLAUDE.md and docs/updating-data-in-code.md describe both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
420a8058b4
commit
de17da7dc8
19 changed files with 507 additions and 192 deletions
|
|
@ -6,10 +6,10 @@
|
|||
|
||||
Dyslexia-friendly font every typeface becomes OpenDyslexic
|
||||
(self-hosted, index.css)
|
||||
Reading mode the page as plain text: one column of
|
||||
ink on white, no colors, pictures,
|
||||
cards or motion; a picture's
|
||||
description stays in its place
|
||||
Reading mode the page as text: its headings,
|
||||
paragraphs, links and described
|
||||
pictures in one column, nothing else
|
||||
(ReaderView.tsx)
|
||||
Color blind mode the palette swapped so its colors stay
|
||||
apart for that type of color blindness,
|
||||
or grays (color.ts, VISIONS)
|
||||
|
|
@ -53,7 +53,7 @@ const SETTINGS = [
|
|||
key: 'site-reading',
|
||||
on: 'on',
|
||||
label: 'Reading mode',
|
||||
help: 'The page as plain text: one column, larger type, no colors, pictures or motion.',
|
||||
help: 'The page as text: headings, paragraphs, links and pictures in one column, nothing else.',
|
||||
},
|
||||
] as const
|
||||
|
||||
|
|
@ -87,30 +87,6 @@ function apply(attribute: string, key: string, value: string | null) {
|
|||
}
|
||||
}
|
||||
|
||||
/* Reading mode hides pictures, video and maps; their descriptions
|
||||
(alt, title, aria-label) go on the parent as data-reading-alt,
|
||||
which index.css shows in their place. An attribute rather than a
|
||||
new element, so React's own nodes are left alone. */
|
||||
const DESCRIBED = 'main img[alt]:not([alt=""]), main iframe[title], main video[aria-label]'
|
||||
|
||||
function describeMedia() {
|
||||
for (const el of document.querySelectorAll(DESCRIBED)) {
|
||||
const words = el.getAttribute('alt') ?? el.getAttribute('title') ?? el.getAttribute('aria-label')
|
||||
const kind = el.tagName === 'IMG' ? 'Image' : 'Video'
|
||||
el.parentElement?.setAttribute('data-reading-alt', `${kind}: ${words}`)
|
||||
}
|
||||
}
|
||||
|
||||
function useMediaDescriptions(on: boolean) {
|
||||
useEffect(() => {
|
||||
if (!on) return undefined
|
||||
describeMedia()
|
||||
const observer = new MutationObserver(describeMedia)
|
||||
observer.observe(document.body, { childList: true, subtree: true })
|
||||
return () => observer.disconnect()
|
||||
}, [on])
|
||||
}
|
||||
|
||||
export default function AccessibilityPanel() {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [state, setState] = useState(() => Object.fromEntries(SETTINGS.map((s) => [s.key, isOn(s)])))
|
||||
|
|
@ -120,8 +96,6 @@ export default function AccessibilityPanel() {
|
|||
const firstRef = useRef<HTMLButtonElement>(null)
|
||||
const panelId = useId()
|
||||
|
||||
useMediaDescriptions(state['site-reading'])
|
||||
|
||||
useEffect(() => {
|
||||
const root = document.documentElement
|
||||
for (const { attribute, key } of PUBLIC_ONLY) {
|
||||
|
|
@ -187,7 +161,7 @@ export default function AccessibilityPanel() {
|
|||
id={panelId}
|
||||
role="region"
|
||||
aria-label="Accessibility"
|
||||
className="reading-solid absolute right-0 bottom-full mb-3 w-[min(20rem,calc(100vw-2rem))] border border-brand/20 bg-raised p-4 shadow-xl"
|
||||
className="absolute right-0 bottom-full mb-3 w-[min(20rem,calc(100vw-2rem))] border border-brand/20 bg-raised p-4 shadow-xl"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<h2 className="font-display text-base font-bold text-ink">Accessibility</h2>
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export default function Banner() {
|
|||
if (!visible) return null;
|
||||
|
||||
const linkClass =
|
||||
"underline underline-offset-4 decoration-[var(--green-2)] hover:text-white transition-colors";
|
||||
"underline underline-offset-4 decoration-[var(--pal-green-2)] hover:text-white transition-colors";
|
||||
|
||||
return (
|
||||
<div
|
||||
|
|
|
|||
|
|
@ -28,14 +28,14 @@ const Footer_Links = [
|
|||
];
|
||||
|
||||
const footerLinkClass =
|
||||
"text-white/65 hover:text-[var(--green-2)] text-sm transition-colors";
|
||||
"text-white/65 hover:text-[var(--pal-green-2)] text-sm transition-colors";
|
||||
|
||||
// inline-block with a little height of its own, so a finger can hit it.
|
||||
const pageLinkClass =
|
||||
"inline-block py-1 text-white/80 hover:text-[var(--green-2)] text-sm font-semibold transition-colors";
|
||||
"inline-block py-1 text-white/80 hover:text-[var(--pal-green-2)] text-sm font-semibold transition-colors";
|
||||
|
||||
const sectionLinkClass =
|
||||
"inline-block py-1 text-white/65 hover:text-[var(--green-2)] text-sm transition-colors";
|
||||
"inline-block py-1 text-white/65 hover:text-[var(--pal-green-2)] text-sm transition-colors";
|
||||
|
||||
const headingClass = "text-white/90 text-sm font-semibold mb-4";
|
||||
|
||||
|
|
|
|||
|
|
@ -9,8 +9,10 @@ import Footer from "./Footer.tsx";
|
|||
import PrivacyNotice from "./PrivacyNotice.tsx";
|
||||
import PageBackdrop from "./PageBackdrop.tsx";
|
||||
import AccessibilityPanel from "./AccessibilityPanel.tsx";
|
||||
import ReaderView from "./ReaderView.tsx";
|
||||
import ThemeToggle from "./ThemeToggle.tsx";
|
||||
import { jumpTo } from "../lib/focus.ts";
|
||||
import { useReadingMode } from "../lib/readingMode.ts";
|
||||
|
||||
/* ── Right-side nav actions ──────────────────────────────── */
|
||||
|
||||
|
|
@ -88,6 +90,9 @@ export default function Layout() {
|
|||
const [dismissed, setDismissed] = useState<string | null>(null);
|
||||
const location = useLocation();
|
||||
const lastPath = useRef(location.pathname);
|
||||
const reading = useReadingMode();
|
||||
// The page itself, drawn hidden for the reader view to read.
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const sectionsOf = useNavSections();
|
||||
|
||||
|
|
@ -124,19 +129,20 @@ export default function Layout() {
|
|||
);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
}, [reading]);
|
||||
|
||||
// On the root, so anything can read it: index.css keeps focused
|
||||
// and jumped-to things clear of the header with it
|
||||
// (scroll-padding-top), and PostContents offsets by it.
|
||||
useEffect(() => {
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty("--header-h", `${headerHeight}px`);
|
||||
// Reading mode has no header to stay clear of.
|
||||
root.style.setProperty("--header-h", `${reading ? 0 : headerHeight}px`);
|
||||
// The admin has no fixed header: nothing to stay clear of there.
|
||||
return () => {
|
||||
root.style.removeProperty("--header-h");
|
||||
};
|
||||
}, [headerHeight]);
|
||||
}, [headerHeight, reading]);
|
||||
|
||||
// Router does not scroll on navigation. Go to top on a new page,
|
||||
// or to the anchor if the URL carries one (handles deep links too).
|
||||
|
|
@ -151,17 +157,42 @@ export default function Layout() {
|
|||
if (newPage) document.getElementById("main")?.focus({ preventScroll: true });
|
||||
}, [location.pathname, location.hash, location.key]);
|
||||
|
||||
const skipLink = (
|
||||
<a
|
||||
href="#main"
|
||||
className="sr-only focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-[70] focus:bg-surface focus:px-4 focus:py-2 focus:font-semibold focus:text-ink"
|
||||
>
|
||||
Skip to content
|
||||
</a>
|
||||
);
|
||||
|
||||
// Reading mode: the page as plain text (ReaderView.tsx), with no
|
||||
// header, backdrop, footer or notices; the panel stays, to turn it
|
||||
// off. The page itself still renders, hidden, for the reader to
|
||||
// read, so every page works without a version of its own.
|
||||
if (reading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-surface text-ink">
|
||||
{skipLink}
|
||||
<main id="main" tabIndex={-1} className="outline-none">
|
||||
<ReaderView source={pageRef} />
|
||||
<div ref={pageRef} hidden>
|
||||
<Suspense fallback={null}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
</div>
|
||||
</main>
|
||||
<AccessibilityPanel />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
// overflow-x-clip, not -hidden: hidden makes this div a scroll
|
||||
// container, and then nothing inside it can be position: sticky
|
||||
// (a blog post's contents column scrolled away with the page).
|
||||
<div className="min-h-screen overflow-x-clip">
|
||||
<a
|
||||
href="#main"
|
||||
className="sr-only focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-[70] focus:bg-surface focus:px-4 focus:py-2 focus:font-semibold focus:text-ink"
|
||||
>
|
||||
Skip to content
|
||||
</a>
|
||||
{skipLink}
|
||||
|
||||
{/* ── NAV ─────────────────────────────────────────────── */}
|
||||
<header
|
||||
|
|
@ -177,7 +208,7 @@ export default function Layout() {
|
|||
<nav
|
||||
className="flex items-center justify-between px-6 py-4"
|
||||
aria-label="Site"
|
||||
style={{ background: "rgba(0, 58, 69, 0.92)" }}
|
||||
style={{ background: "color-mix(in srgb, var(--pal-teal-1) 92%, transparent)" }}
|
||||
>
|
||||
<div className="flex items-center gap-8">
|
||||
<Link to="/" aria-label="Next Generation of Unity home" className="inline-block">
|
||||
|
|
@ -212,7 +243,7 @@ export default function Layout() {
|
|||
className={({ isActive }) =>
|
||||
`block text-base font-bold pb-1 border-b-2 transition-colors duration-200 ${
|
||||
isActive
|
||||
? "text-white border-[var(--green-2)]"
|
||||
? "text-white border-[var(--pal-green-2)]"
|
||||
: "text-white/75 hover:text-white border-transparent"
|
||||
}`
|
||||
}
|
||||
|
|
@ -233,13 +264,13 @@ export default function Layout() {
|
|||
>
|
||||
<ul
|
||||
className="min-w-56 py-2 shadow-xl"
|
||||
style={{ background: "rgba(0, 16, 17, 0.97)", borderTop: "2px solid var(--green-2)" }}
|
||||
style={{ background: "rgba(0, 16, 17, 0.97)", borderTop: "2px solid var(--pal-green-2)" }}
|
||||
>
|
||||
{pageSections.map((section) => (
|
||||
<li key={section.hash}>
|
||||
<Link
|
||||
to={`${page.path}${section.hash}`}
|
||||
className="block px-4 py-2 text-sm text-white/80 transition-colors hover:bg-white/10 hover:text-[#f0bd4f] focus-visible:bg-white/10"
|
||||
className="block px-4 py-2 text-sm text-white/80 transition-colors hover:bg-white/10 hover:text-[var(--pal-amber-2)] focus-visible:bg-white/10"
|
||||
>
|
||||
{section.label}
|
||||
</Link>
|
||||
|
|
@ -299,8 +330,8 @@ export default function Layout() {
|
|||
{/* Mobile menu */}
|
||||
{mobileMenuOpen && (
|
||||
<div
|
||||
className="reading-solid fixed inset-0 z-[60] flex flex-col items-center [justify-content:safe_center] overflow-y-auto py-16"
|
||||
style={{ background: "rgba(0, 58, 69, 0.97)" }}
|
||||
className="fixed inset-0 z-[60] flex flex-col items-center [justify-content:safe_center] overflow-y-auto py-16"
|
||||
style={{ background: "color-mix(in srgb, var(--pal-teal-1) 97%, transparent)" }}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Menu"
|
||||
|
|
@ -326,7 +357,7 @@ export default function Layout() {
|
|||
end={page.path === "/"}
|
||||
className={({ isActive }) =>
|
||||
`block text-2xl font-bold py-3 transition-colors ${
|
||||
isActive ? "text-[var(--green-2)]" : "text-white hover:text-[#f0bd4f]"
|
||||
isActive ? "text-[var(--pal-green-2)]" : "text-white hover:text-[var(--pal-amber-2)]"
|
||||
}`
|
||||
}
|
||||
>
|
||||
|
|
@ -337,13 +368,13 @@ export default function Layout() {
|
|||
{isActive && pageSections.length > 0 && (
|
||||
<div
|
||||
className="ml-3 pl-4 mb-2 flex flex-col"
|
||||
style={{ borderLeft: "1px solid rgba(45,200,224,0.35)" }}
|
||||
style={{ borderLeft: "1px solid color-mix(in srgb, var(--pal-teal-2) 35%, transparent)" }}
|
||||
>
|
||||
{pageSections.map((section) => (
|
||||
<a
|
||||
key={section.hash}
|
||||
href={section.hash}
|
||||
className="text-white/80 text-lg py-2 hover:text-[#f0bd4f] transition-colors"
|
||||
className="text-white/80 text-lg py-2 hover:text-[var(--pal-amber-2)] transition-colors"
|
||||
onClick={() => setMobileMenuOpen(false)}
|
||||
>
|
||||
{section.label}
|
||||
|
|
|
|||
|
|
@ -18,10 +18,10 @@
|
|||
pointer-events: none;
|
||||
|
||||
--pb-opacity: 0.6;
|
||||
--pb-0: #d6f5fa;
|
||||
--pb-1: var(--green-3);
|
||||
--pb-2: #fdf1d6;
|
||||
--pb-3: #d6f5fa;
|
||||
--pb-0: var(--pal-teal-3);
|
||||
--pb-1: var(--pal-green-3);
|
||||
--pb-2: var(--pal-amber-3);
|
||||
--pb-3: var(--pal-teal-3);
|
||||
}
|
||||
|
||||
/* A circle's place: across by its left, down its layer's whole
|
||||
|
|
@ -71,18 +71,18 @@
|
|||
toggle's choice, or the system's when there is none. */
|
||||
:root[data-theme="dark"] .page-backdrop {
|
||||
--pb-opacity: 0.3;
|
||||
--pb-0: #003a45;
|
||||
--pb-1: var(--green-1);
|
||||
--pb-2: #4a2e00;
|
||||
--pb-3: #003a45;
|
||||
--pb-0: var(--pal-teal-1);
|
||||
--pb-1: var(--pal-green-1);
|
||||
--pb-2: var(--pal-amber-1);
|
||||
--pb-3: var(--pal-teal-1);
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) .page-backdrop {
|
||||
--pb-opacity: 0.3;
|
||||
--pb-0: #003a45;
|
||||
--pb-1: var(--green-1);
|
||||
--pb-2: #4a2e00;
|
||||
--pb-3: #003a45;
|
||||
--pb-0: var(--pal-teal-1);
|
||||
--pb-1: var(--pal-green-1);
|
||||
--pb-2: var(--pal-amber-1);
|
||||
--pb-3: var(--pal-teal-1);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
on the page backdrop (PageBackdrop.css). */
|
||||
|
||||
.side-nav-circle {
|
||||
background: #d6f5fa;
|
||||
background: var(--pal-teal-3);
|
||||
/* A slight drop shadow, as the cards have: down and soft, no glow. */
|
||||
box-shadow: 0 4px 12px rgb(0 16 17 / 0.14);
|
||||
/* Color by section; size and place between centered on the list
|
||||
|
|
@ -18,32 +18,32 @@
|
|||
top 0.6s ease-in-out;
|
||||
}
|
||||
.side-nav-circle[data-family="green"] {
|
||||
background: var(--green-3);
|
||||
background: var(--pal-green-3);
|
||||
}
|
||||
.side-nav-circle[data-family="amber"] {
|
||||
background: #fdf1d6;
|
||||
background: var(--pal-amber-3);
|
||||
}
|
||||
|
||||
/* Dark mode: the toggle's choice, or the system's when there is none. */
|
||||
:root[data-theme="dark"] .side-nav-circle {
|
||||
background: #003a45;
|
||||
background: var(--pal-teal-1);
|
||||
box-shadow: 0 4px 12px rgb(0 0 0 / 0.45);
|
||||
}
|
||||
:root[data-theme="dark"] .side-nav-circle[data-family="green"] {
|
||||
background: var(--green-1);
|
||||
background: var(--pal-green-1);
|
||||
}
|
||||
:root[data-theme="dark"] .side-nav-circle[data-family="amber"] {
|
||||
background: #4a2e00;
|
||||
background: var(--pal-amber-1);
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) .side-nav-circle {
|
||||
background: #003a45;
|
||||
background: var(--pal-teal-1);
|
||||
box-shadow: 0 4px 12px rgb(0 0 0 / 0.45);
|
||||
}
|
||||
:root:not([data-theme="light"]) .side-nav-circle[data-family="green"] {
|
||||
background: var(--green-1);
|
||||
background: var(--pal-green-1);
|
||||
}
|
||||
:root:not([data-theme="light"]) .side-nav-circle[data-family="amber"] {
|
||||
background: #4a2e00;
|
||||
background: var(--pal-amber-1);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ export default function PrivacyNotice() {
|
|||
<div
|
||||
role="region"
|
||||
aria-label="Privacy notice"
|
||||
className="reading-solid fixed bottom-20 left-4 right-4 z-40 sm:bottom-4 mx-auto max-w-md border border-brand/20 bg-surface p-4 text-sm text-body shadow-xl sm:right-auto"
|
||||
className="fixed bottom-20 left-4 right-4 z-40 sm:bottom-4 mx-auto max-w-md border border-brand/20 bg-surface p-4 text-sm text-body shadow-xl sm:right-auto"
|
||||
>
|
||||
<p>
|
||||
No tracking cookies here. Videos and maps come from YouTube, Facebook or Google only when you press
|
||||
|
|
|
|||
217
src/components/ReaderView.tsx
Normal file
217
src/components/ReaderView.tsx
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
READER VIEW: reading mode (AccessibilityPanel.tsx)
|
||||
|
||||
The page as text: its headings, paragraphs, links and pictures,
|
||||
one column, nothing else. No buttons, cards, colors, carousels or
|
||||
forms.
|
||||
|
||||
The real page still renders, hidden (Layout.tsx), so every page
|
||||
and section works without a reading version of its own; this reads
|
||||
what it drew and writes it out plainly, again whenever it changes
|
||||
(data arriving, a new page).
|
||||
|
||||
What's kept:
|
||||
h1 to h6 headings, at their level
|
||||
p, li, td, quote... paragraphs, with their links
|
||||
a links (a card that is one link gives its
|
||||
heading the link)
|
||||
img with alt text pictures; one with empty alt is decoration
|
||||
(a card's faded background) and is left out
|
||||
a button that opens its words, as a line: a person's tile, a
|
||||
something schedule row (aria-expanded)
|
||||
What's dropped: other buttons, form fields, navigation lists, video and
|
||||
map frames, drawings, and anything hidden from screen readers
|
||||
(aria-hidden, the copies a carousel draws for its turns).
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useState, type ReactNode, type RefObject } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import { PAGE_LINKS } from '../navConfig.ts'
|
||||
|
||||
type Inline = string | { href: string; children: Inline[] }
|
||||
type Block =
|
||||
| { kind: 'heading'; level: number; content: Inline[] }
|
||||
| { kind: 'text'; content: Inline[] }
|
||||
| { kind: 'image'; src: string; alt: string }
|
||||
|
||||
const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'NAV', 'IFRAME', 'VIDEO', 'AUDIO', 'CANVAS', 'DIALOG', 'svg'])
|
||||
const HEADINGS = new Set(['H1', 'H2', 'H3', 'H4', 'H5', 'H6'])
|
||||
const TEXT_BLOCKS = new Set(['P', 'LI', 'DT', 'DD', 'BLOCKQUOTE', 'FIGCAPTION', 'CAPTION', 'ADDRESS', 'TH', 'TD'])
|
||||
const BLOCK_SELECTOR = 'div,section,article,header,footer,aside,main,p,ul,ol,li,dl,dt,dd,table,tr,figure,blockquote,h1,h2,h3,h4,h5,h6,img,form,fieldset'
|
||||
|
||||
/* A button that opens something (a person's tile, a schedule row):
|
||||
its words name content, so it's read as a line, not dropped. */
|
||||
const opens = (el: Element) => el.tagName === 'BUTTON' && el.hasAttribute('aria-expanded')
|
||||
|
||||
const skipped = (el: Element) =>
|
||||
(SKIP.has(el.tagName) && !opens(el)) ||
|
||||
el.getAttribute('aria-hidden') === 'true' ||
|
||||
el.hasAttribute('hidden') ||
|
||||
['button', 'switch', 'tab', 'slider', 'presentation', 'none'].includes(el.getAttribute('role') ?? '')
|
||||
|
||||
/* A link's address as the app routes it: a path for this site, so
|
||||
it opens without reloading; the full address for anywhere else. */
|
||||
function hrefOf(a: HTMLAnchorElement): string | null {
|
||||
const raw = a.getAttribute('href')
|
||||
if (!raw || raw.startsWith('javascript:')) return null
|
||||
try {
|
||||
const url = new URL(raw, location.href)
|
||||
return url.origin === location.origin ? url.pathname + url.search + url.hash : url.href
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function inline(node: Node): Inline[] {
|
||||
if (node.nodeType === Node.TEXT_NODE) return [node.textContent ?? '']
|
||||
if (!(node instanceof Element) || skipped(node) || node.tagName === 'IMG') return []
|
||||
if (node.tagName === 'BR') return [' ']
|
||||
const children = [...node.childNodes].flatMap(inline)
|
||||
if (node instanceof HTMLAnchorElement) {
|
||||
const href = hrefOf(node)
|
||||
return href ? [{ href, children }] : children
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
const textOf = (parts: Inline[]): string =>
|
||||
parts.map((p) => (typeof p === 'string' ? p : textOf(p.children))).join('').replace(/\s+/g, ' ').trim()
|
||||
|
||||
const isBlock = (el: Element) => opens(el) || el.matches(BLOCK_SELECTOR) || el.querySelector(BLOCK_SELECTOR) !== null
|
||||
|
||||
function extract(root: Element): Block[] {
|
||||
const blocks: Block[] = []
|
||||
const text = (content: Inline[]) => {
|
||||
if (textOf(content)) blocks.push({ kind: 'text', content })
|
||||
}
|
||||
|
||||
function walk(el: Element, link: string | null) {
|
||||
// The root is the hidden copy of the page itself: read inside it.
|
||||
if (el !== root && skipped(el)) return
|
||||
if (opens(el)) {
|
||||
// Each part on its own line in the page (a name, a title) joins
|
||||
// with a comma.
|
||||
const parts = [...el.querySelectorAll('*')]
|
||||
.filter((part) => !part.closest('[aria-hidden="true"]') && [...part.childNodes].some((n) => n.nodeType === Node.TEXT_NODE && n.textContent?.trim()))
|
||||
.map((part) => [...part.childNodes].filter((n) => n.nodeType === Node.TEXT_NODE).map((n) => n.textContent).join('').trim())
|
||||
text([parts.join(', ')])
|
||||
return
|
||||
}
|
||||
if (HEADINGS.has(el.tagName)) {
|
||||
const content = [...el.childNodes].flatMap(inline)
|
||||
if (textOf(content)) {
|
||||
blocks.push({ kind: 'heading', level: Number(el.tagName[1]), content: link ? [{ href: link, children: content }] : content })
|
||||
}
|
||||
return
|
||||
}
|
||||
if (el.tagName === 'IMG') {
|
||||
const img = el as HTMLImageElement
|
||||
const alt = img.getAttribute('alt')?.trim()
|
||||
const src = img.currentSrc || img.getAttribute('src')
|
||||
if (alt && src) blocks.push({ kind: 'image', src, alt })
|
||||
return
|
||||
}
|
||||
if (TEXT_BLOCKS.has(el.tagName) && !el.querySelector('p,li,h1,h2,h3,h4,h5,h6,img')) {
|
||||
text([...el.childNodes].flatMap(inline))
|
||||
return
|
||||
}
|
||||
if (el.tagName === 'TR') {
|
||||
const cells = [...el.children].map((cell) => [...cell.childNodes].flatMap(inline)).filter((c) => textOf(c))
|
||||
text(cells.flatMap((cell, i) => (i ? [' · ', ...cell] : cell)))
|
||||
return
|
||||
}
|
||||
// A link around a whole card: its parts, with the link on the first
|
||||
// heading (or, with none, kept as a line of its own).
|
||||
const href = el instanceof HTMLAnchorElement ? hrefOf(el) : null
|
||||
if (href && isBlock(el)) {
|
||||
const before = blocks.length
|
||||
for (const child of el.children) walk(child, href)
|
||||
if (!blocks.slice(before).some((b) => b.kind === 'heading')) {
|
||||
const label = el.getAttribute('aria-label')
|
||||
if (label) blocks.splice(before, 0, { kind: 'text', content: [{ href, children: [label] }] })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Anything else: its loose text and inline parts make paragraphs,
|
||||
// broken where a block of its own comes.
|
||||
let run: Inline[] = []
|
||||
for (const child of el.childNodes) {
|
||||
if (child instanceof Element && !skipped(child) && isBlock(child)) {
|
||||
text(run)
|
||||
run = []
|
||||
walk(child, link)
|
||||
} else {
|
||||
run.push(...inline(child))
|
||||
}
|
||||
}
|
||||
text(run)
|
||||
}
|
||||
|
||||
walk(root, null)
|
||||
// Carousels and repeated strips can say the same line twice in a row.
|
||||
return blocks.filter((b, i) => {
|
||||
const prev = blocks[i - 1]
|
||||
return !prev || prev.kind !== b.kind || JSON.stringify(prev) !== JSON.stringify(b)
|
||||
})
|
||||
}
|
||||
|
||||
function render(parts: Inline[]): ReactNode[] {
|
||||
return parts.map((part, i) => {
|
||||
if (typeof part === 'string') return part
|
||||
const children = render(part.children)
|
||||
return part.href.startsWith('/') ? (
|
||||
<Link key={i} to={part.href}>
|
||||
{children}
|
||||
</Link>
|
||||
) : (
|
||||
<a key={i} href={part.href}>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export default function ReaderView({ source }: { source: RefObject<HTMLElement | null> }) {
|
||||
const [blocks, setBlocks] = useState<Block[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const root = source.current
|
||||
if (!root) return undefined
|
||||
let frame = 0
|
||||
const update = () => {
|
||||
frame = 0
|
||||
setBlocks(extract(root))
|
||||
}
|
||||
const schedule = () => {
|
||||
if (!frame) frame = requestAnimationFrame(update)
|
||||
}
|
||||
update()
|
||||
const observer = new MutationObserver(schedule)
|
||||
observer.observe(root, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['src', 'alt', 'href', 'hidden', 'aria-hidden'] })
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
if (frame) cancelAnimationFrame(frame)
|
||||
}
|
||||
}, [source])
|
||||
|
||||
return (
|
||||
<article className="reader">
|
||||
<p>
|
||||
{PAGE_LINKS.map((page, i) => (
|
||||
<span key={page.path}>
|
||||
{i > 0 && ' · '}
|
||||
<Link to={page.path}>{page.label}</Link>
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
{blocks.map((block, i) => {
|
||||
if (block.kind === 'image') return <img key={i} src={block.src} alt={block.alt} loading="lazy" />
|
||||
if (block.kind === 'text') return <p key={i}>{render(block.content)}</p>
|
||||
const Heading = `h${block.level}` as 'h1'
|
||||
return <Heading key={i}>{render(block.content)}</Heading>
|
||||
})}
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
|
@ -90,7 +90,7 @@ export default function VideoPlayer({
|
|||
className="block aspect-video w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="block aspect-video w-full bg-[#003a45]" />
|
||||
<span className="block aspect-video w-full bg-[var(--pal-teal-1)]" />
|
||||
)}
|
||||
<span
|
||||
aria-hidden="true"
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { jumpTo } from "../../lib/focus.ts";
|
||||
import { scrollBehavior } from "../../lib/motion.ts";
|
||||
import { accentText } from "../../lib/color.ts";
|
||||
|
||||
export type EditorSection = {
|
||||
id: string;
|
||||
|
|
@ -107,7 +106,11 @@ export function SectionNav({ sections, wrap = false }: { sections: EditorSection
|
|||
type="button"
|
||||
onClick={() => jumpTo(section.id)}
|
||||
aria-current={lit ? "location" : undefined}
|
||||
style={section.accent ? ({ "--nav-accent": accentText(section.accent) } as React.CSSProperties) : undefined}
|
||||
style={
|
||||
section.accent
|
||||
? ({ "--nav-accent": `color-mix(in srgb, ${section.accent} var(--nav-text-mix), #ffffff)` } as React.CSSProperties)
|
||||
: undefined
|
||||
}
|
||||
className={`-ml-px flex w-full items-center gap-1.5 border-l-2 px-3 py-1.5 text-left text-sm transition-colors ${
|
||||
section.accent
|
||||
? lit
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue