107 lines
11 KiB
TypeScript
107 lines
11 KiB
TypeScript
import { useMemo, type ReactNode } from 'react'
|
|
import { docHref, href, kinds, shortDate, useApi, type LegalDocument, type ReaderData, type Route, type Kind } from '@/lib/api'
|
|
|
|
const pantheonKinds: Kind[] = ['code', 'federal-law', 'bylaw', 'plenum', 'review']
|
|
const plenaryTopics: Array<[string, RegExp]> = [
|
|
['Гражданское право', /гражданск|договор|недвижим|потребител/i],
|
|
['Гражданский процесс', /гражданск.{0,30}(процесс|судопроизвод)|исков|судебн.{0,20}расход/i],
|
|
['Уголовное право', /уголовн|преступлен|наказан/i],
|
|
['Уголовный процесс', /уголовн.{0,30}(процесс|судопроизвод)|следствен|доказательств/i],
|
|
['Экономические споры', /арбитраж|экономичес|банкрот|предприним/i],
|
|
['Административные дела', /административн|публичн|правонаруш/i],
|
|
['Трудовые споры', /трудов|работник|работодател/i],
|
|
['Семейные споры', /семейн|брак|алименты/i],
|
|
]
|
|
const stoneNames: Record<string, string> = {
|
|
'gk-rf': 'Гражданский кодекс', 'gpk-rf': 'Гражданский процессуальный кодекс',
|
|
'apk-rf': 'Арбитражный процессуальный кодекс', 'uk-rf': 'Уголовный кодекс',
|
|
'upk-rf': 'Уголовно-процессуальный кодекс', 'kas-rf': 'Кодекс административного судопроизводства',
|
|
'koap-rf': 'Кодекс об административных правонарушениях', 'tk-rf': 'Трудовой кодекс',
|
|
'sk-rf': 'Семейный кодекс', 'zhk-rf': 'Жилищный кодекс', 'zk-rf': 'Земельный кодекс',
|
|
'nk-rf-gosposhlina': 'Налоговый кодекс',
|
|
}
|
|
|
|
function slug(id: string) { return id.split(':').pop() || id }
|
|
function titleFor(document: LegalDocument) { return stoneNames[slug(document.id)] || document.subject || document.title }
|
|
function countWord(count: number) { return `${count} ${count % 10 === 1 && count % 100 !== 11 ? 'материал' : count % 10 >= 2 && count % 10 <= 4 && !(count % 100 >= 12 && count % 100 <= 14) ? 'материала' : 'материалов'}` }
|
|
|
|
export function Catalog({documents, route, search, aside, hero = false}: {documents: LegalDocument[]; route: Route; search?: ReactNode; aside?: ReactNode; hero?: boolean}) {
|
|
const selected = (route.kind as Kind) || 'code'
|
|
const docs = documents.filter(document => document.kind === selected)
|
|
return <section className="p-catalog" aria-labelledby="catalog-title">
|
|
{hero && <div className="p-hero"><div className="p-hero-copy"><p className="p-eyebrow">Локальная правовая библиотека</p><h1>Найти норму.<br />Понять контекст.</h1><p>Тексты актов, редакции и проверяемые связи в одном рабочем месте.</p>{search}</div><div className="p-hero-figure"><img src="/assets/pantheon/eunomia-marble.webp" alt="Эвномия" onError={event => { event.currentTarget.hidden = true }} /></div></div>}
|
|
{aside}
|
|
<div className="p-catalog-head"><div><p className="p-eyebrow">Библиотека</p><h2 id="catalog-title">Корпус документов</h2></div><span className="p-catalog-total">{countWord(documents.length)}</span></div>
|
|
<nav className="p-tabs" aria-label="Тип материала">{pantheonKinds.map(kind => <a key={kind} href={href({view: 'category', kind})} aria-current={selected === kind ? 'page' : undefined}>{kinds[kind][0]} <span>{documents.filter(document => document.kind === kind).length}</span></a>)}</nav>
|
|
{selected === 'code' ? <CodeCatalog documents={docs} /> : selected === 'plenum' ? <PlenumCatalog documents={docs} route={route} /> : <DocumentList documents={docs} route={route} />}
|
|
</section>
|
|
}
|
|
|
|
function corpusStatus(document: LegalDocument) {
|
|
if (!document.available) return 'Текст недоступен'
|
|
if (document.warnings?.length) return 'Есть предупреждения корпуса'
|
|
return 'Текст доступен'
|
|
}
|
|
|
|
function CodeCatalog({documents}: {documents: LegalDocument[]}) {
|
|
return <div className="p-stone-grid">{documents.map(document => {
|
|
const civil = slug(document.id) === 'gk-rf'
|
|
return <a className="p-stone" key={document.id} href={civil ? href({view: 'contents', id: document.id}) : docHref(document.id)}>
|
|
<div className="p-stone-image"><img src={`/assets/pantheon/${slug(document.id)}.webp`} alt="" loading="lazy" decoding="async" width="1536" height="1024" /></div>
|
|
<div className="p-stone-face"><strong>{titleFor(document)}</strong><span>{document.number || (civil ? 'Четыре части кодекса' : 'Кодекс Российской Федерации')}</span>
|
|
<small>{civil ? 'Редакции указаны в каждой части' : document.revision ? `Редакция ${shortDate(document.revision)}` : 'Редакция не указана'}</small><small>{corpusStatus(document)}</small>
|
|
</div>
|
|
</a>
|
|
})}</div>
|
|
}
|
|
|
|
function pageFromRoute(route: Route, pageCount: number) {
|
|
const value = Number(route.page)
|
|
return Number.isInteger(value) && value >= 1 && value <= pageCount ? value : 1
|
|
}
|
|
|
|
function PlenumCatalog({documents, route}: {documents: LegalDocument[]; route: Route}) {
|
|
const dateKey = (value?: string | null) => /^\d{2}\.\d{2}\.\d{4}$/.test(value || '') ? (value || '').split('.').reverse().join('-') : value || ''
|
|
const years = [...new Set(documents.map(document => dateKey(document.act_date).slice(0, 4)).filter(Boolean))].sort().reverse()
|
|
const sort = route.sort === 'old' ? 'old' : 'new'
|
|
const year = route.year && years.includes(route.year) ? route.year : ''
|
|
const topic = route.topic && plenaryTopics.some(([label]) => label === route.topic) ? route.topic : ''
|
|
const topicMatcher = plenaryTopics.find(([label]) => label === topic)?.[1]
|
|
const visible = documents.filter(document => {
|
|
const text = `${document.subject || ''} ${document.title}`
|
|
return (!year || (document.act_date || '').includes(year)) && (!topicMatcher || topicMatcher.test(text))
|
|
}).sort((a, b) => (sort === 'new' ? dateKey(b.act_date).localeCompare(dateKey(a.act_date)) : dateKey(a.act_date).localeCompare(dateKey(b.act_date))))
|
|
const pageCount = Math.max(1, Math.ceil(visible.length / 12))
|
|
const page = pageFromRoute(route, pageCount)
|
|
const setFilter = (patch: Partial<Record<'sort' | 'year' | 'topic', string | undefined>>) => { location.hash = href({...route, ...patch, page: undefined}) }
|
|
return <><div className="p-topic-grid" aria-label="Тематика пленумов">{plenaryTopics.map(([label, matcher]) => { const count = documents.filter(document => matcher.test(`${document.subject || ''} ${document.title}`)).length; return count ? <button className={`p-topic${topic === label ? ' is-active' : ''}`} type="button" key={label} aria-pressed={topic === label} onClick={() => setFilter({topic: topic === label ? undefined : label})}><strong>{label}</strong><span>{count}</span></button> : null })}</div><div className="p-filterbar"><label>Сортировка<select value={sort} onChange={event => setFilter({sort: event.target.value === 'new' ? undefined : event.target.value})}><option value="new">Сначала новые</option><option value="old">Сначала ранние</option></select></label><label>Год<select value={year} onChange={event => setFilter({year: event.target.value})}><option value="">Все годы</option>{years.map(value => <option key={value}>{value}</option>)}</select></label></div><DocumentRows documents={visible.slice((page - 1) * 12, page * 12)} /><Pagination page={page} pageCount={pageCount} total={visible.length} onChange={next => location.hash = href({...route, page: next})} /></>
|
|
}
|
|
|
|
function DocumentList({documents, route}: {documents: LegalDocument[]; route: Route}) {
|
|
const pageCount = Math.max(1, Math.ceil(documents.length / 12))
|
|
const page = pageFromRoute(route, pageCount)
|
|
return <><DocumentRows documents={documents.slice((page - 1) * 12, page * 12)} route={route} /><Pagination page={page} pageCount={pageCount} total={documents.length} onChange={next => location.hash = href({...route, page: next})} /></>
|
|
}
|
|
|
|
function Pagination({page, pageCount, total, onChange}: {page: number; pageCount: number; total: number; onChange: (page: number) => void}) {
|
|
return <div className="p-pagination" aria-label="Страницы"><span>{total} документов · страница {page} из {pageCount}</span><div className="p-pagination-actions"><button type="button" disabled={page <= 1} onClick={() => onChange(page - 1)}>Предыдущая</button><button type="button" disabled={page >= pageCount} onClick={() => onChange(page + 1)}>Следующая</button></div></div>
|
|
}
|
|
|
|
function DocumentRows({documents, route}: {documents: LegalDocument[]; route?: Route}) {
|
|
return <div className="p-document-list">{documents.map(document => <a className="p-document-row" key={document.id} href={docHref(document.id)}><span><strong>{document.subject || document.title}</strong><small>{document.number || 'Документ'} · {shortDate(document.act_date)}</small></span><span className="p-row-meta">{document.warnings?.length ? 'Требует сверки' : document.available ? 'Текст доступен' : 'Нет текста'}</span></a>)}{!documents.length && <p className="p-empty">Для этого типа пока нет материалов.</p>}</div>
|
|
}
|
|
|
|
export function Contents({documents, route}: {documents: LegalDocument[]; route: Route}) {
|
|
const id = route.doc || route.id || documents[0]?.id || null
|
|
const {data, loading, error} = useApi<ReaderData>(id ? `/reader?${new URLSearchParams({id, fragment: route.fragment || ''})}` : null)
|
|
const documentId = id || ''
|
|
const groups = useMemo(() => {
|
|
const toc = data?.toc || []
|
|
if (!documentId.endsWith('gk-rf')) return toc
|
|
return toc.filter(fragment => /^Часть\s+/i.test(fragment.label))
|
|
}, [data, documentId])
|
|
if (loading) return <section className="p-contents"><p>Загружаем оглавление…</p></section>
|
|
if (error || !data) return <section className="p-contents"><p className="p-empty">Оглавление пока недоступно.</p></section>
|
|
return <section className="p-contents" aria-labelledby="contents-title"><p className="p-eyebrow">Оглавление</p><h1 id="contents-title">{data.document.subject || data.document.title}</h1><div className="p-contents-list">{groups.map((fragment, index) => <a key={fragment.id} href={docHref(data.document.id, fragment.id)}><span>{String(index + 1).padStart(2, '0')}</span><strong>{fragment.label}</strong></a>)}</div></section>
|
|
}
|