Files
themiz/eunomia/frontend/src/views/Reader.tsx
T

226 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {useCallback, useEffect, useMemo, useRef, useState, type ReactNode} from 'react'
import {api, docHref, href, normalized, safeURL, shortDate, useApi, type Anchor, type Fragment, type GraphEdge, type ReaderData, type RelatedData, type Route} from '../lib/api'
import {Icon} from '../components/Icon'
import {Sheet, SheetContent, SheetDescription, SheetTitle} from '../components/ui/sheet'
type DocumentData = ReaderData & {fragments?: Fragment[]; body?: string}
type ReaderProps = {route: Route; onNotify: (message: string) => void; onUpdate: (id: string) => Promise<void>}
const emptyDocument: Fragment[] = []
function labelKind(kind: string) {
return ({code: 'Кодекс', 'federal-law': 'Федеральный закон', bylaw: 'Подзаконный акт', plenum: 'Пленум', review: 'Обзор практики'} as Record<string, string>)[kind] || 'Правовой документ'
}
function renderAnchoredText(text: string, anchors: Anchor[] = [], query = ''): ReactNode[] {
const sorted = anchors.filter(anchor => Number.isFinite(anchor.offset) && anchor.offset >= 0).slice().sort((a, b) => a.offset - b.offset)
const chunks: ReactNode[] = []
let cursor = 0
const addText = (value: string, key: string) => {
if (!value) return
if (!query) { chunks.push(<span key={key}>{value}</span>); return }
const parts = value.split(new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'ig'))
chunks.push(...parts.map((part, index) => part.toLocaleLowerCase('ru') === query.toLocaleLowerCase('ru') ? <mark key={`${key}-mark-${index}`}>{part}</mark> : <span key={`${key}-${index}`}>{part}</span>))
}
sorted.forEach((anchor, index) => {
const offset = Math.min(text.length, Math.max(cursor, anchor.offset))
addText(text.slice(cursor, offset), `text-${index}`)
chunks.push(<span id={anchor.id} key={`anchor-${anchor.id}`} className="reader-anchor" aria-hidden="true" />)
cursor = offset
})
addText(text.slice(cursor), 'text-tail')
return chunks
}
function fragmentText(fragment: Fragment, query = '') {
return <div className="fragment-body">{renderAnchoredText(String(fragment.text || ''), fragment.anchors, query)}</div>
}
function isHeadingDuplicated(fragment: Fragment) {
const firstLine = String(fragment.text || '').split(/\r?\n/, 1)[0].replace(/^\s*#+\s*/, '').trim()
return firstLine && normalized(firstLine) === normalized(fragment.label)
}
function Toc({items, documentId, activeId, filter, onFilter, onSelect}: {items: Fragment[]; documentId: string; activeId: string; filter: string; onFilter: (value: string) => void; onSelect: (id: string) => void}) {
const rows = useMemo(() => items.filter(item => !filter || normalized(`${item.label} ${item.text || ''}`).includes(normalized(filter))), [items, filter])
const chapters = rows.filter(item => !['article', 'point', 'paragraph'].includes(item.kind))
const chapterIds = new Set(chapters.map(item => item.id))
const chapterRows = useMemo(() => chapters.map((chapter, index) => {
const start = items.indexOf(chapter)
const nextStart = index + 1 < chapters.length ? items.indexOf(chapters[index + 1]) : Infinity
const children = rows.filter(item => item.id !== chapter.id && !chapterIds.has(item.id) && items.indexOf(item) > start && items.indexOf(item) < nextStart)
return {chapter, children}
}), [chapters, chapterIds, items, rows])
return <aside className="reader-toc" aria-label="Оглавление">
<div className="reader-panel-content">
<div className="section-heading"><h2>Оглавление</h2><span className="muted">{rows.length} разделов</span></div>
<label className="field"><span>Статья или пункт</span><input type="search" value={filter} onChange={event => onFilter(event.target.value)} placeholder="Например, 395" /></label>
<div className="toc-scroll">
{chapterRows.map(({chapter, children}) => <details key={chapter.id} open={Boolean(filter) || activeId === chapter.id || children.some(item => item.id === activeId)} className="toc-group">
<summary>{chapter.label}</summary>
<a aria-label={`Читать раздел ${chapter.label}`} className={activeId === chapter.id ? 'toc-link is-active' : 'toc-link'} href={docHref(documentId, chapter.id)} onClick={() => onSelect(chapter.id)}>Читать раздел</a>
{children.map(item => <a key={item.id} className={activeId === item.id ? 'toc-link is-active' : 'toc-link'} href={docHref(documentId, item.id)} onClick={() => onSelect(item.id)}>{item.label}</a>)}
</details>)}
{!chapters.length && rows.map(item => <a key={item.id} className={activeId === item.id ? 'toc-link is-active' : 'toc-link'} href={docHref(documentId, item.id)} onClick={() => onSelect(item.id)}>{item.label}</a>)}
</div>
</div>
</aside>
}
function Related({edges, loading, documentId, fragmentId, nodeId}: {edges: GraphEdge[]; loading: boolean; documentId: string; fragmentId: string; nodeId?: string}) {
return <aside className="reader-related" aria-label="Связанные материалы">
<div className="reader-panel-content"><h2>Связанные материалы</h2><p className="muted">{fragmentId ? 'К выбранной статье или пункту' : 'К документу целиком'}</p>
{loading && <p className="help-note" role="status">Загружаем связи…</p>}
{!loading && !edges.length && <p className="help-note">Подтвержденных связей пока нет. Текст можно читать.</p>}
<div className="related-list">{edges.slice(0, 30).map((edge, index) => {
const source = edge.source_node
const target = edge.target_node
const other = (nodeId && source?.id === nodeId ? target : nodeId && target?.id === nodeId ? source : undefined) || (source?.resource_id === documentId ? target : source)
if (!other) return null
return <details key={`${edge.source}-${edge.target}-${index}`} className="relation-item"><summary>{other.label || 'Связанный фрагмент'} · {other.document_title || ''}</summary><div className="relation-detail"><span className="status-tag">{edge.relation === 'references' ? 'Прямая ссылка' : edge.relation === 'thematic' ? 'Тематическая связь' : 'Связь из графа'}</span><p>{edge.evidence?.excerpt || 'Доказательство связи не предоставлено.'}</p><p>Редакция: {shortDate(edge.evidence?.revision)}</p>{edge.evidence?.source_url && <a className="text-link" href={safeURL(edge.evidence.source_url)} target="_blank" rel="noopener noreferrer">Источник связи ↗</a>}<a className="button quiet" href={docHref(other.resource_id, other.reader_id)}>{other.reader_id ? 'Открыть фрагмент' : 'Открыть документ'} →</a></div></details>
})}</div>
<a className="text-link" href={href({view: 'graph', ...(nodeId ? {node_id: nodeId} : {resource_id: documentId})})}>Показать на карте связей →</a>
</div>
</aside>
}
export default function Reader({route, onNotify, onUpdate}: ReaderProps) {
const documentId = route.doc || route.id || ''
const fragmentId = route.fragment || ''
const readerPath = documentId ? `/reader?${new URLSearchParams({id: documentId, ...(fragmentId ? {fragment: fragmentId} : {})})}` : null
const reader = useApi<ReaderData>(readerPath)
const [allFragments, setAllFragments] = useState<Fragment[]>([])
const [wholeLoading, setWholeLoading] = useState(false)
const [wholeError, setWholeError] = useState('')
const [tocFilter, setTocFilter] = useState('')
const [query, setQuery] = useState('')
const [searchQuery, setSearchQuery] = useState('')
const [fontSize, setFontSize] = useState(20)
const [focusMode, setFocusMode] = useState(false)
const [mobilePanel, setMobilePanel] = useState<'toc' | 'related' | null>(null)
const [matchIndex, setMatchIndex] = useState(-1)
const [matchCount, setMatchCount] = useState(0)
const [related, setRelated] = useState<RelatedData>({related: []})
const [relatedLoading, setRelatedLoading] = useState(false)
const findRef = useRef<HTMLInputElement>(null)
const requestRef = useRef(0)
const wholeControllerRef = useRef<AbortController | null>(null)
const wholeGenerationRef = useRef(0)
const legalDocument = reader.data?.document
const toc = reader.data?.toc || emptyDocument
const fragments = allFragments.length ? allFragments : reader.data?.fragment ? [reader.data.fragment] : emptyDocument
const activeId = reader.data?.selected_id || fragmentId || fragments[0]?.id || ''
useEffect(() => { document.body.classList.toggle('reading-focus', focusMode); return () => document.body.classList.remove('reading-focus') }, [focusMode])
useEffect(() => { const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape' && focusMode) setFocusMode(false) }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey) }, [focusMode])
useEffect(() => { setAllFragments([]); setQuery(''); setSearchQuery(''); setWholeError(''); wholeGenerationRef.current += 1; wholeControllerRef.current?.abort(); wholeControllerRef.current = null }, [documentId, fragmentId])
useEffect(() => () => { wholeGenerationRef.current += 1; wholeControllerRef.current?.abort() }, [])
const loadWhole = useCallback(async () => {
if (!documentId || wholeLoading || allFragments.length) return allFragments
wholeControllerRef.current?.abort()
const controller = new AbortController()
wholeControllerRef.current = controller
const generation = ++wholeGenerationRef.current
setWholeLoading(true); setWholeError('')
try {
const data = await api<{fragments?: Fragment[]; body?: string}>(`/document?${new URLSearchParams({id: documentId})}`, {signal: controller.signal})
if (controller.signal.aborted || generation !== wholeGenerationRef.current) return []
const next = data.fragments || (data.body ? [{id: documentId, label: 'Документ', kind: 'document', text: data.body}] : [])
setAllFragments(next); return next
} catch (error) { if (controller.signal.aborted || generation !== wholeGenerationRef.current) return []; const message = error instanceof Error ? error.message : 'Не удалось загрузить полный текст.'; setWholeError(message); onNotify(message); return []
} finally { if (generation === wholeGenerationRef.current) { setWholeLoading(false); wholeControllerRef.current = null } }
}, [allFragments, documentId, onNotify, wholeLoading])
const runSearch = useCallback(async (value = query) => {
const clean = value.trim(); setSearchQuery(clean)
if (!clean) return
const loaded = await loadWhole()
if (loaded.length) setTimeout(() => document.querySelector('.reader-find mark')?.scrollIntoView({block: 'center'}), 0)
}, [loadWhole, query])
useEffect(() => {
if (!documentId) return
const controller = new AbortController(); const request = ++requestRef.current
setRelatedLoading(true)
let attempts = 0
let timer: number | undefined
const load = async () => {
try { const data = await api<RelatedData>(`/related?${new URLSearchParams({id: documentId, ...(activeId ? {fragment: activeId} : {})})}`, {signal: controller.signal}); if (request !== requestRef.current || controller.signal.aborted) return; setRelated(data); setRelatedLoading(Boolean(data.loading)); if (data.loading && attempts++ < 4) timer = window.setTimeout(load, 1500) }
catch (error) { if (error instanceof Error && error.name === 'AbortError') return; if (request === requestRef.current) { setRelated({related: []}); setRelatedLoading(false) } }
}
void load(); return () => { controller.abort(); if (timer !== undefined) window.clearTimeout(timer) }
}, [documentId, activeId])
const selectFragment = (id: string) => { window.location.hash = docHref(documentId, id).slice(1) }
const copy = async (value: string, message: string) => { try { await navigator.clipboard.writeText(value); onNotify(message) } catch { onNotify('Копирование недоступно в этом браузере.') } }
const navigateMatch = (direction: 1 | -1) => {
const marks = Array.from(document.querySelectorAll<HTMLElement>('.reading-text mark'))
if (!marks.length) return
const next = (matchIndex + direction + marks.length) % marks.length
setMatchIndex(next)
marks[next]?.scrollIntoView({block: 'center', behavior: 'auto'})
}
const visibleFragments = searchQuery ? allFragments : fragments
useEffect(() => {
setMatchIndex(-1)
if (!query.trim()) { setSearchQuery(''); return }
const timer = window.setTimeout(() => { void runSearch(query) }, 280)
return () => window.clearTimeout(timer)
}, [query])
useEffect(() => {
const frame = window.requestAnimationFrame(() => {
const node = activeId ? document.getElementById(activeId) : null
if (!node) return
const topbar = document.querySelector<HTMLElement>('.topbar')?.getBoundingClientRect().height || 0
const toolbar = document.querySelector<HTMLElement>('.document-toolbar')?.getBoundingClientRect().height || 0
const top = node.getBoundingClientRect().top + window.scrollY - topbar - toolbar - 20
window.scrollTo({top: Math.max(0, top), behavior: 'auto'})
})
return () => window.cancelAnimationFrame(frame)
}, [activeId, allFragments, reader.data])
useEffect(() => {
const frame = window.requestAnimationFrame(() => setMatchCount(document.querySelectorAll('.reading-text mark').length))
return () => window.cancelAnimationFrame(frame)
}, [searchQuery, allFragments])
if (reader.loading && !legalDocument) return <div className="wide-page reader-shell"><p className="help-note" role="status">Открываем документ…</p></div>
if (reader.error || !legalDocument) return <div className="wide-page reader-shell"><p className="notice warning">{reader.error || 'Документ не найден.'}</p></div>
const title = legalDocument.subject || legalDocument.title
const warnings = legalDocument.warnings || []
const findText = (fragment: Fragment) => {
const raw = String(fragment.text || '')
if (!isHeadingDuplicated(fragment)) return fragmentText(fragment, searchQuery)
const newline = raw.search(/\r?\n/)
if (newline < 0) return null
const removed = newline + (raw[newline] === '\r' && raw[newline + 1] === '\n' ? 2 : 1)
return <div className="fragment-body">{renderAnchoredText(raw.slice(removed), (fragment.anchors || []).filter(anchor => anchor.offset >= removed).map(anchor => ({...anchor, offset: anchor.offset - removed})), searchQuery)}</div>
}
return <main className="wide-page reader-page">
<div className="reader-document-head"><div><p className="eyebrow">{labelKind(legalDocument.kind)}{legalDocument.number ? ` · № ${legalDocument.number}` : ''}</p><h1>{title}</h1><p className="muted">{legalDocument.title !== title ? legalDocument.title : ''}</p></div><div className="inline-actions"><button className="button quiet" onClick={() => setFocusMode(value => !value)} aria-pressed={focusMode}><Icon name="focus" /> {focusMode ? 'Выйти из режима чтения' : 'Сосредоточенное чтение'}</button><a className="button quiet" href={href({view: 'history', id: legalDocument.id})}>История редакций</a><button className="button quiet" onClick={() => void onUpdate(legalDocument.id).catch(error => onNotify(error instanceof Error ? error.message : 'Не удалось обновить документ.'))}>Обновить</button></div></div>
{warnings.length > 0 && <details className="notice warning"><summary>{warnings[0]} <span>Подробнее</span></summary><ul>{warnings.map(warning => <li key={warning}>{warning}</li>)}</ul></details>}
<div className="reader-mobile-actions"><button className="button quiet" onClick={() => setMobilePanel('toc')}><Icon name="menu" /> Оглавление</button><button className="button quiet" onClick={() => setMobilePanel('related')}>Связи</button></div>
<div className="reader-shell">
<div className={`reader-desktop-panel ${mobilePanel === 'toc' ? 'is-mobile-open' : ''}`}><Toc items={toc} documentId={legalDocument.id} activeId={activeId} filter={tocFilter} onFilter={setTocFilter} onSelect={selectFragment} /></div>
<article className="reader-center">
<div className="document-toolbar"><div className="inline-actions"><button className="button quiet" onClick={() => copy(visibleFragments.map(item => item.text || '').join('\n\n'), 'Текст скопирован')}><Icon name="copy" /> Копировать текст</button><button className="button quiet" onClick={() => copy(`${location.origin}${location.pathname}${docHref(legalDocument.id, activeId)}`, 'Ссылка скопирована')}>Копировать ссылку</button>{legalDocument.source_url && <a className="button quiet" href={safeURL(legalDocument.source_url)} target="_blank" rel="noopener noreferrer">Источник ↗</a>}</div><div className="size-controls" aria-label="Размер текста"><button onClick={() => setFontSize(value => Math.max(16, value - 2))} aria-label="Уменьшить текст">А−</button><span>{fontSize}</span><button onClick={() => setFontSize(value => Math.min(30, value + 2))} aria-label="Увеличить текст">А+</button></div></div>
<div className="reader-find"><label className="field grow"><span>Найти в документе</span><input ref={findRef} type="search" value={query} onChange={event => setQuery(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') void runSearch() }} placeholder="Слово или фраза" /></label><button className="button quiet" onClick={() => void runSearch()} disabled={wholeLoading}>Найти</button><button className="button quiet" onClick={() => navigateMatch(-1)} aria-label="Предыдущее совпадение">↑</button><button className="button quiet" onClick={() => navigateMatch(1)} aria-label="Следующее совпадение">↓</button><span className="reader-find-count" role="status" aria-live="polite">{matchCount ? (matchIndex >= 0 ? `${matchIndex + 1} из ${matchCount}` : `Совпадений: ${matchCount}`) : query ? 'Совпадений нет' : ''}</span>{wholeError && <span className="status-tag">{wholeError}</span>}</div>
<div className="reader-meta"><span>Редакция: <strong>{shortDate(legalDocument.revision)}</strong></span><span>Копия получена: {shortDate(legalDocument.retrieved_at)}</span><span>Проверка: {shortDate(legalDocument.last_checked)}</span>{legalDocument.effective_date && <span>Вступление в силу: {shortDate(legalDocument.effective_date)}</span>}</div>
{!allFragments.length && <button className="button primary" onClick={() => void loadWhole()} disabled={wholeLoading}>{wholeLoading ? 'Загружаем…' : 'Открыть весь документ'}</button>}
<div className="reading-text" style={{fontSize}}>{visibleFragments.length ? visibleFragments.map(fragment => <section className="text-fragment" id={fragment.id} key={fragment.id}><h2 className="fragment-heading">{fragment.label}</h2>{findText(fragment)}</section>) : <p className="help-note">Текст пока не загружен.</p>}</div>
</article>
<div className={`reader-desktop-panel ${mobilePanel === 'related' ? 'is-mobile-open' : ''}`}><Related edges={related.related || []} loading={relatedLoading} documentId={legalDocument.id} fragmentId={activeId} nodeId={related.node_id} /></div>
</div>
<Sheet open={mobilePanel !== null} onOpenChange={open => { if (!open) setMobilePanel(null) }}>
<SheetContent side={mobilePanel === 'toc' ? 'left' : 'right'} className="reader-mobile-sheet">
<SheetTitle>{mobilePanel === 'toc' ? 'Оглавление' : 'Связанные материалы'}</SheetTitle>
<SheetDescription className="sr-only">Навигационная панель документа</SheetDescription>
{mobilePanel === 'toc' ? <Toc items={toc} documentId={legalDocument.id} activeId={activeId} filter={tocFilter} onFilter={setTocFilter} onSelect={id => { selectFragment(id); setMobilePanel(null) }} /> : <Related edges={related.related || []} loading={relatedLoading} documentId={legalDocument.id} fragmentId={activeId} nodeId={related.node_id} />}
</SheetContent>
</Sheet>
</main>
}