Pages -> Navigation (migration 075) edits the header's pages and buttons and the footer's links; navConfig.ts is now only the defaults. Page titles and intros move there from Site settings. A hidden page answers Not found below viewer (server and app) and is out of the menus and sitemap; signed in, it shows with a bar. Adds a /shop page of sections, hidden, with its header button. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
310 lines
12 KiB
TypeScript
310 lines
12 KiB
TypeScript
/* ═══════════════════════════════════════════════════════════════
|
||
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, or with none its first
|
||
line or picture); an icon-only link reads
|
||
its aria-label
|
||
br a line break
|
||
a part drawn on its a line of its own: a row of facts or link
|
||
own line buttons reads one per line
|
||
form one line saying it can't be used here
|
||
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, anything hidden from screen readers
|
||
(aria-hidden, the copies a carousel draws for its turns) and
|
||
anything CSS hides (display: none, eg. a print-only footer).
|
||
|
||
Ids on sections and headings are kept, so #links still land.
|
||
|
||
What this can't do well (a carousel showing one card, tabs,
|
||
details opened by a click, a count waiting to be scrolled to) the
|
||
component draws as text itself when useReadingMode() is on.
|
||
═══════════════════════════════════════════════════════════════ */
|
||
|
||
import { Fragment, useEffect, useState, type ReactNode, type RefObject } from 'react'
|
||
import { Link } from 'react-router-dom'
|
||
|
||
import { useSiteNav } from '../lib/useSiteNav.ts'
|
||
|
||
type Inline = string | { href: string; children: Inline[] }
|
||
|
||
/* A <br> in the page, kept as a line break (an address, a poem). */
|
||
const BREAK = '
'
|
||
/* `ids` are the page's own ids on a section or heading (a section
|
||
and its heading can both have one), kept so a #link (the side
|
||
nav, a "Jump to" button) still lands. */
|
||
type Block = { ids?: string[] } & (
|
||
| { kind: 'heading'; level: number; content: Inline[] }
|
||
| { kind: 'text'; content: Inline[] }
|
||
| { kind: 'image'; src: string; alt: string; href?: 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') ?? '') ||
|
||
// Hidden by CSS: a print-only footer, a phone-only copy.
|
||
getComputedStyle(el).display === 'none'
|
||
|
||
/* Drawn on a line of its own (a flex row's items, a block link): a
|
||
row of facts or link buttons reads one per line, not run together. */
|
||
const ownLine = (el: Element) => {
|
||
const display = getComputedStyle(el).display
|
||
return !display.startsWith('inline') && display !== 'contents'
|
||
}
|
||
|
||
/* 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 [BREAK]
|
||
let children = [...node.childNodes].flatMap(inline)
|
||
const href = node instanceof HTMLAnchorElement ? hrefOf(node) : null
|
||
// An icon-only link (an arrow) names itself in aria-label.
|
||
const label = node.getAttribute('aria-label')
|
||
if (href && label && !textOf(children)) children = [label]
|
||
const parts: Inline[] = href ? [{ href, children }] : children
|
||
// A part the page draws on its own line (a span set to block, a
|
||
// flex row's items) has no space in its text: give it one.
|
||
return getComputedStyle(node).display.startsWith('inline') ? parts : [' ', ...parts, ' ']
|
||
}
|
||
|
||
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[] = []
|
||
// Ids waiting for the next block written, which takes them.
|
||
let pendingIds: string[] = []
|
||
const push = (block: Block) => {
|
||
blocks.push(pendingIds.length ? { ...block, ids: pendingIds } : block)
|
||
pendingIds = []
|
||
}
|
||
const text = (content: Inline[]) => {
|
||
if (textOf(content)) 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 (el.id && el !== root) pendingIds.push(el.id)
|
||
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 (el.tagName === 'FORM') {
|
||
text(['This form can’t be filled in while reading mode is on. Turn it off (the accessibility button) to use it.'])
|
||
return
|
||
}
|
||
if (HEADINGS.has(el.tagName)) {
|
||
const content = [...el.childNodes].flatMap(inline)
|
||
if (textOf(content)) {
|
||
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) push({ kind: 'image', src, alt, ...(link ? { href: link } : {}) })
|
||
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)).map((c) => (textOf(c) ? 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; with none, on its aria-label as a line of its own, or
|
||
// else on its first line of text.
|
||
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)
|
||
const own = blocks.slice(before)
|
||
if (!own.some((b) => b.kind === 'heading')) {
|
||
const label = el.getAttribute('aria-label')
|
||
const first = own.findIndex((b) => b.kind === 'text')
|
||
if (label) blocks.splice(before, 0, { kind: 'text', content: [{ href, children: [label] }] })
|
||
else if (first >= 0) {
|
||
const block = blocks[before + first] as Extract<Block, { kind: 'text' }>
|
||
blocks[before + first] = { ...block, content: [{ href, children: block.content }] }
|
||
}
|
||
}
|
||
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 if (child instanceof Element && !skipped(child) && ownLine(child)) {
|
||
text(run)
|
||
run = []
|
||
text(inline(child))
|
||
} 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') {
|
||
if (!part.includes(BREAK)) return part
|
||
return part.split(BREAK).map((line, j) => (
|
||
<Fragment key={`${i}-${j}`}>
|
||
{j > 0 && <br />}
|
||
{line}
|
||
</Fragment>
|
||
))
|
||
}
|
||
return (
|
||
<Anchor key={i} href={part.href}>
|
||
{render(part.children)}
|
||
</Anchor>
|
||
)
|
||
})
|
||
}
|
||
|
||
/* A page on this site opens without reloading; a file (an upload,
|
||
the API) or anywhere else is a plain link. */
|
||
const isFile = (href: string) => /^\/(uploads|api)\//.test(href)
|
||
|
||
function Anchor({ href, children }: { href: string; children: ReactNode }) {
|
||
return href.startsWith('/') && !isFile(href) ? <Link to={href}>{children}</Link> : <a href={href}>{children}</a>
|
||
}
|
||
|
||
export default function ReaderView({ source }: { source: RefObject<HTMLElement | null> }) {
|
||
const [blocks, setBlocks] = useState<Block[]>([])
|
||
const { main: pages } = useSiteNav()
|
||
|
||
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>
|
||
{pages.map((page, i) => (
|
||
<span key={page.path}>
|
||
{i > 0 && ' · '}
|
||
<Link to={page.path}>{page.label}</Link>
|
||
</span>
|
||
))}
|
||
</p>
|
||
{blocks.map((block, i) => {
|
||
const [id, ...more] = block.ids ?? []
|
||
const anchors = more.map((other) => <span key={other} id={other} />)
|
||
if (block.kind === 'image') {
|
||
return (
|
||
<Fragment key={i}>
|
||
{anchors}
|
||
{block.href ? (
|
||
<Anchor href={block.href}>
|
||
<img id={id} src={block.src} alt={block.alt} loading="lazy" />
|
||
</Anchor>
|
||
) : (
|
||
<img id={id} src={block.src} alt={block.alt} loading="lazy" />
|
||
)}
|
||
</Fragment>
|
||
)
|
||
}
|
||
if (block.kind === 'text') {
|
||
return (
|
||
<p key={i} id={id}>
|
||
{anchors}
|
||
{render(block.content)}
|
||
</p>
|
||
)
|
||
}
|
||
const Heading = `h${block.level}` as 'h1'
|
||
return (
|
||
<Heading key={i} id={id}>
|
||
{anchors}
|
||
{render(block.content)}
|
||
</Heading>
|
||
)
|
||
})}
|
||
</article>
|
||
)
|
||
}
|