release: Евномия, новая версия, линейка юристов
This commit is contained in:
@@ -0,0 +1 @@
|
||||
node_modules/
|
||||
@@ -0,0 +1,11 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#0067b9" />
|
||||
<meta name="description" content="Эвномия — локальная правовая библиотека" />
|
||||
<title>Эвномия — правовая библиотека</title>
|
||||
</head>
|
||||
<body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body>
|
||||
</html>
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Paco Coursey
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,43 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026 Lucide Icons and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
The following Lucide icons are derived from the Feather project:
|
||||
|
||||
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
|
||||
|
||||
The MIT License (MIT) (for the icons listed above)
|
||||
|
||||
Copyright (c) 2013-present Cole Bemis
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 WorkOS
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 shadcn
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Generated
+3329
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "eunomia",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview --host 127.0.0.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-dialog": "1.1.23",
|
||||
"@radix-ui/react-separator": "1.1.15",
|
||||
"@radix-ui/react-slot": "1.3.3",
|
||||
"@radix-ui/react-tooltip": "1.2.16",
|
||||
"class-variance-authority": "0.7.1",
|
||||
"clsx": "2.1.1",
|
||||
"cmdk": "1.1.1",
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8",
|
||||
"react-force-graph-2d": "^1.29.1",
|
||||
"react-force-graph-3d": "^1.29.1",
|
||||
"tailwind-merge": "3.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "4.3.3",
|
||||
"@types/node": "26.5.0",
|
||||
"@types/react": "19.2.18",
|
||||
"@types/react-dom": "19.2.7",
|
||||
"@vitejs/plugin-react": "6.1.1",
|
||||
"axe-core": "4.12.1",
|
||||
"tailwindcss": "4.3.3",
|
||||
"tw-animate-css": "1.4.0",
|
||||
"typescript": "7.0.2",
|
||||
"vite": "8.2.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useCallback, useEffect, useRef, useState, type CSSProperties } from 'react'
|
||||
import { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInset, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarProvider, useSidebar } from '@/components/ui/sidebar'
|
||||
import { CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { Icon } from '@/components/Icon'
|
||||
import { api, docHref, href, kinds, type Bootstrap, type Kind, type Route, type SearchData } from '@/lib/api'
|
||||
import { Home, Category, Contents } from '@/views/Library'
|
||||
import Reader from '@/views/Reader'
|
||||
import { Empty, Search, History, Graph, Updates } from '@/views/Research'
|
||||
|
||||
function readRoute(): Route {
|
||||
const route = Object.fromEntries(new URLSearchParams(location.hash.slice(1)))
|
||||
return {...route, view: route.doc ? 'reader' : route.view || 'home'}
|
||||
}
|
||||
const tools = [{view:'graph', title:'Связи документов'}, {view:'history',title:'История редакций'}, {view:'updates',title:'Обновления'}]
|
||||
|
||||
function Navigation({route, ready}: {route: Route; ready: boolean}) {
|
||||
const {setOpenMobile, state, toggleSidebar} = useSidebar()
|
||||
const links = [{view:'home', title:'Библиотека', icon:'home'}, ...Object.entries(kinds).map(([kind,value]) => ({view:'category',kind,title:value[0],icon:kind}))]
|
||||
const item = (link: {view:string;kind?:string;title:string;icon?:string}) => {
|
||||
const active = route.view===link.view && (!link.kind || link.kind===route.kind)
|
||||
return <SidebarMenuItem key={link.kind || link.view}><SidebarMenuButton asChild isActive={active} tooltip={link.title}><a href={href({view:link.view,kind:link.kind})} aria-current={active?'page':undefined} onClick={()=>setOpenMobile(false)}><Icon name={link.icon || link.view} /><span>{link.title}</span></a></SidebarMenuButton></SidebarMenuItem>
|
||||
}
|
||||
return <Sidebar collapsible="icon" className="eunomia-sidebar"><SidebarHeader><a className="brand-link" href={href({view:'home'})} onClick={()=>setOpenMobile(false)} aria-label="Эвномия — библиотека"><span className="brand-mark" aria-hidden="true">Э</span><span className="brand-copy group-data-[collapsible=icon]:hidden"><strong>Эвномия</strong><small>ПРАВОВАЯ БИБЛИОТЕКА</small></span></a></SidebarHeader><SidebarContent><SidebarGroup><SidebarGroupLabel>Библиотека</SidebarGroupLabel><SidebarGroupContent><SidebarMenu>{links.map(item)}</SidebarMenu></SidebarGroupContent></SidebarGroup><SidebarGroup><SidebarGroupLabel>Инструменты</SidebarGroupLabel><SidebarGroupContent><SidebarMenu>{tools.map(item)}</SidebarMenu></SidebarGroupContent></SidebarGroup></SidebarContent><SidebarFooter><div className="sidebar-status group-data-[collapsible=icon]:hidden"><span className={ready?'connection-dot ready':'connection-dot'} /><span>{ready?'Документы на компьютере':'Подключаем библиотеку'}</span></div><SidebarMenu><SidebarMenuItem><SidebarMenuButton onClick={toggleSidebar} tooltip={state==='expanded'?'Свернуть меню':'Развернуть меню'} aria-label={state==='expanded'?'Свернуть меню':'Развернуть меню'} aria-expanded={state==='expanded'}><Icon name="menu" /><span>Свернуть меню</span></SidebarMenuButton></SidebarMenuItem></SidebarMenu><small className="sidebar-brand-note group-data-[collapsible=icon]:hidden">Themiz · Эвномия</small></SidebarFooter></Sidebar>
|
||||
}
|
||||
function Shell({route, data, refresh, notify, busy, onAction}: {route:Route;data:Bootstrap;refresh:()=>void;notify:(s:string)=>void;busy:boolean;onAction:(kind:'update'|'graph',id?:string)=>Promise<void>}) {
|
||||
const {toggleSidebar, state, isMobile} = useSidebar()
|
||||
const [searchOpen,setSearchOpen] = useState(false), [query,setQuery] = useState(''), [results,setResults] = useState<SearchData | null>(null), [searching,setSearching] = useState(false), [searchError,setSearchError] = useState('')
|
||||
const mainRef = useRef<HTMLElement>(null)
|
||||
useEffect(()=>{
|
||||
const handle=(event:KeyboardEvent)=>{document.body.dataset.input='keyboard';if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()==='k'){event.preventDefault();setSearchOpen(open=>!open)}}
|
||||
const pointer=()=>{document.body.dataset.input='pointer'}
|
||||
document.addEventListener('keydown',handle);document.addEventListener('pointerdown',pointer)
|
||||
return()=>{document.removeEventListener('keydown',handle);document.removeEventListener('pointerdown',pointer)}
|
||||
},[])
|
||||
useEffect(()=>{
|
||||
if(!searchOpen){setQuery('');setResults(null);setSearchError('');setSearching(false);return}
|
||||
if(!query.trim()){setResults(null);setSearchError('');setSearching(false);return}
|
||||
let live=true;const controller=new AbortController();setSearching(true);setSearchError('')
|
||||
const timer=setTimeout(()=>{api<SearchData>('/search?'+new URLSearchParams({q:query}),{signal:controller.signal}).then(value=>{if(live)setResults(value)}).catch(error=>{if(live&&error.name!=='AbortError')setSearchError(error.message)}).finally(()=>{if(live)setSearching(false)})},180)
|
||||
return()=>{live=false;controller.abort();clearTimeout(timer)}
|
||||
},[query,searchOpen])
|
||||
useEffect(()=>{setSearchOpen(false);if(!route.doc)window.scrollTo({top:0,behavior:'instant'})},[route])
|
||||
const go=(url:string)=>{setSearchOpen(false);location.hash=url.slice(1)}
|
||||
const doc=data.documents.find(d=>d.id===(route.doc||route.id))
|
||||
const title=route.view==='category'?kinds[route.kind as Kind]?.[0]:doc?doc.subject||doc.title:({home:'Библиотека',search:'Поиск',graph:'Связи документов',history:'История редакций',updates:'Обновления'}[route.view]||'Библиотека')
|
||||
useEffect(()=>{document.title=`${title} — Эвномия`;document.body.dataset.view=route.view},[title,route.view])
|
||||
return <><a href="#main-content" className="skip-link" onClick={e=>{e.preventDefault();mainRef.current?.focus()}}>К содержанию</a><Navigation route={route} ready={!data.status.index?.indexing} /><SidebarInset className="eunomia-main"><header className="topbar"><Tooltip><TooltipTrigger asChild><Button id="menu-toggle" variant="ghost" size="icon" aria-label={isMobile?'Открыть навигацию':state==='expanded'?'Свернуть меню':'Развернуть меню'} aria-expanded={state==='expanded'} onClick={toggleSidebar}><Icon name="menu" /></Button></TooltipTrigger><TooltipContent>{isMobile?'Навигация':state==='expanded'?'Свернуть меню':'Развернуть меню'}</TooltipContent></Tooltip><nav className="breadcrumb" aria-label="Путь по разделам"><a href={href({view:'home'})}>Библиотека</a>{route.view!=='home'&&<><span aria-hidden="true">/</span><span aria-current="page">{title}</span></>}</nav><button className="search-launcher" onClick={()=>setSearchOpen(true)} aria-keyshortcuts="Meta+k Control+k" aria-label="Поиск по библиотеке"><Icon name="search" /><span>Поиск по библиотеке</span><kbd>⌘ K</kbd></button><Tooltip><TooltipTrigger asChild><Button variant="ghost" size="icon" disabled={busy} onClick={refresh} aria-label="Обновить сведения на экране"><Icon name="updates" /></Button></TooltipTrigger><TooltipContent>Обновить сведения на экране</TooltipContent></Tooltip></header><main id="main-content" className="content" tabIndex={-1} ref={mainRef}>{route.doc?<Reader key={route.doc} route={route} onNotify={notify} onUpdate={id=>onAction('update',id)} />:route.view==='category'?<Category route={route} docs={data.documents}/>:route.view==='contents'?<Contents route={route} docs={data.documents}/>:route.view==='search'?<Search route={route}/>:route.view==='history'?<History route={route} docs={data.documents}/>:route.view==='updates'?<Updates status={data.status} docs={data.documents} onAction={onAction}/>:route.view==='graph'?<Graph route={route}/>:<Home docs={data.documents}/>}</main></SidebarInset><CommandDialog open={searchOpen} onOpenChange={setSearchOpen}><CommandInput placeholder="Статья, название или фраза…" value={query} onValueChange={setQuery} aria-label="Запрос для поиска" /><CommandList>{query.trim()?<><CommandGroup heading="Поиск по текстам"><CommandItem value={`all ${query}`} onSelect={()=>go(href({view:'search',q:query.trim()}))}><Icon name="search" /><span>Все результаты по запросу «{query}»</span></CommandItem></CommandGroup><CommandSeparator/>{searching?<p className="command-status" role="status">Ищем…</p>:searchError?<p className="command-status" role="alert">{searchError}</p>:results?.results.length?<CommandGroup heading="Найденные фрагменты">{results.results.slice(0,6).map(row=><CommandItem key={row.id} value={`${query} ${row.id}`} onSelect={()=>go(docHref(row.resource_id,row.id))}><Icon name={row.kind}/><span><strong>{row.label}</strong><small>{row.document||row.title}</small></span></CommandItem>)}</CommandGroup>:<p className="command-status">Совпадений пока нет. Попробуйте другой запрос.</p>}</>:<><CommandGroup heading="Быстрый переход">{Object.entries(kinds).map(([kind,value])=><CommandItem key={kind} value={value[0]} onSelect={()=>go(href({view:'category',kind}))}><Icon name={kind}/><span>{value[0]}</span></CommandItem>)}</CommandGroup><CommandGroup heading="Примеры запросов">{['ст. 131 ГПК','ст. 395 ГК'].map(q=><CommandItem key={q} value={q} onSelect={()=>setQuery(q)}><Icon name="search"/>{q}</CommandItem>)}</CommandGroup></>}<CommandEmpty>Ничего не найдено.</CommandEmpty></CommandList><div className="command-footer"><span>↑ ↓ выбрать</span><span>Enter открыть</span><span>Esc закрыть</span></div></CommandDialog></>
|
||||
}
|
||||
export default function App() {
|
||||
const [route,setRoute]=useState(readRoute),[data,setData]=useState<Bootstrap|null>(null),[error,setError]=useState(''),[busy,setBusy]=useState(false),[message,setMessage]=useState('')
|
||||
const toastTimer=useRef<ReturnType<typeof setTimeout>|undefined>(undefined)
|
||||
const notify=useCallback((value:string)=>{clearTimeout(toastTimer.current);setMessage(value);toastTimer.current=setTimeout(()=>setMessage(''),5000)},[])
|
||||
useEffect(()=>()=>clearTimeout(toastTimer.current),[])
|
||||
useEffect(()=>{const change=()=>setRoute(readRoute());window.addEventListener('hashchange',change);return()=>window.removeEventListener('hashchange',change)},[])
|
||||
const refresh=useCallback(async()=>{setBusy(true);try{const value=await api<Bootstrap>('/bootstrap');setData(value);setError('')}catch(e){setError((e as Error).message)}finally{setBusy(false)}},[])
|
||||
useEffect(()=>{void refresh()},[refresh])
|
||||
useEffect(()=>{if(!data?.status.index?.indexing||data.documents.length)return;const timer=setTimeout(refresh,1500);return()=>clearTimeout(timer)},[data,refresh])
|
||||
const action=async(kind:'update'|'graph',id?:string)=>{try{const response=await api<{detail:string}>(kind==='graph'?'/graph/rebuild':'/update',{method:'POST',headers:{'Content-Type':'application/json','X-Eunomia-CSRF':data?.csrf||''},body:JSON.stringify(id?{id}:{})});notify(response.detail);await refresh()}catch(e){notify((e as Error).message)}}
|
||||
return <TooltipProvider delayDuration={300}><SidebarProvider className="eunomia-shell" style={{'--sidebar-width':'15rem','--sidebar-width-icon':'4rem'} as CSSProperties}>{data?.documents.length||data&&!data.status.index?.indexing?<Shell route={route} data={data} refresh={refresh} notify={notify} busy={busy} onAction={action}/>:<main className="content"><Empty title={error?'Не удалось подключиться к библиотеке':'Готовим библиотеку к чтению'}>{error||'Проверяем сохраненные документы.'}</Empty>{error&&<button className="button primary" onClick={refresh}>Повторить</button>}</main>}</SidebarProvider><div role="status" aria-live="polite" className={`toast ${message?'show':''}`}>{message}</div></TooltipProvider>
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
const positions: Record<string, number> = {home:0,code:1,'federal-law':2,bylaw:3,plenum:4,review:5,graph:6,history:7,updates:8,search:9,menu:10,arrow:11,copy:12,close:13,back:14,focus:15}
|
||||
export function Icon({name, className = ''}: {name: string; className?: string}) {
|
||||
const n = positions[name] ?? 2
|
||||
return <span aria-hidden="true" className={`ui-icon ${className}`} style={{'--icon-x': `${n % 4 * 100 / 3}%`, '--icon-y': `${Math.floor(n / 4) * 100 / 3}%`} as CSSProperties} />
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
return (
|
||||
<Comp
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
Button.displayName = "Button"
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,169 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { type DialogProps } from "@radix-ui/react-dialog"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
|
||||
import { Icon } from "@/pantheon/Icon"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Dialog, DialogContent } from "@/components/ui/dialog"
|
||||
|
||||
const Command = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Command.displayName = CommandPrimitive.displayName
|
||||
|
||||
type CommandDialogProps = DialogProps & {
|
||||
title?: string
|
||||
description?: string
|
||||
shouldFilter?: boolean
|
||||
}
|
||||
|
||||
const CommandDialog = ({
|
||||
children,
|
||||
title = "Поиск по библиотеке",
|
||||
description = "Найдите документ, статью или пункт.",
|
||||
shouldFilter = false,
|
||||
...props
|
||||
}: CommandDialogProps) => {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogContent
|
||||
title={title}
|
||||
description={description}
|
||||
className="overflow-hidden p-0 shadow-lg"
|
||||
>
|
||||
<Command shouldFilter={shouldFilter} className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
const CommandInput = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Input>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
|
||||
<Icon name="search" className="mr-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
|
||||
CommandInput.displayName = CommandPrimitive.Input.displayName
|
||||
|
||||
const CommandList = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.List
|
||||
ref={ref}
|
||||
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandList.displayName = CommandPrimitive.List.displayName
|
||||
|
||||
const CommandEmpty = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Empty>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
|
||||
>((props, ref) => (
|
||||
<CommandPrimitive.Empty
|
||||
ref={ref}
|
||||
className="py-6 text-center text-sm"
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandEmpty.displayName = CommandPrimitive.Empty.displayName
|
||||
|
||||
const CommandGroup = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Group>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Group
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandGroup.displayName = CommandPrimitive.Group.displayName
|
||||
|
||||
const CommandSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CommandSeparator.displayName = CommandPrimitive.Separator.displayName
|
||||
|
||||
const CommandItem = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandItem.displayName = CommandPrimitive.Item.displayName
|
||||
|
||||
const CommandShortcut = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
CommandShortcut.displayName = "CommandShortcut"
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
|
||||
import { Icon } from "@/pantheon/Icon"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Dialog = DialogPrimitive.Root
|
||||
|
||||
const DialogTrigger = DialogPrimitive.Trigger
|
||||
|
||||
const DialogPortal = DialogPrimitive.Portal
|
||||
|
||||
const DialogClose = DialogPrimitive.Close
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
|
||||
title?: string
|
||||
description?: string
|
||||
}
|
||||
>(({ className, children, title = "Диалог", description = "Диалоговое окно", ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<DialogTitle className="sr-only">{title}</DialogTitle>
|
||||
<DialogDescription className="sr-only">{description}</DialogDescription>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-3 top-3 flex size-11 items-center justify-center rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<Icon name="close" className="h-4 w-4" />
|
||||
<span className="sr-only">Закрыть</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
))
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName
|
||||
|
||||
const DialogHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-1.5 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DialogHeader.displayName = "DialogHeader"
|
||||
|
||||
const DialogFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DialogFooter.displayName = "DialogFooter"
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-lg font-semibold leading-none tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
Input.displayName = "Input"
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Separator = React.forwardRef<
|
||||
React.ElementRef<typeof SeparatorPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||
>(
|
||||
(
|
||||
{ className, orientation = "horizontal", decorative = true, ...props },
|
||||
ref
|
||||
) => (
|
||||
<SeparatorPrimitive.Root
|
||||
ref={ref}
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border",
|
||||
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
)
|
||||
Separator.displayName = SeparatorPrimitive.Root.displayName
|
||||
|
||||
export { Separator }
|
||||
@@ -0,0 +1,140 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { Icon } from "@/pantheon/Icon"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Sheet = SheetPrimitive.Root
|
||||
|
||||
const SheetTrigger = SheetPrimitive.Trigger
|
||||
|
||||
const SheetClose = SheetPrimitive.Close
|
||||
|
||||
const SheetPortal = SheetPrimitive.Portal
|
||||
|
||||
const SheetOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Overlay
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
))
|
||||
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
|
||||
|
||||
const sheetVariants = cva(
|
||||
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-150 data-[state=open]:duration-200",
|
||||
{
|
||||
variants: {
|
||||
side: {
|
||||
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
|
||||
bottom:
|
||||
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
||||
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
|
||||
right:
|
||||
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
side: "right",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
interface SheetContentProps
|
||||
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
|
||||
VariantProps<typeof sheetVariants> {}
|
||||
|
||||
const SheetContent = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Content>,
|
||||
SheetContentProps
|
||||
>(({ side = "right", className, children, ...props }, ref) => (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(sheetVariants({ side }), className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="absolute right-3 top-3 flex size-11 items-center justify-center rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||
<Icon name="close" className="h-4 w-4" />
|
||||
<span className="sr-only">Закрыть</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
))
|
||||
SheetContent.displayName = SheetPrimitive.Content.displayName
|
||||
|
||||
const SheetHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-2 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
SheetHeader.displayName = "SheetHeader"
|
||||
|
||||
const SheetFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
SheetFooter.displayName = "SheetFooter"
|
||||
|
||||
const SheetTitle = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SheetTitle.displayName = SheetPrimitive.Title.displayName
|
||||
|
||||
const SheetDescription = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SheetDescription.displayName = SheetPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetPortal,
|
||||
SheetOverlay,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
@@ -0,0 +1,773 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { Icon } from "@/pantheon/Icon"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
const SidebarProvider = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
>(
|
||||
(
|
||||
{
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile
|
||||
? setOpenMobile((open) => !open)
|
||||
: setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
)
|
||||
SidebarProvider.displayName = "SidebarProvider"
|
||||
|
||||
const Sidebar = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}
|
||||
>(
|
||||
(
|
||||
{
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full w-[var(--sidebar-width)] flex-col bg-sidebar text-sidebar-foreground",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-mobile="true"
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
document.getElementById("menu-toggle")?.focus()
|
||||
}}
|
||||
className={cn("w-[var(--sidebar-width)] bg-sidebar p-0 text-sidebar-foreground", className)}
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Навигация</SheetTitle>
|
||||
<SheetDescription>Основная навигация по библиотеке.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="group peer hidden text-sidebar-foreground md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative w-[var(--sidebar-width)] bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_1rem)]"
|
||||
: "group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)]"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-[var(--sidebar-width)] transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_1rem_+_2px)]"
|
||||
: "group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)] group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
)
|
||||
Sidebar.displayName = "Sidebar"
|
||||
|
||||
const SidebarTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof Button>,
|
||||
React.ComponentProps<typeof Button>
|
||||
>(({ className, onClick, ...props }, ref) => {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
data-sidebar="trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("h-7 w-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<Icon name="menu" />
|
||||
<span className="sr-only">Переключить боковую панель</span>
|
||||
</Button>
|
||||
)
|
||||
})
|
||||
SidebarTrigger.displayName = "SidebarTrigger"
|
||||
|
||||
const SidebarRail = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button">
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
data-sidebar="rail"
|
||||
aria-label="Переключить боковую панель"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Переключить боковую панель"
|
||||
className={cn(
|
||||
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
|
||||
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarRail.displayName = "SidebarRail"
|
||||
|
||||
const SidebarInset = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"main">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<main
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex w-full flex-1 flex-col bg-background",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarInset.displayName = "SidebarInset"
|
||||
|
||||
const SidebarInput = React.forwardRef<
|
||||
React.ElementRef<typeof Input>,
|
||||
React.ComponentProps<typeof Input>
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<Input
|
||||
ref={ref}
|
||||
data-sidebar="input"
|
||||
className={cn(
|
||||
"h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarInput.displayName = "SidebarInput"
|
||||
|
||||
const SidebarHeader = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarHeader.displayName = "SidebarHeader"
|
||||
|
||||
const SidebarFooter = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarFooter.displayName = "SidebarFooter"
|
||||
|
||||
const SidebarSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof Separator>,
|
||||
React.ComponentProps<typeof Separator>
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<Separator
|
||||
ref={ref}
|
||||
data-sidebar="separator"
|
||||
className={cn("mx-2 w-auto bg-sidebar-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarSeparator.displayName = "SidebarSeparator"
|
||||
|
||||
const SidebarContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarContent.displayName = "SidebarContent"
|
||||
|
||||
const SidebarGroup = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarGroup.displayName = "SidebarGroup"
|
||||
|
||||
const SidebarGroupLabel = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & { asChild?: boolean }
|
||||
>(({ className, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarGroupLabel.displayName = "SidebarGroupLabel"
|
||||
|
||||
const SidebarGroupAction = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button"> & { asChild?: boolean }
|
||||
>(({ className, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 after:md:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarGroupAction.displayName = "SidebarGroupAction"
|
||||
|
||||
const SidebarGroupContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarGroupContent.displayName = "SidebarGroupContent"
|
||||
|
||||
const SidebarMenu = React.forwardRef<
|
||||
HTMLUListElement,
|
||||
React.ComponentProps<"ul">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ul
|
||||
ref={ref}
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenu.displayName = "SidebarMenu"
|
||||
|
||||
const SidebarMenuItem = React.forwardRef<
|
||||
HTMLLIElement,
|
||||
React.ComponentProps<"li">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<li
|
||||
ref={ref}
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenuItem.displayName = "SidebarMenuItem"
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const SidebarMenuButton = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>
|
||||
>(
|
||||
(
|
||||
{
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="menu-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!tooltip || isMobile || state !== "collapsed") {
|
||||
return button
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
)
|
||||
SidebarMenuButton.displayName = "SidebarMenuButton"
|
||||
|
||||
const SidebarMenuAction = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
}
|
||||
>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 after:md:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarMenuAction.displayName = "SidebarMenuAction"
|
||||
|
||||
const SidebarMenuBadge = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenuBadge.displayName = "SidebarMenuBadge"
|
||||
|
||||
const SidebarMenuSkeleton = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}
|
||||
>(({ className, showIcon = false, ...props }, ref) => {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-[var(--skeleton-width)] flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton"
|
||||
|
||||
const SidebarMenuSub = React.forwardRef<
|
||||
HTMLUListElement,
|
||||
React.ComponentProps<"ul">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ul
|
||||
ref={ref}
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenuSub.displayName = "SidebarMenuSub"
|
||||
|
||||
const SidebarMenuSubItem = React.forwardRef<
|
||||
HTMLLIElement,
|
||||
React.ComponentProps<"li">
|
||||
>(({ ...props }, ref) => <li ref={ref} {...props} />)
|
||||
SidebarMenuSubItem.displayName = "SidebarMenuSubItem"
|
||||
|
||||
const SidebarMenuSubButton = React.forwardRef<
|
||||
HTMLAnchorElement,
|
||||
React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}
|
||||
>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarMenuSubButton.displayName = "SidebarMenuSubButton"
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
className={cn("animate-pulse rounded-md bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
@@ -0,0 +1,30 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const TooltipProvider = TooltipPrimitive.Provider
|
||||
|
||||
const Tooltip = TooltipPrimitive.Root
|
||||
|
||||
const TooltipTrigger = TooltipPrimitive.Trigger
|
||||
|
||||
const TooltipContent = React.forwardRef<
|
||||
React.ElementRef<typeof TooltipPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<TooltipPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[var(--radix-tooltip-content-transform-origin)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TooltipContent.displayName = TooltipPrimitive.Content.displayName
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
|
||||
return !!isMobile
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
export type Route = Record<string, string>
|
||||
export type Kind = 'code' | 'federal-law' | 'bylaw' | 'plenum' | 'review'
|
||||
export interface LegalDocument {
|
||||
id: string; title: string; subject?: string; kind: Kind; source_url?: string;
|
||||
revision?: string | null; act_date?: string | null; number?: string | null;
|
||||
available: boolean; integrity?: boolean; coverage?: {status?: string; scope?: string | null};
|
||||
warnings?: string[]; last_checked?: string | null; retrieved_at?: string | null; effective_date?: string | null;
|
||||
}
|
||||
export interface Anchor {id: string; label: string; offset: number}
|
||||
export interface Fragment {id: string; label: string; kind: string; text?: string; anchors?: Anchor[]}
|
||||
export interface ReaderData {document: LegalDocument; toc: Fragment[]; fragment: Fragment | null; selected_id: string | null}
|
||||
export interface SearchResult {id: string; resource_id: string; label: string; title: string; document: string; kind: Kind; snippet: string; revision?: string; warnings?: string[]}
|
||||
export interface SearchData {results: SearchResult[]; total: number}
|
||||
export interface GraphNode {id: string; label: string; resource_id: string; kind: string; document_kind?: Kind; document_title?: string; reader_id?: string | null; needs_review?: boolean}
|
||||
export interface Evidence {excerpt?: string; revision?: string; source_url?: string}
|
||||
export interface GraphEdge {source: string; target: string; relation?: string; evidence?: Evidence; source_node?: GraphNode; target_node?: GraphNode}
|
||||
export interface RelatedData {related: GraphEdge[]; loading?: boolean; node_id?: string}
|
||||
export interface StatusData {
|
||||
index?: {ready: boolean; indexing: boolean; error?: string};
|
||||
schedule?: {enabled: boolean; next_run?: string; next_due_at?: string; detail?: string};
|
||||
graph?: {available?: boolean; built_at?: string};
|
||||
queue?: Record<string, number>;
|
||||
jobs?: {id: string; state: string; detail?: string}[];
|
||||
practice?: PracticeStatus;
|
||||
}
|
||||
export interface PracticeStatus {
|
||||
ready: boolean; acts: number; links: number; error?: string;
|
||||
last_import?: {finished_at?: string; seconds?: number; added?: number; updated?: number; removed?: number; rejected?: number; watermark?: string} | null;
|
||||
build?: {meaning?: string; running?: boolean; attempted_at?: string; finished_at?: string; next_due?: string} | null;
|
||||
tick?: string | null;
|
||||
schedule?: {installed: boolean; interval_hours: number};
|
||||
}
|
||||
export interface PracticeCard {doc: string; title: string; kind: string; number?: string; act_date?: string | null; court?: string | null; area?: string | null; category?: string | null; excerpt?: string; subject?: string}
|
||||
export interface PracticeArticle {code: string; article: string; label: string; total?: number; reader?: {id: string; fragment: string} | null}
|
||||
export interface PracticeList {ready: boolean; items: PracticeCard[]; total: number; page: number; pages: number; terms: string[]; articles: PracticeArticle[]}
|
||||
export interface Facet {value: string; count: number}
|
||||
export interface PracticeFacets {ready: boolean; months: Facet[]; kinds: Facet[]; courts: Facet[]; categories: Facet[]}
|
||||
export interface PracticeLink {start: number; end: number; code: string; article: string}
|
||||
export interface PracticeActData {
|
||||
act: PracticeCard & {url: string; fetched_at?: string | null; lastmod?: string | null; sha256?: string | null; bytes?: number | null; verified: boolean; removed_at?: string | null; removed_code?: string | null};
|
||||
heading: string; court_line: string; text: string | null; links: PracticeLink[]; articles: PracticeArticle[];
|
||||
areas: {id: string; title: string; parent?: string | null; parent_title?: string | null; reason: string}[];
|
||||
}
|
||||
export interface PracticeNode {id: string; title: string; count: number}
|
||||
export interface PracticeTree {ready: boolean; total: number; productions: Facet[]; areas: (PracticeNode & {children: PracticeNode[]})[]}
|
||||
export interface PracticeAreaGraph {
|
||||
ready: boolean; area: PracticeNode; children: PracticeNode[]; productions: Facet[];
|
||||
intersections: {a: string; b: string; count: number}[];
|
||||
articles: {node: string; code: string; article: string; label: string; count: number}[];
|
||||
}
|
||||
export interface PracticeNorm {code: string | null; article: string | null; label?: string; total: number; ready: boolean}
|
||||
export type Action = 'update' | 'graph' | 'refresh'
|
||||
export interface Load {done: number; total: number; per_min: number; eta_min: number | null; updated_at: string; error?: string}
|
||||
export interface Walk {running: boolean; requested_at: string | null; stopped: string | null; at: string | null; next_due: string | null; found?: number | null}
|
||||
// Отметки свежести считает сервер по живому состоянию (eunomia/server.py: practice_freshness, law_freshness).
|
||||
export interface PracticeFreshness {fresh: boolean; label: string; as_of: string | null; interval_days: number}
|
||||
export interface LawFreshness {full: boolean; label: string; as_of: string | null; interval_days: number; missing: {id: string; title: string; reason: string}[]}
|
||||
export interface PracticeProgress extends Load {walk: Walk; freshness?: PracticeFreshness}
|
||||
export interface LawProgress extends Load {running: boolean; states: Record<string, number>; freshness?: LawFreshness}
|
||||
export interface Bootstrap {documents: LegalDocument[]; csrf: string; status: StatusData}
|
||||
export const kinds: Record<Kind, [string, string]> = {
|
||||
code: ['Кодексы', 'Основные отрасли права'],
|
||||
'federal-law': ['Федеральные законы', 'Законы по отдельным вопросам'],
|
||||
bylaw: ['Подзаконные акты', 'Постановления, приказы и правила'],
|
||||
plenum: ['Пленумы', 'Разъяснения по применению права'],
|
||||
review: ['Обзоры практики', 'Правовые позиции и выводы судов'],
|
||||
}
|
||||
export const normalized = (value = '') => value.toLocaleLowerCase('ru').replaceAll('ё', 'е')
|
||||
export function href(route: Record<string, string | number | undefined | null>) {
|
||||
return '#' + new URLSearchParams(Object.entries(route).filter(([,v]) => v !== undefined && v !== null && v !== '').map(([k,v]) => [k, String(v)])).toString()
|
||||
}
|
||||
export const docHref = (id: string, fragment?: string | null) => href({doc: id, fragment})
|
||||
export const shortDate = (value?: string | null) => {
|
||||
if (!value) return 'не указана'
|
||||
if (/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return value
|
||||
const date = new Date(value)
|
||||
return Number.isNaN(+date) ? value : date.toLocaleDateString('ru-RU')
|
||||
}
|
||||
export const docCount = (n: number) => `${n} ${n % 10 === 1 && n % 100 !== 11 ? 'документ' : n % 10 >= 2 && n % 10 <= 4 && !(n % 100 >= 12 && n % 100 <= 14) ? 'документа' : 'документов'}`
|
||||
export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const response = await fetch('/api' + path, {...options, headers: {Accept: 'application/json', ...options.headers}})
|
||||
const data = await response.json()
|
||||
if (!response.ok) throw new Error(data.error || 'Не удалось получить данные. Попробуйте снова.')
|
||||
return data as T
|
||||
}
|
||||
export function useApi<T>(path: string | null) {
|
||||
const [state, setState] = useState<{data: T | null; error: string; loading: boolean}>({data: null, error: '', loading: true})
|
||||
useEffect(() => {
|
||||
if (!path) { setState({data: null, error: '', loading: false}); return }
|
||||
const controller = new AbortController(); let live = true
|
||||
setState({data: null, error: '', loading: true})
|
||||
api<T>(path, {signal: controller.signal}).then(data => {if(live)setState({data, error: '', loading: false})}).catch(error => {if(live && error.name !== 'AbortError')setState({data: null, error: error.message, loading: false})})
|
||||
return () => {live = false; controller.abort()}
|
||||
}, [path])
|
||||
return state
|
||||
}
|
||||
// Опрос, пока экран открыт: прежние данные остаются до нового ответа, скрытая вкладка запросов не шлет.
|
||||
export function usePoll<T>(path: string, ms: number) {
|
||||
const [state, setState] = useState<{data: T | null; error: string}>({data: null, error: ''})
|
||||
const [round, setRound] = useState(0)
|
||||
useEffect(() => {
|
||||
const controller = new AbortController(); let timer = 0
|
||||
const load = async () => {
|
||||
if (!document.hidden) {
|
||||
try { const data = await api<T>(path, {signal: controller.signal}); setState({data, error: ''}) }
|
||||
catch (error) { if ((error as Error).name !== 'AbortError') setState(old => ({...old, error: (error as Error).message})) }
|
||||
}
|
||||
if (!controller.signal.aborted) timer = window.setTimeout(load, ms)
|
||||
}
|
||||
void load()
|
||||
return () => {controller.abort(); clearTimeout(timer)}
|
||||
}, [path, ms, round])
|
||||
return {...state, reload: () => setRound(n => n + 1)}
|
||||
}
|
||||
export function safeURL(value?: string) {
|
||||
try {const url = new URL(value || ''); return ['https:', 'http:'].includes(url.protocol) ? url.href : '#'} catch {return '#'}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { clsx, type ClassValue } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) }
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import App from './pantheon/App'
|
||||
import './pantheon/pantheon.css'
|
||||
import './pantheon/atmosphere.css'
|
||||
import './pantheon/atomic.css'
|
||||
import './pantheon/tricolor.css'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(<App />)
|
||||
@@ -0,0 +1,87 @@
|
||||
import {lazy, Suspense, useCallback, useEffect, useState, type CSSProperties} from 'react'
|
||||
import {Sidebar, SidebarContent, SidebarFooter, SidebarHeader, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarProvider, useSidebar} from '@/components/ui/sidebar'
|
||||
import {TooltipProvider} from '@/components/ui/tooltip'
|
||||
import {api, docHref, href, type Action, type Bootstrap, type Route} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import {SearchBox} from './SearchBox'
|
||||
import {Catalog, Contents} from './Catalog'
|
||||
import Document from './Document'
|
||||
import {Results, Editions, Service, RecentView} from './Research'
|
||||
import {PracticeAct, PracticeTeaser, PracticeView} from './Practice'
|
||||
import {remember, recentItems, clearRecent, type Recent} from './storage'
|
||||
|
||||
const Connections = lazy(() => import('./Connections').then(module => ({default:module.Connections})))
|
||||
function readRoute(): Route {
|
||||
const route = Object.fromEntries(new URLSearchParams(location.hash.slice(1)))
|
||||
return {...route, view:route.doc ? 'reader' : route.view || 'home'}
|
||||
}
|
||||
const nav = [{view:'home',title:'Библиотека',icon:'library'}, {view:'practice',title:'Судебная практика',icon:'document'}, {view:'recent',title:'Недавнее',icon:'history'}, {view:'graph',title:'Граф знаний',icon:'graph'}]
|
||||
function Navigation({route}: {route:Route}) {
|
||||
const {setOpenMobile,state,toggleSidebar} = useSidebar()
|
||||
const item = (view:string,title:string,icon:string) => <SidebarMenuItem key={view}>
|
||||
<SidebarMenuButton asChild isActive={view==='home' ? ['home','category','contents'].includes(route.view) : view==='practice' ? ['practice','act'].includes(route.view) : view===route.view} tooltip={title}>
|
||||
<a href={href({view})} onClick={() => setOpenMobile(false)} aria-current={route.view===view?'page':undefined}><Icon name={icon}/><span>{title}</span></a>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
return <Sidebar collapsible="icon" className="p-sidebar" role="navigation" aria-label="Меню библиотеки">
|
||||
<SidebarHeader><a href={href({view:'home'})} className="p-brand" aria-label="Эвномия — главная" onClick={() => setOpenMobile(false)}>
|
||||
<span className="p-monogram" aria-hidden="true">Э</span><span className="p-brand-name"><strong>Эвномия</strong><small>ПАНТЕОН · THEMIZ</small></span>
|
||||
</a></SidebarHeader>
|
||||
<SidebarContent><SidebarMenu>{nav.map(x => item(x.view,x.title,x.icon))}</SidebarMenu></SidebarContent>
|
||||
<SidebarFooter><SidebarMenu>{item('updates','Состояние базы','updates')}<SidebarMenuItem>
|
||||
<SidebarMenuButton onClick={toggleSidebar} tooltip={state==='expanded'?'Свернуть меню':'Развернуть меню'} aria-label={state==='expanded'?'Свернуть меню':'Развернуть меню'}><Icon name="menu"/><span>Свернуть меню</span></SidebarMenuButton>
|
||||
</SidebarMenuItem></SidebarMenu><div className="p-sidebar-note"><span/>Локальная библиотека</div></SidebarFooter>
|
||||
</Sidebar>
|
||||
}
|
||||
function Surface({data,route,onNotify,refresh}: {data:Bootstrap;route:Route;onNotify:(s:string)=>void;refresh:()=>Promise<void>}) {
|
||||
const {toggleSidebar,openMobile,state,isMobile} = useSidebar()
|
||||
const [recent,setRecent] = useState<Recent[]>(recentItems)
|
||||
const onRecent = useCallback((id:string,fragment?:string) => {setRecent(remember(id,fragment))},[])
|
||||
const isHome = route.view==='home'
|
||||
const title = ({home:'Библиотека',category:'Библиотека',contents:'Оглавление',reader:'Чтение',search:'Результаты поиска',recent:'Недавнее',graph:'Граф знаний',history:'Редакции',updates:'Состояние базы',practice:'Судебная практика',act:'Судебный акт'}[route.view] || 'Библиотека')
|
||||
useEffect(() => {document.title=`${title} · Эвномия`; if(route.view!=='reader') window.scrollTo({top:0,behavior:'instant'})},[route,title])
|
||||
const action = async (kind:Action) => {
|
||||
const response = await api<{detail:string}>({update:'/update',graph:'/graph/rebuild',refresh:'/practice/refresh'}[kind],{method:'POST',headers:{'Content-Type':'application/json','X-Eunomia-CSRF':data.csrf},body:'{}'})
|
||||
onNotify(response.detail); if(kind!=='refresh') await refresh() // полосы опрашивают свои маршруты сами
|
||||
}
|
||||
return <>
|
||||
<a className="p-skip" href="#p-main" onClick={e => {e.preventDefault();document.getElementById('p-main')?.focus()}}>К содержанию</a>
|
||||
<Navigation route={route}/>
|
||||
<div className="p-surface">
|
||||
<header className="p-topbar">
|
||||
<button className="p-icon-button" id="menu-toggle" onClick={toggleSidebar} aria-label={isMobile?'Открыть меню':state==='expanded'?'Свернуть меню':'Развернуть меню'} aria-expanded={isMobile?openMobile:state==='expanded'}><Icon name="menu"/></button>
|
||||
<nav aria-label="Путь" className="p-breadcrumb"><a href={href({view:'home'})}>Эвномия</a><span aria-hidden="true">/</span><span>{title}</span></nav>
|
||||
{!isHome && <SearchBox initialQuery={route.view==='search' ? route.q : ''}/>}
|
||||
{isHome && <span className="p-local-note"><span/>Документы на вашем компьютере</span>}
|
||||
</header>
|
||||
<main id="p-main" tabIndex={-1} className={`p-main ${route.view==='reader'?'p-main-reading':route.view==='graph'?'p-main-graph':''}`}>
|
||||
{route.doc ? <Document key={route.doc} route={route} onNotify={onNotify} onRecent={onRecent}/> :
|
||||
route.view==='contents' ? <Contents documents={data.documents} route={route}/> :
|
||||
route.view==='search' ? <Results route={route}/> :
|
||||
route.view==='practice' ? <PracticeView route={route}/> :
|
||||
route.view==='act' ? <PracticeAct key={route.act} route={route}/> :
|
||||
route.view==='graph' ? <Suspense fallback={<p role="status">Загружаем граф знаний…</p>}><Connections route={route}/></Suspense> :
|
||||
route.view==='history' ? <Editions documents={data.documents} route={route}/> :
|
||||
route.view==='updates' ? <Service data={data} onAction={action}/> :
|
||||
route.view==='recent' ? <RecentView documents={data.documents} recent={recent} onClear={() => {clearRecent();setRecent([])}}/> :
|
||||
<Catalog documents={data.documents} route={route} hero={isHome} search={isHome?<SearchBox large/>:undefined} aside={isHome?<PracticeTeaser status={data.status.practice}/>:undefined}/>}
|
||||
</main>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
export default function App() {
|
||||
const [route,setRoute] = useState(readRoute)
|
||||
const [data,setData] = useState<Bootstrap|null>(null)
|
||||
const [error,setError] = useState('')
|
||||
const [message,setMessage] = useState('')
|
||||
const refresh = useCallback(async () => {
|
||||
try {setData(await api<Bootstrap>('/bootstrap'));setError('')} catch(e) {setError((e as Error).message)}
|
||||
},[])
|
||||
useEffect(() => {void refresh()},[refresh])
|
||||
useEffect(() => {const handle=()=>setRoute(readRoute());window.addEventListener('hashchange',handle);return()=>window.removeEventListener('hashchange',handle)},[])
|
||||
useEffect(() => {if(!data?.status.index?.indexing || data.documents.length) return;const timer=setTimeout(refresh,1500);return()=>clearTimeout(timer)},[data,refresh])
|
||||
useEffect(() => {if(!message)return;const timer=setTimeout(()=>setMessage(''),5000);return()=>clearTimeout(timer)},[message])
|
||||
return <TooltipProvider delayDuration={300}><SidebarProvider className="p-app" style={{'--sidebar-width':'224px','--sidebar-width-icon':'72px'} as CSSProperties}>
|
||||
{data && (data.documents.length || !data.status.index?.indexing) ? <Surface data={data} route={route} onNotify={setMessage} refresh={refresh}/> : <div className="p-start-state"><span className="p-monogram">Э</span><h1>{error?'Библиотека недоступна':'Открываем библиотеку'}</h1><p>{error||'Подготавливаем сохраненные тексты.'}</p>{error&&<button className="p-button p-primary" onClick={refresh}>Повторить</button>}</div>}
|
||||
</SidebarProvider><div role="status" aria-live="polite" className={`p-toast ${message?'is-visible':''}`}>{message}</div></TooltipProvider>
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
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>
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import {Component, lazy, Suspense, useEffect, useMemo, useRef, useState, type ReactNode} from 'react'
|
||||
import ForceGraph2D, {type ForceGraphMethods as Graph2D, type LinkObject} from 'react-force-graph-2d'
|
||||
import type {ForceGraphMethods as Graph3D} from 'react-force-graph-3d'
|
||||
import {api, docHref, href, kinds, safeURL, shortDate, type GraphEdge, type GraphNode, type Route} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import './connections.css'
|
||||
|
||||
type NetworkNode = GraphNode & {x?:number; y?:number; z?:number; aliases?:string[]; document_number?:string; document_date?:string}
|
||||
type LinkMeta = Omit<GraphEdge, 'source'|'target'> & {count?:number}
|
||||
type NetworkLink = LinkObject<NetworkNode, LinkMeta>
|
||||
type Level = 'documents'|'atoms'
|
||||
interface NetworkData {level?:Level; status?:string; note?:string; focus_id?:string; nodes:NetworkNode[]; edges:GraphEdge[]; total_nodes:number; total_edges:number; truncated?:boolean; stale?:boolean; loading?:boolean; warnings?:{problem?:string; output?:string}[]}
|
||||
const ForceGraph3D = lazy(() => import('react-force-graph-3d').then(module => ({default:module.default<NetworkNode, LinkMeta>})))
|
||||
const nodeLabel = (node:NetworkNode) => {
|
||||
const label=node.label&&!/^(doc:|legal-corpus:)/.test(node.label)?node.label:node.document_title||'Документ'
|
||||
if(node.kind!=='point')return label
|
||||
const point=label.match(/^(?:Пункт|п\.)\s*(\d+(?:\.\d+)*)/i)?.[1]
|
||||
const article=node.id.match(/:article:(\d+(?:\.\d+)*):/)?.[1]
|
||||
return point?'Пункт '+point+(article?' статьи '+article:''):label
|
||||
}
|
||||
const linkId = (value:NetworkLink['source']) => typeof value === 'object' ? value.id : value
|
||||
const graphStyle=getComputedStyle(document.documentElement)
|
||||
const graphColors={blue:graphStyle.getPropertyValue('--accent').trim(),red:graphStyle.getPropertyValue('--red').trim(),point:graphStyle.getPropertyValue('--graph-point').trim(),canvas:graphStyle.getPropertyValue('--graph-canvas').trim(),ink:graphStyle.getPropertyValue('--ink').trim()}
|
||||
const nodeColor = (node:NetworkNode) => node.document_kind === 'plenum' ? graphColors.red : node.kind === 'point' ? graphColors.point : graphColors.blue
|
||||
const tooltip = (node:NetworkNode) => {const span=document.createElement('span');span.textContent=nodeLabel(node)+(node.kind!=='document'?' · '+(node.document_title||''):'');return span.innerHTML}
|
||||
class WebGLBoundary extends Component<{children:ReactNode;onFallback:()=>void},{failed:boolean}> {
|
||||
state={failed:false}
|
||||
static getDerivedStateFromError(){return {failed:true}}
|
||||
render(){return this.state.failed ? <div className="p-connection-state" role="alert"><p>Объемный граф недоступен в этом браузере.</p><button className="p-button" onClick={this.props.onFallback}>Открыть 2D</button></div> : this.props.children}
|
||||
}
|
||||
|
||||
export function Connections({route}:{route:Route}) {
|
||||
const [query,setQuery]=useState(route.q||''), [mode,setMode]=useState<'graph'|'list'>('graph'), [threeD,setThreeD]=useState(false)
|
||||
const [selected,setSelected]=useState(route.node_id||''), [data,setData]=useState<NetworkData|null>(null), [error,setError]=useState(''), [retry,setRetry]=useState(0)
|
||||
const level:Level=route.level==='documents'?'documents':'atoms'
|
||||
const withStructure=route.include_contains!=='0'
|
||||
const path='/graph/network?'+new URLSearchParams({level,limit:'1000',include_contains:withStructure?'1':'0',...(route.fragment?{fragment:route.fragment}:{}),...(route.resource_id?{resource_id:route.resource_id}:{}),...(route.node_id?{node_id:route.node_id}:{}),...(route.q?{q:route.q}:{}),...(route.kind?{kind:route.kind}:{})})
|
||||
useEffect(()=>setQuery(route.q||''),[route.q])
|
||||
useEffect(()=>{
|
||||
const controller=new AbortController();let timer:ReturnType<typeof setTimeout>
|
||||
setData(null);setError('');setSelected(route.node_id||'')
|
||||
const fetchNetwork=()=>api<NetworkData>(path,{signal:controller.signal}).then(value=>{
|
||||
if(controller.signal.aborted)return
|
||||
if(value.loading&&!value.nodes.length){timer=setTimeout(fetchNetwork,700);return}
|
||||
setData(value);setSelected(value.focus_id||route.node_id||'')
|
||||
}).catch(reason=>{if(!controller.signal.aborted)setError(reason.message)})
|
||||
fetchNetwork();return()=>{controller.abort();clearTimeout(timer)}
|
||||
},[path,retry])
|
||||
const navigate=(next:Record<string,string|undefined>)=>{location.hash=href({view:'graph',level,fragment:route.fragment,include_contains:route.include_contains,...(route.resource_id?{resource_id:route.resource_id}:{}),...(route.node_id?{node_id:route.node_id}:{}),q:route.q,kind:route.kind,...next})}
|
||||
return <section className="p-connections" aria-labelledby="connections-title">
|
||||
<header className="p-connections-head"><div><p className="p-eyebrow">Статьи, пункты и точные ссылки</p><h1 id="connections-title">Граф знаний</h1><p>{level==='atoms'?'Каждая точка — отдельная статья или пункт. Найдите норму или откройте ее граф из текста.':'Сводный обзор документов. Для точных связей переключитесь на статьи и пункты.'}</p></div><div className="p-connection-actions" aria-label="Вид графа"><button className="p-button" aria-pressed={mode==='graph'&&!threeD} onClick={()=>{setMode('graph');setThreeD(false)}}>2D</button><button className="p-button" aria-pressed={mode==='graph'&&threeD} onClick={()=>{setMode('graph');setThreeD(true)}}>3D</button><button className="p-button" aria-pressed={mode==='list'} onClick={()=>setMode('list')}>Список</button></div></header>
|
||||
<form className="p-connection-filters" onSubmit={e=>{e.preventDefault();navigate({q:query||undefined,node_id:undefined,fragment:undefined,resource_id:undefined})}}><label className="p-field"><span>Поиск узлов</span><input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Например, ст. 395 ГК или ст. 131 ГПК"/></label><label className="p-field"><span>Слой</span><select value={level} onChange={e=>navigate({level:e.target.value,node_id:undefined,fragment:undefined,resource_id:undefined})}><option value="atoms">Статьи и пункты</option><option value="documents">Обзор документов</option></select></label><label className="p-field"><span>Тип</span><select value={route.kind||''} onChange={e=>navigate({kind:e.target.value||undefined})}><option value="">Все типы</option>{Object.entries(kinds).map(([key,value])=><option key={key} value={key}>{value[0]}</option>)}</select></label><button className="p-button p-button-primary" type="submit"><Icon name="search"/>Найти</button></form>
|
||||
{level==='atoms'&&<label className="p-structure-toggle"><input type="checkbox" checked={withStructure} onChange={e=>navigate({include_contains:e.target.checked?'1':'0'})}/>Показывать состав статьи и вложенные пункты</label>}
|
||||
{(route.resource_id||route.node_id||route.fragment||route.q||route.kind)&&<div className="p-graph-scope"><span>{route.node_id||route.fragment?'Связи выбранной нормы':route.resource_id?'Статьи документа':'Результаты поиска норм'}</span><a href={href({view:'graph'})}>Общий граф</a></div>}
|
||||
{data?.stale&&<p className="p-connection-notice">После сборки исходные тексты изменились. Связи требуют сверки.</p>}
|
||||
{!!data?.warnings?.length&&<details className="p-connection-warnings"><summary>Проверка источников · {data.warnings.length}</summary>{data.warnings.map((warning,i)=><p key={i}>{warning.problem||warning.output||'Источник требует сверки.'}</p>)}</details>}
|
||||
{error?<div className="p-connection-state" role="alert"><strong>Граф недоступен</strong><p>{error}</p><button className="p-button" onClick={()=>setRetry(n=>n+1)}>Повторить</button></div>:!data?<p className="p-connection-state" role="status">Загружаем узлы и связи…</p>:!data.nodes.length?<p className="p-connection-state">{data.status==='focus_not_found'?'Этот фрагмент еще не выделен в графе. Связи всего документа вместо него не подставляются.':'Узлы не найдены. Измените запрос или фильтры.'}</p>:<NetworkContent key={path} data={data} mode={mode} threeD={threeD} selected={selected} onSelect={setSelected} onFallback={()=>setThreeD(false)}/>}
|
||||
</section>
|
||||
}
|
||||
|
||||
function NetworkContent({data,mode,threeD,selected,onSelect,onFallback}:{data:NetworkData;mode:'graph'|'list';threeD:boolean;selected:string;onSelect:(id:string)=>void;onFallback:()=>void}) {
|
||||
const [hover,setHover]=useState(''), [reduced,setReduced]=useState(()=>matchMedia('(prefers-reduced-motion: reduce)').matches)
|
||||
const [paused,setPaused]=useState(reduced), [settled,setSettled]=useState(false), [size,setSize]=useState({width:640,height:540})
|
||||
const [showIsolated,setShowIsolated]=useState(false)
|
||||
const labelRects=useRef<{x:number;y:number;width:number;height:number}[]>([])
|
||||
const canvasRef=useRef<HTMLDivElement>(null), ref2=useRef<Graph2D<NetworkNode,LinkMeta>|undefined>(undefined), ref3=useRef<Graph3D<NetworkNode,LinkMeta>|undefined>(undefined), fitted=useRef(false)
|
||||
// Force libraries mutate their data. Preserve the API snapshot when switching dimensions.
|
||||
const degree=useMemo(()=>{const result=new Map<string,number>();data.edges.forEach(link=>{result.set(link.source,(result.get(link.source)||0)+1);result.set(link.target,(result.get(link.target)||0)+1)});return result},[data])
|
||||
const isolated=data.nodes.filter(node=>!degree.has(node.id)).length
|
||||
const graphData=useMemo(()=>({nodes:data.nodes.filter(node=>node.id===data.focus_id||showIsolated||!data.edges.length||degree.has(node.id)).map(node=>({...node})),links:data.edges.map(link=>({...link})) as NetworkLink[]}),[data,threeD,showIsolated,degree])
|
||||
const focus=hover||selected
|
||||
const focusFamily=useMemo(()=>new Set(data.nodes.filter(node=>node.id===focus||(data.nodes.find(item=>item.id===focus)?.kind==='article'&&node.id.startsWith(focus+':'))).map(node=>node.id)),[data,focus])
|
||||
const neighbors=useMemo(()=>{const result=new Set(focusFamily);data.edges.forEach(link=>{if(focusFamily.has(link.source))result.add(link.target);if(focusFamily.has(link.target))result.add(link.source)});return result},[data,focusFamily])
|
||||
const selectedNode=data.nodes.find(node=>node.id===selected), duration=reduced?0:240
|
||||
const fit=()=>{(threeD?ref3.current:ref2.current)?.zoomToFit(duration,36)}
|
||||
useEffect(()=>{const media=matchMedia('(prefers-reduced-motion: reduce)');const change=()=>{setReduced(media.matches);if(media.matches)setPaused(true)};media.addEventListener('change',change);return()=>media.removeEventListener('change',change)},[])
|
||||
useEffect(()=>{const element=canvasRef.current;if(!element)return;const observer=new ResizeObserver(([entry])=>{setSize({width:Math.max(1,Math.floor(entry.contentRect.width)),height:Math.max(1,Math.floor(entry.contentRect.height))})});observer.observe(element);return()=>observer.disconnect()},[mode,threeD])
|
||||
useEffect(()=>{fitted.current=false;setSettled(false);setHover('')},[graphData,mode,threeD])
|
||||
useEffect(()=>{if(!fitted.current)return;const timer=setTimeout(fit,50);return()=>clearTimeout(timer)},[size.width,size.height])
|
||||
const onStop=()=>{setSettled(true);if(!fitted.current){fitted.current=true;fit()}}
|
||||
const togglePhysics=()=>{if(paused||settled){setPaused(false);setSettled(false);(threeD?ref3.current:ref2.current)?.d3ReheatSimulation()}else setPaused(true)}
|
||||
const zoom=(factor:number)=>{
|
||||
if(!threeD){const graph=ref2.current;if(graph)graph.zoom(Math.max(.05,Math.min(20,graph.zoom()*factor)),duration);return}
|
||||
const graph=ref3.current;if(!graph)return
|
||||
const camera=graph.camera(), controls=graph.controls() as {target?:{x:number;y:number;z:number}}, target=controls.target||{x:0,y:0,z:0}
|
||||
graph.cameraPosition({x:target.x+(camera.position.x-target.x)/factor,y:target.y+(camera.position.y-target.y)/factor,z:target.z+(camera.position.z-target.z)/factor},target,duration)
|
||||
}
|
||||
const colored=(node:NetworkNode)=>focus&&!neighbors.has(node.id)?'#d4dfed':node.id===focus?graphColors.blue:nodeColor(node)
|
||||
const paintLabel=(node:NetworkNode,ctx:CanvasRenderingContext2D,scale:number)=>{
|
||||
const radius=1.6*Math.sqrt(3+Math.sqrt(degree.get(node.id)||0)*2)
|
||||
ctx.beginPath();ctx.arc(node.x||0,node.y||0,radius,0,Math.PI*2)
|
||||
ctx.strokeStyle=node.id===focus?graphColors.red:graphColors.blue;ctx.lineWidth=(node.id===focus?2:1)/scale;ctx.stroke()
|
||||
if(node.id!==focus&&graphData.nodes.length>70&&scale<2)return
|
||||
const label=compactLabel(node), text=label.length>52?label.slice(0,49)+'…':label
|
||||
ctx.font=`${node.id===focus?500:400} ${11/scale}px Golos Text`
|
||||
const width=ctx.measureText(text).width+8/scale, height=15/scale
|
||||
const box={x:(node.x||0)-width/2,y:(node.y||0)+radius+5/scale,width,height}
|
||||
if(node.id!==focus&&labelRects.current.some(other=>box.x<other.x+other.width&&box.x+box.width>other.x&&box.y<other.y+other.height&&box.y+box.height>other.y))return
|
||||
labelRects.current.push(box);ctx.fillStyle=graphColors.canvas;ctx.fillRect(box.x,box.y,box.width,box.height)
|
||||
ctx.fillStyle=graphColors.ink;ctx.textAlign='center';ctx.fillText(text,node.x||0,box.y+11/scale)
|
||||
}
|
||||
const linked=(link:NetworkLink)=>focus&&(focusFamily.has(String(linkId(link.source)))||focusFamily.has(String(linkId(link.target))))
|
||||
const common={graphData,width:size.width,height:size.height,backgroundColor:graphColors.canvas,nodeLabel:tooltip,nodeColor:colored,nodeVal:(node:NetworkNode)=>3+Math.sqrt(degree.get(node.id)||0)*2,linkColor:(link:NetworkLink)=>linked(link)?graphColors.blue:focus?'#d4dfed':link.relation==='contains'?'#99abc2':'#6e95bd',linkDirectionalArrowLength:(link:NetworkLink)=>link.relation==='contains'?0:3,linkDirectionalArrowRelPos:1,linkWidth:(link:NetworkLink)=>linked(link)?1.8:.6,onNodeClick:(node:NetworkNode)=>onSelect(node.id),onNodeHover:(node:NetworkNode|null)=>setHover(node?.id||''),onBackgroundClick:()=>onSelect(''),warmupTicks:120,cooldownTicks:paused?0:180,cooldownTime:5000,onEngineStop:onStop,onEngineTick:()=>{if(!fitted.current){fitted.current=true;fit()}},enableNodeDrag:true}
|
||||
return <div className="p-network-layout"><div className="p-network-main">
|
||||
<div className="p-network-toolbar"><span>{mode==='graph'?graphData.nodes.length:data.nodes.length} узлов · {data.edges.length} связей</span>{mode==='graph'&&<div className="p-network-controls"><button className="p-button" aria-label="Приблизить карту" onClick={()=>zoom(1.3)}>+</button><button className="p-button" aria-label="Отдалить карту" onClick={()=>zoom(1/1.3)}>−</button><button className="p-button" onClick={fit}>По размеру</button><button className="p-button" aria-pressed={paused||settled} onClick={togglePhysics}>{paused||settled?'Оживить':'Пауза'}</button></div>}</div>
|
||||
{mode==='graph'&&isolated>0&&data.edges.length>0&&<label className="p-isolated-toggle"><input type="checkbox" checked={showIsolated} onChange={e=>setShowIsolated(e.target.checked)}/>Показать также узлы без связей · {isolated}</label>}
|
||||
{data.truncated&&<p className="p-connection-notice">Показано {data.nodes.length} из {data.total_nodes} узлов и {data.edges.length} из {data.total_edges} связей. Уточните документ или запрос.</p>}
|
||||
{mode==='graph'?<div className="p-force-canvas" ref={canvasRef} onPointerLeave={()=>setHover('')} role="region" aria-label={threeD?'Объемный граф знаний':'Граф знаний: перетаскивание и масштабирование'}>{threeD?<WebGLBoundary onFallback={onFallback}><Suspense fallback={<p role="status" className="p-connection-state">Загружаем объемный граф…</p>}><ForceGraph3D {...common} ref={ref3} controlType="orbit" showNavInfo={false} nodeResolution={12} linkOpacity={.55}/></Suspense></WebGLBoundary>:<ForceGraph2D<NetworkNode,LinkMeta> {...common} ref={ref2} nodeRelSize={1.6} minZoom={.05} maxZoom={20} linkLineDash={(link)=>link.relation==='contains'?[3,3]:null} nodeCanvasObjectMode={()=>'after'} onRenderFramePre={()=>{labelRects.current=[]}} nodeCanvasObject={paintLabel}/>}</div>:<div className="p-network-list" aria-label="Список узлов">{data.nodes.map(node=><button key={node.id} className="p-network-list-row" aria-pressed={node.id===selected} onClick={()=>onSelect(node.id)}><span className="p-network-dot" style={{background:nodeColor(node)}}/><span><strong>{nodeLabel(node)}</strong><small>{node.document_title} · {degree.get(node.id)||0} связей</small></span><Icon name="arrow"/></button>)}</div>}
|
||||
<div className="p-network-legend"><span><i style={{background:graphColors.blue}}/>Статьи</span><span><i style={{background:graphColors.red}}/>Пункты Пленумов</span><span><i style={{background:graphColors.point}}/>Другие пункты</span></div>
|
||||
</div><aside className="p-network-panel" aria-label="Выбранный узел">{selectedNode?<NodePanel node={selectedNode} data={data} onSelect={onSelect}/>:<div className="p-connection-state"><Icon name="graph"/><h2>Связи конкретной нормы</h2><p>Выберите статью или пункт. Здесь появятся точные входящие и исходящие ссылки с фрагментами источников.</p><p>Стрелка — прямая ссылка. Линия без стрелки — состав статьи.</p></div>}</aside></div>
|
||||
}
|
||||
|
||||
function compactLabel(node:NetworkNode) {
|
||||
if(node.kind==='document')return nodeLabel(node)
|
||||
const number=node.label.match(/^(?:Статья|Пункт|п\.)\s*(\d+(?:\.\d+)*)/i)?.[1]
|
||||
const alias=node.aliases?.filter(value=>value.length<=12).sort((a,b)=>a.length-b.length)[0]?.toLocaleUpperCase('ru')
|
||||
const plenum=node.document_number||node.document_title?.match(/(?:N|№)\s*([\d-]+)/)?.[1]
|
||||
const documentName=alias||(node.document_kind==='plenum'?'Пленум'+(plenum?' №'+plenum:''):(node.document_title||'').slice(0,28))
|
||||
const parent=node.kind==='point'?node.id.match(/:article:(\d+(?:\.\d+)*):/)?.[1]:undefined
|
||||
return number?(node.kind==='article'?'ст.':'п.')+' '+number+(parent?' ст. '+parent:'')+' · '+documentName:nodeLabel(node)
|
||||
}
|
||||
function NodePanel({node,data,onSelect}:{node:NetworkNode;data:NetworkData;onSelect:(id:string)=>void}) {
|
||||
const family=new Set(data.nodes.filter(item=>item.id===node.id||(node.kind==='article'&&item.id.startsWith(node.id+':'))).map(item=>item.id))
|
||||
const links=data.edges.filter(link=>family.has(link.source)||family.has(link.target))
|
||||
const references=links.filter(link=>link.relation!=='contains'), structural=links.filter(link=>link.relation==='contains')
|
||||
return <div className="p-selected-node"><div className="p-panel-heading"><p className="p-eyebrow">{node.kind==='document'?'Документ':'Конкретная норма'}</p><button className="p-icon-button" aria-label="Снять выбор" onClick={()=>onSelect('')}><Icon name="close"/></button></div><h2>{nodeLabel(node)}</h2>{node.document_title!==nodeLabel(node)&&<p>{node.document_title}</p>}<a className="p-button p-button-primary" href={docHref(node.resource_id,node.reader_id)}>{node.kind==='document'?'Читать документ':'Читать точное место'}</a><a className="p-local-graph-link" href={href({view:'graph',level:'atoms',resource_id:node.resource_id,node_id:node.kind==='document'?undefined:node.id})}>{node.kind==='document'?'Статьи этого документа':'В центре — эта норма'}<Icon name="graph"/></a><h3>Прямые ссылки · {references.length}</h3>{!references.length&&<p className="p-muted">Прямые ссылки для этой нормы в сохраненном графе не найдены. Это не означает отсутствия правовой связи.</p>}{[...references,...structural].map((link,index)=>{
|
||||
const outgoing=family.has(link.source), other=data.nodes.find(item=>item.id===(outgoing?link.target:link.source))
|
||||
if(!other)return null
|
||||
const origin=data.nodes.find(item=>item.id===(outgoing?link.source:link.target))
|
||||
const attribution=origin&&origin.id!==node.id?nodeLabel(origin)+' · ':''
|
||||
const relation=link.relation==='contains'?(outgoing?'Содержит':'Входит в'):attribution+(outgoing?'Ссылается на':'Ссылка из')
|
||||
return <section className="p-atomic-relation" key={link.source+'-'+link.target+'-'+index}><p className="p-eyebrow">{relation}</p><button className="p-related-node" onClick={()=>onSelect(other.id)}><span>{nodeLabel(other)}<small>{other.document_title}</small></span><Icon name="arrow"/></button>{link.relation!=='contains'&&<details className="p-network-evidence"><summary>Основание этой связи</summary><blockquote>{link.evidence?.excerpt||'Подтверждающий фрагмент не сохранен.'}</blockquote>{link.evidence?.revision&&<small>Редакция: {shortDate(link.evidence.revision)}</small>}{link.evidence?.source_url&&<a href={safeURL(link.evidence.source_url)} target="_blank" rel="noreferrer">Источник ↗</a>}</details>}<a className="p-atomic-read" href={docHref(other.resource_id,other.reader_id)}>Читать {compactLabel(other)}</a></section>
|
||||
})}</div>
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import {useCallback, useEffect, useMemo, useRef, useState, type ReactNode} from 'react'
|
||||
import {api, docHref, href, kinds, normalized, safeURL, shortDate, useApi, type Anchor, type Fragment, type GraphEdge, type ReaderData, type RelatedData, type Route} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import {NormPractice} from './Practice'
|
||||
import {Sheet, SheetContent, SheetDescription, SheetTitle} from '@/components/ui/sheet'
|
||||
import './document.css'
|
||||
|
||||
type Props = {route: Route; onNotify: (message: string) => void; onRecent?: (id: string, fragment?: string) => void}
|
||||
type FullData = {fragments?: Fragment[]; body?: string}
|
||||
|
||||
function renderText(text: string, anchors: Anchor[] = [], query = ''): ReactNode[] {
|
||||
const pattern = query.trim() ? new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'ig') : null
|
||||
const ordered = anchors.slice().sort((a, b) => a.offset - b.offset)
|
||||
const parts: ReactNode[] = []
|
||||
let cursor = 0
|
||||
const add = (value: string, key: string) => {
|
||||
if (!value) return
|
||||
if (!pattern) { parts.push(<span key={key}>{value}</span>); return }
|
||||
parts.push(...value.split(pattern).map((part, index) => part.toLocaleLowerCase('ru') === query.toLocaleLowerCase('ru') ? <mark key={`${key}-mark-${index}`}>{part}</mark> : <span key={`${key}-${index}`}>{part}</span>))
|
||||
}
|
||||
ordered.forEach((anchor, index) => {
|
||||
const offset = Math.max(cursor, Math.min(text.length, anchor.offset))
|
||||
add(text.slice(cursor, offset), `text-${index}`)
|
||||
parts.push(<span className="p-anchor" id={anchor.id} key={`anchor-${anchor.id}`} aria-hidden="true" />)
|
||||
cursor = offset
|
||||
})
|
||||
add(text.slice(cursor), 'text-tail')
|
||||
return parts
|
||||
}
|
||||
|
||||
function bodyWithoutHeading(fragment: Fragment, query: string) {
|
||||
const raw = String(fragment.text || '')
|
||||
const first = raw.split(/\r?\n/, 1)[0].replace(/^\s*#+\s*/, '').trim()
|
||||
if (!first || normalized(first) !== normalized(fragment.label)) return renderText(raw, fragment.anchors, query)
|
||||
const match = raw.match(/\r?\n/)
|
||||
if (!match || match.index === undefined) return null
|
||||
const headingEnd = match.index + match[0].length
|
||||
const removed = headingEnd + (raw.slice(headingEnd).match(/^[\r\n]+/)?.[0].length || 0)
|
||||
const anchors = (fragment.anchors || []).filter(anchor => anchor.offset >= removed).map(anchor => ({...anchor, offset: anchor.offset - removed}))
|
||||
return renderText(raw.slice(removed), anchors, query)
|
||||
}
|
||||
|
||||
function shortTitle(title: string) {
|
||||
return title.replace(/\s*\(?Российской Федерации\)?\s*/gi, ' ').replace(/\s+РФ\s*$/i, '').trim() || title
|
||||
}
|
||||
|
||||
function Toc({items, activeId, documentId, filter, onFilter, onSelect}: {items: Fragment[]; activeId: string; documentId: string; filter: string; onFilter: (value: string) => void; onSelect: (id: string) => void}) {
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
useEffect(() => {
|
||||
const list=listRef.current, active=list?.querySelector('.is-active')
|
||||
if (list && active) list.scrollTop += active.getBoundingClientRect().top - list.getBoundingClientRect().top - 64
|
||||
}, [activeId, filter, items])
|
||||
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 chapterRows = useMemo(() => chapters.map((chapter, index) => {
|
||||
const start = items.indexOf(chapter)
|
||||
const end = index + 1 < chapters.length ? items.indexOf(chapters[index + 1]) : Infinity
|
||||
return {chapter, children: rows.filter(item => item.id !== chapter.id && !chapters.some(other => other.id === item.id) && items.indexOf(item) > start && items.indexOf(item) < end)}
|
||||
}), [chapters, items, rows])
|
||||
return <nav className="p-toc" aria-label="Оглавление"><div className="p-panel-title"><h2>Оглавление</h2></div><label className="p-field"><span>Статья или раздел</span><input type="search" value={filter} onChange={event => onFilter(event.target.value)} placeholder="Например, 395" /></label><div className="p-toc-list" ref={listRef}>
|
||||
{chapterRows.map(({chapter, children}) => <details key={chapter.id} open={Boolean(filter) || activeId === chapter.id || children.some(item => item.id === activeId)}><summary>{chapter.label}</summary><a className={activeId === chapter.id ? 'p-toc-link is-active' : 'p-toc-link'} aria-label={`Читать раздел ${chapter.label}`} href={docHref(documentId, chapter.id)} onClick={() => onSelect(chapter.id)}>Читать раздел</a>{children.map(item => <a className={activeId === item.id ? 'p-toc-link is-active' : 'p-toc-link'} href={docHref(documentId, item.id)} key={item.id} onClick={() => onSelect(item.id)}>{item.label}</a>)}</details>)}
|
||||
{!chapters.length && rows.map(item => <a className={activeId === item.id ? 'p-toc-link is-active' : 'p-toc-link'} href={docHref(documentId, item.id)} key={item.id} onClick={() => onSelect(item.id)}>{item.label}</a>)}
|
||||
</div></nav>
|
||||
}
|
||||
|
||||
const linkCount = (n: number) => n ? `${n} ${n % 10 === 1 && n % 100 !== 11 ? 'связь' : n % 10 >= 2 && n % 10 <= 4 && !(n % 100 >= 12 && n % 100 <= 14) ? 'связи' : 'связей'}` : 'Связей нет'
|
||||
function Related({data, documentId, fragmentId}: {data: RelatedData; documentId: string; fragmentId:string}) {
|
||||
const nodeId = data.node_id
|
||||
return <aside className="p-context" aria-label="Контекст и связи"><div className="p-panel-title"><h2>Контекст</h2><span>{linkCount(data.related?.length || 0)}</span></div><p className="p-context-intro">Основания связи с выбранным фрагментом. Проверяйте каждый переход по источнику.</p><div className="p-related-list">{(data.related || []).map((edge: GraphEdge, index) => {
|
||||
const source = edge.source_node
|
||||
const target = edge.target_node
|
||||
const other = nodeId && source?.id === nodeId ? target : nodeId && target?.id === nodeId ? source : source?.resource_id === documentId ? target : source
|
||||
if (!other) return null
|
||||
return <details className="p-relation" key={`${edge.source}-${edge.target}-${index}`}><summary>{other.label || 'Связанный фрагмент'}</summary><div><span className="p-chip">{edge.relation === 'references' ? 'Прямая ссылка' : edge.relation === 'thematic' ? 'Тематическая связь' : 'Связь из графа'}</span>{edge.evidence?.excerpt ? <p>«{edge.evidence.excerpt}»</p> : <p className="p-muted">Доказательный фрагмент не сохранен.</p>}{edge.evidence?.revision && <p className="p-muted">Редакция: {shortDate(edge.evidence.revision)}</p>}{edge.evidence?.source_url && <a href={safeURL(edge.evidence.source_url)} target="_blank" rel="noopener noreferrer">Источник связи ↗</a>}<a className="p-button p-button-quiet" href={docHref(other.resource_id, other.reader_id)}>{other.reader_id ? 'Открыть фрагмент' : 'Открыть документ'} <Icon name="arrow" /></a></div></details>
|
||||
})}</div><a className="p-context-graph" href={href({view:'graph',level:'atoms',node_id:nodeId||undefined,resource_id:documentId,fragment:nodeId?undefined:fragmentId})}>Граф выбранной нормы →</a></aside>
|
||||
}
|
||||
|
||||
export default function Document({route, onNotify, onRecent}: Props) {
|
||||
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 [find, setFind] = useState('')
|
||||
const [findOpen, setFindOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [fontSize, setFontSize] = useState(20)
|
||||
const [readingFocus, setReadingFocus] = useState(false)
|
||||
const [tocFilter, setTocFilter] = useState('')
|
||||
const [panel, setPanel] = useState<'toc' | 'context' | null>(null)
|
||||
const [related, setRelated] = useState<RelatedData>({related: []})
|
||||
const [relatedLoading, setRelatedLoading] = useState(false)
|
||||
const [matchIndex, setMatchIndex] = useState(-1)
|
||||
const [matchCount, setMatchCount] = useState(0)
|
||||
const findRef = useRef<HTMLInputElement>(null)
|
||||
const fullController = useRef<AbortController | null>(null)
|
||||
const fullGeneration = useRef(0)
|
||||
const documentData = reader.data?.document
|
||||
const toc = reader.data?.toc || []
|
||||
const fragments = allFragments.length ? allFragments : reader.data?.fragment ? [reader.data.fragment] : []
|
||||
const activeId = reader.data?.selected_id || fragmentId || fragments[0]?.id || ''
|
||||
const visible = query ? allFragments : fragments
|
||||
|
||||
useEffect(() => { setAllFragments([]); setQuery(''); setFind(''); setWholeError(''); setWholeLoading(false); fullGeneration.current += 1; fullController.current?.abort(); window.scrollTo(0,0) }, [documentId, fragmentId])
|
||||
useEffect(() => { if (reader.data?.document && activeId) onRecent?.(documentId, activeId) }, [reader.data?.document.id, activeId, documentId, onRecent])
|
||||
useEffect(() => { if (findOpen) findRef.current?.focus() }, [findOpen])
|
||||
useEffect(() => { document.body.classList.toggle('p-reading-focus', readingFocus); return () => document.body.classList.remove('p-reading-focus') }, [readingFocus])
|
||||
useEffect(() => { const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape' && readingFocus) setReadingFocus(false) }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey) }, [readingFocus])
|
||||
useEffect(() => () => { fullGeneration.current += 1; fullController.current?.abort() }, [])
|
||||
|
||||
const loadWhole = useCallback(async () => {
|
||||
if (!documentId || allFragments.length || wholeLoading) return allFragments
|
||||
fullController.current?.abort()
|
||||
const controller = new AbortController(); fullController.current = controller; const generation = ++fullGeneration.current
|
||||
setWholeLoading(true); setWholeError('')
|
||||
try {
|
||||
const data = await api<FullData>(`/document?${new URLSearchParams({id: documentId})}`, {signal: controller.signal})
|
||||
if (controller.signal.aborted || generation !== fullGeneration.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 !== fullGeneration.current) return []
|
||||
const message = error instanceof Error ? error.message : 'Полный текст недоступен.'; setWholeError(message); onNotify(message); return []
|
||||
} finally { if (generation === fullGeneration.current) { setWholeLoading(false); fullController.current = null } }
|
||||
}, [allFragments, documentId, onNotify, wholeLoading])
|
||||
|
||||
useEffect(() => {
|
||||
if (!find.trim()) { setQuery(''); return }
|
||||
const timer = window.setTimeout(() => { if (allFragments.length) {setQuery(find.trim());setMatchIndex(-1)} else if (!wholeLoading && !wholeError) void loadWhole() }, 260)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [find, allFragments, wholeLoading, wholeError, loadWhole])
|
||||
|
||||
useEffect(() => {
|
||||
if (!documentId) return
|
||||
const controller = new AbortController(); let timer: number | undefined; let attempts = 0; let live = true
|
||||
setRelatedLoading(true)
|
||||
const load = async () => { try { const data = await api<RelatedData>(`/related?${new URLSearchParams({id: documentId, ...(activeId ? {fragment: activeId} : {})})}`, {signal: controller.signal}); if (!live || controller.signal.aborted) return; setRelated(data); setRelatedLoading(Boolean(data.loading)); if (data.loading && attempts++ < 4) timer = window.setTimeout(load, 1500) } catch (error) { if (live && !(error instanceof Error && error.name === 'AbortError')) setRelated({related: []}) } }
|
||||
void load(); return () => { live = false; controller.abort(); if (timer !== undefined) window.clearTimeout(timer) }
|
||||
}, [documentId, activeId])
|
||||
|
||||
useEffect(() => { const frame = window.requestAnimationFrame(() => { setMatchCount(document.querySelectorAll('.p-reading mark').length); if (!query && !allFragments.length && activeId === reader.data?.fragment?.id) return; const node = activeId ? document.getElementById(activeId) : null; if (node) window.scrollTo({top: Math.max(0, node.getBoundingClientRect().top + window.scrollY - 110), behavior: 'auto'}) }); return () => window.cancelAnimationFrame(frame) }, [activeId, query, allFragments, reader.data])
|
||||
|
||||
const select = (id: string) => { window.location.hash = docHref(documentId, id).slice(1); onRecent?.(documentId, id) }
|
||||
const articleRows = toc.filter(item => item.kind === 'article')
|
||||
const articleIndex = articleRows.findIndex(item => item.id === reader.data?.fragment?.id)
|
||||
const adjacent = (direction: -1 | 1) => { const next = articleRows[articleIndex + direction]; if (next) select(next.id) }
|
||||
const navigateMatch = (direction: -1 | 1) => { const marks = Array.from(document.querySelectorAll<HTMLElement>('.p-reading mark')); if (!marks.length) return; const index = (matchIndex + direction + marks.length) % marks.length; setMatchIndex(index); marks[index].scrollIntoView({block: 'center', behavior: 'auto'}) }
|
||||
const copyLink = async () => { try { await navigator.clipboard.writeText(`${location.origin}${location.pathname}${docHref(documentId, activeId)}`); onNotify('Ссылка скопирована') } catch { onNotify('Копирование недоступно в этом браузере.') } }
|
||||
|
||||
if (reader.loading && !documentData) return <div className="p-document"><p className="p-status">Открываем документ…</p></div>
|
||||
if (reader.error || !documentData) return <div className="p-document"><p className="p-warning">{reader.error || 'Документ не найден.'}</p></div>
|
||||
const title = documentData.subject || documentData.title
|
||||
const longRevision = (documentData.revision?.length || 0) > 35
|
||||
return <div className="p-document">
|
||||
<header className="p-document-header">
|
||||
<div><span className="p-kicker">{kinds[documentData.kind]?.[0] || 'Документ'}</span><h1>{shortTitle(title)}</h1>
|
||||
<details><summary>Название, редакция и реквизиты</summary><p>{documentData.title}</p><dl><div><dt>Номер</dt><dd>{documentData.number || 'не указан'}</dd></div><div><dt>Дата акта</dt><dd>{shortDate(documentData.act_date)}</dd></div></dl><p>Редакция: {shortDate(documentData.revision)}</p><p>Получено: {shortDate(documentData.retrieved_at)} · Проверено: {shortDate(documentData.last_checked)}</p><p>{documentData.integrity ? 'Целостность сохраненного текста подтверждена' : 'Целостность текста не подтверждена'}</p></details>
|
||||
</div>
|
||||
<div className="p-header-actions"><a className="p-button" href={href({view:'history',id:documentId})}><Icon name="history"/>Редакции</a>{safeURL(documentData.source_url)!=='#'&&<a className="p-button" href={safeURL(documentData.source_url)} target="_blank" rel="noopener noreferrer">Источник<Icon name="source"/></a>}</div>
|
||||
</header>
|
||||
<div className="p-document-meta"><span>{longRevision ? 'Редакции четырех частей — в реквизитах' : `Редакция: ${shortDate(documentData.revision)}`}</span>{!!documentData.warnings?.length&&<details className="p-reader-warning"><summary>Требует сверки · {documentData.warnings.length}</summary>{documentData.warnings.map((text,i)=><p key={i}>{text}</p>)}</details>}</div>
|
||||
<div className="p-mobile-actions"><button className="p-button p-toc-trigger" onClick={()=>setPanel('toc')}><Icon name="menu"/>Оглавление</button><button className="p-button" onClick={()=>setPanel('context')}><Icon name="graph"/>Контекст</button></div>
|
||||
<div className="p-layout">
|
||||
<div className="p-side"><Toc items={toc} activeId={reader.data?.fragment?.id || activeId} documentId={documentId} filter={tocFilter} onFilter={setTocFilter} onSelect={select}/></div>
|
||||
<div className="p-reader-main">
|
||||
<div className="p-reader-tools">
|
||||
<div className="p-toolbar" role="toolbar" aria-label="Инструменты чтения">
|
||||
<button className="p-button" onClick={()=>setFindOpen(v=>!v)} aria-expanded={findOpen}><Icon name="search"/>Найти</button>
|
||||
<span className="p-tool-divider"/>
|
||||
<button className="p-icon-button" aria-label="Уменьшить шрифт" title="Уменьшить шрифт" disabled={fontSize<=16} onClick={()=>setFontSize(n=>n-1)}>A−</button>
|
||||
<button className="p-icon-button" aria-label="Увеличить шрифт" title="Увеличить шрифт" disabled={fontSize>=30} onClick={()=>setFontSize(n=>n+1)}>A+</button>
|
||||
<button className="p-icon-button" aria-label="Копировать ссылку" title="Копировать ссылку" onClick={()=>void copyLink()}><Icon name="copy"/></button>
|
||||
<button className="p-icon-button" aria-label={readingFocus?'Выйти из режима чтения':'Режим чтения'} title="Режим чтения · Escape для выхода" aria-pressed={readingFocus} onClick={()=>setReadingFocus(v=>!v)}><Icon name="expand"/></button>
|
||||
</div>
|
||||
{findOpen&&<div className="p-find-row"><label className="p-field p-find"><span className="sr-only">Найти в тексте</span><input ref={findRef} aria-label="Найти в тексте" type="search" value={find} onChange={e=>setFind(e.target.value)} placeholder="Слово или фраза"/></label><span className="p-counter" role="status">{wholeLoading?'Загрузка…':query?`${matchIndex>=0?matchIndex+1:0} / ${matchCount}`:''}</span><button className="p-icon-button" disabled={!matchCount} aria-label="Предыдущее совпадение" onClick={()=>navigateMatch(-1)}>↑</button><button className="p-icon-button" disabled={!matchCount} aria-label="Следующее совпадение" onClick={()=>navigateMatch(1)}>↓</button></div>}
|
||||
</div>
|
||||
{wholeError&&<p className="p-warning" role="alert">{wholeError}</p>}
|
||||
{!query&&<NormPractice documentId={documentId} fragmentId={reader.data?.fragment?.id || activeId}/>}
|
||||
<div className="p-reading" style={{fontSize}}>{visible.length?visible.map(fragment=><section className="p-fragment" id={fragment.id} key={fragment.id}><h2>{fragment.label}</h2><a className="p-fragment-graph" href={href({view:'graph',level:'atoms',resource_id:documentId,fragment:fragment.id})}><Icon name="graph"/>Граф этой нормы</a><div>{bodyWithoutHeading(fragment,query)}</div></section>):<p className="p-muted">Текст пока не загружен.</p>}</div>
|
||||
{articleIndex>=0&&<div className="p-adjacent"><button className="p-button" disabled={articleIndex<=0} onClick={()=>adjacent(-1)}>← Предыдущая статья</button><button className="p-button" disabled={articleIndex>=articleRows.length-1} onClick={()=>adjacent(1)}>Следующая статья →</button></div>}
|
||||
{!allFragments.length&&<button className="p-button p-whole-text" disabled={wholeLoading} onClick={()=>void loadWhole()}>{wholeLoading?'Загружаем…':'Открыть весь документ'}</button>}
|
||||
</div>
|
||||
<div className="p-side"><Related data={{...related,loading:relatedLoading}} documentId={documentId} fragmentId={activeId}/></div>
|
||||
</div>
|
||||
<Sheet open={panel!==null} onOpenChange={open=>{if(!open)setPanel(null)}}><SheetContent side={panel==='toc'?'left':'right'} className="p-sheet"><SheetTitle>{panel==='toc'?'Оглавление':'Контекст'}</SheetTitle><SheetDescription className="sr-only">Навигация и проверяемые связи документа</SheetDescription>{panel==='toc'?<Toc items={toc} activeId={reader.data?.fragment?.id || activeId} documentId={documentId} filter={tocFilter} onFilter={setTocFilter} onSelect={id=>{select(id);setPanel(null)}}/>:<Related data={{...related,loading:relatedLoading}} documentId={documentId} fragmentId={activeId}/>}</SheetContent></Sheet>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import {useEffect, useMemo, useState} from 'react'
|
||||
import {api, href, normalized, shortDate, useApi, type LegalDocument, type Route} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import './editions.css'
|
||||
|
||||
interface Version {id: string; revision?: string | null; retrieved_at?: string | null; observed_at?: string | null; effective_date?: string | null; current?: boolean}
|
||||
interface HistoryData {versions: Version[]; note: string}
|
||||
interface DiffChange {id: string; label: string; kind: 'added' | 'removed' | 'changed'; before: string; after: string; lines?: string[]}
|
||||
interface DiffData {changes: DiffChange[]; before: Version; after: Version; formatting_only?: boolean; note: string}
|
||||
|
||||
function shortTitle(value?: string | null) {
|
||||
return (value || 'Редакции документа')
|
||||
.replace(/\s*\(?Российской Федерации\)?\s*/gi, ' ')
|
||||
.replace(/\s+РФ\s*$/i, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function observedDate(version: Version) {
|
||||
return shortDate(version.observed_at || version.retrieved_at || version.revision)
|
||||
}
|
||||
|
||||
function copyLabel(version: Version, index: number) {
|
||||
return `Копия ${index + 1} · ${observedDate(version)}${version.current ? ' · текущая' : ''}`
|
||||
}
|
||||
|
||||
export function Editions({documents, route}: {documents: LegalDocument[]; route: Route}) {
|
||||
const [search, setSearch] = useState('')
|
||||
const [before, setBefore] = useState('')
|
||||
const [after, setAfter] = useState('')
|
||||
const [comparison, setComparison] = useState<string | null>(null)
|
||||
const documentId = route.id || route.doc || ''
|
||||
const document = documents.find(item => item.id === documentId)
|
||||
const history = useApi<HistoryData>(documentId ? `/history?${new URLSearchParams({id: documentId})}` : null)
|
||||
const diff = useApi<DiffData>(comparison)
|
||||
const versions = history.data?.versions || []
|
||||
const choices = useMemo(() => documents.filter(item => normalized(`${item.title} ${item.subject || ''} ${item.number || ''}`).includes(normalized(search))).slice(0, 16), [documents, search])
|
||||
|
||||
useEffect(() => {
|
||||
setComparison(null)
|
||||
if (versions.length >= 2) { setBefore(versions[0].id); setAfter(versions[versions.length - 1].id) } else { setBefore(''); setAfter('') }
|
||||
}, [documentId, history.data])
|
||||
|
||||
const compare = (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
if (!documentId || !before || !after || before === after) return
|
||||
setComparison(`/diff?${new URLSearchParams({id: documentId, before, after})}`)
|
||||
}
|
||||
|
||||
if (!documentId) return <div className="p-editions"><header className="p-editions-head"><span className="p-kicker">ИСТОРИЯ ТЕКСТА</span><h1>Редакции документов</h1><p>Выберите документ, чтобы увидеть только сохраненные копии и сравнить их.</p></header><label className="p-field"><span>Найти документ</span><input type="search" value={search} onChange={event => setSearch(event.target.value)} placeholder="Название или номер" /></label><div className="p-edition-picker">{choices.map(item => <a className="p-edition-choice" href={href({view: 'history', id: item.id})} key={item.id}><strong>{item.subject || item.title}</strong><span>{item.number || 'Номер не указан'}</span></a>)}{!choices.length && <p className="p-muted">Документы не найдены.</p>}</div></div>
|
||||
return <div className="p-editions"><header className="p-editions-head"><div><span className="p-kicker">ИСТОРИЯ ТЕКСТА</span><h1>{shortTitle(document?.subject || document?.title)}</h1><p className="p-editions-full-title">{document?.title || 'Сохраненные копии документа'}</p></div><a className="p-button p-button-quiet" href={href({doc: documentId})}><Icon name="back" /> К тексту</a></header>{history.loading && <p className="p-status">Загружаем сохраненные копии…</p>}{history.error && <p className="p-warning">{history.error}</p>}{history.data && <><p className="p-edition-note">{history.data.note}</p><div className="p-edition-list"><h2>Доступные копии</h2>{versions.map((version, index) => <div className="p-edition-row" key={version.id}><div><strong>Копия {index + 1}</strong><span>Наблюдалась: {observedDate(version)}</span><span className="p-edition-detail">Редакция: {shortDate(version.revision)}</span>{version.effective_date && <span className="p-edition-detail">Вступила в силу: {shortDate(version.effective_date)}</span>}</div>{version.current && <span className="p-chip">Текущая копия</span>}</div>)}{!versions.length && <p className="p-muted">Сохраненных копий пока нет.</p>}</div>{versions.length >= 2 ? <form className="p-compare" onSubmit={compare}><h2>Сравнить копии</h2><p>Дата наблюдения показывает, когда Эвномия получила копию. Она не подтверждает дату вступления изменений в силу.</p><div className="p-compare-fields"><label className="p-field"><span>Исходная</span><select value={before} onChange={event => setBefore(event.target.value)}>{versions.map((version, index) => <option value={version.id} key={version.id}>{copyLabel(version, index)}</option>)}</select></label><label className="p-field"><span>Сравниваемая</span><select value={after} onChange={event => setAfter(event.target.value)}>{versions.map((version, index) => <option value={version.id} key={version.id}>{copyLabel(version, index)}</option>)}</select></label><button className="p-button p-button-primary" disabled={before === after}>Сравнить</button></div></form> : <p className="p-empty">Для сравнения нужна еще одна сохраненная копия.</p>}{comparison && <DiffView state={diff} />}</>}</div>
|
||||
}
|
||||
|
||||
function DiffView({state}: {state: ReturnType<typeof useApi<DiffData>>}) {
|
||||
if (state.loading) return <p className="p-status">Сравниваем тексты…</p>
|
||||
if (state.error) return <p className="p-warning">{state.error}</p>
|
||||
const data = state.data
|
||||
if (!data) return null
|
||||
return <section className="p-diff"><h2>Результат сравнения</h2><p className="p-edition-note">{data.note}</p>{!data.changes.length ? <p className="p-empty">{data.formatting_only ? 'Изменилось только оформление текста.' : 'Тексты совпадают.'}</p> : data.changes.map(change => <article className="p-diff-change" key={change.id}><h3>{change.label}</h3><div><section><h4>Исходная копия</h4><pre>{change.before || 'Фрагмент отсутствовал'}</pre></section><section><h4>Сравниваемая копия</h4><pre>{change.after || 'Фрагмент отсутствовал'}</pre></section></div></article>)}</section>
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type {CSSProperties} from 'react'
|
||||
|
||||
const names = ['library', 'search', 'history', 'graph', 'updates', 'back', 'arrow', 'menu', 'close', 'copy', 'source', 'minus', 'plus', 'expand', 'chevron', 'document']
|
||||
const aliases: Record<string, string> = {home:'library', code:'library', plenum:'document', bylaw:'document', review:'document', 'federal-law':'document', focus:'expand', recent:'history'}
|
||||
export function Icon({name, className = ''}: {name: string; className?: string}) {
|
||||
const index = Math.max(0, names.indexOf(aliases[name] || name))
|
||||
return <span aria-hidden="true" className={`p-icon ${className}`} style={{'--ix': `${index % 4 * 100 / 3}%`, '--iy': `${Math.floor(index / 4) * 100 / 3}%`} as CSSProperties} />
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import {useEffect, useState, type FormEvent, type ReactNode} from 'react'
|
||||
import {docHref, href, safeURL, shortDate, useApi, type PracticeActData, type PracticeAreaGraph, type PracticeArticle, type PracticeCard, type PracticeFacets, type PracticeLink, type PracticeList, type PracticeNorm, type PracticeStatus, type PracticeTree, type Route} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import './practice.css'
|
||||
|
||||
const MONTHS = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь']
|
||||
const FILTERS = ['q', 'area', 'month', 'kind', 'category', 'court', 'code', 'article', 'sort'] as const
|
||||
const PRODUCTION: Record<string, string> = {'Гражданское': 'Гражданские', 'Административное': 'Административные', 'Уголовное': 'Уголовные'}
|
||||
type Link = (patch: Record<string, string | undefined>) => string
|
||||
export const plural = (n: number, one: string, few: string, many: string) => n % 10 === 1 && n % 100 !== 11 ? one : n % 10 >= 2 && n % 10 <= 4 && !(n % 100 >= 12 && n % 100 <= 14) ? few : many
|
||||
export const actsWord = (n: number) => `${n.toLocaleString('ru-RU')} ${plural(n, 'акт', 'акта', 'актов')}`
|
||||
const monthLabel = (value: string) => { const [year, month] = value.split('-'); return `${MONTHS[Number(month) - 1] || value} ${year}` }
|
||||
const moment = (value?: string | null) => { const date = new Date(value || ''); return value && !Number.isNaN(+date) ? date.toLocaleString('ru-RU', {dateStyle: 'long', timeStyle: 'short'}) : 'не указано' }
|
||||
const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
|
||||
function highlight(text: string, terms: string[]): ReactNode {
|
||||
const stems = terms.filter(term => term.length > 1).map(escape)
|
||||
if (!stems.length) return text
|
||||
const pattern = new RegExp(`(?<![\\p{L}\\d])((?:${stems.join('|')})[\\p{L}\\d]*)`, 'giu')
|
||||
return text.split(pattern).map((part, index) => index % 2 ? <mark key={index}>{part}</mark> : part)
|
||||
}
|
||||
|
||||
function Select({label, value = '', options = [], all, onChange}: {label: string; value?: string; options?: [string, string][]; all: string; onChange: (value?: string) => void}) {
|
||||
return <label><span>{label}</span><select value={value} onChange={event => onChange(event.target.value || undefined)}>
|
||||
<option value="">{all}</option>
|
||||
{options.map(([option, text]) => <option key={option} value={option}>{text}</option>)}
|
||||
{value && !options.some(([option]) => option === value) && <option value={value}>{value}</option>}
|
||||
</select></label>
|
||||
}
|
||||
|
||||
function Row({item, terms}: {item: PracticeCard; terms: string[]}) {
|
||||
const quote = item.excerpt || item.subject || ''
|
||||
return <article className="p-result p-practice-row">
|
||||
<div className="p-result-kind">{item.category || 'Судебный акт'}</div>
|
||||
<h2><a href={href({view: 'act', act: item.doc})}>{item.kind}{item.number ? ` № ${item.number}` : ''}<Icon name="arrow" /></a></h2>
|
||||
<p className="p-result-document">{[shortDate(item.act_date), item.court].filter(Boolean).join(' · ')}</p>
|
||||
{quote && <p className="p-result-excerpt">{highlight(quote, terms)}</p>}
|
||||
</article>
|
||||
}
|
||||
|
||||
function lines(title: string, width = 16): string[] {
|
||||
if (title.length <= width) return [title]
|
||||
const spaces = [...title.matchAll(/ /g)].map(match => match.index || 0)
|
||||
const cut = spaces.reduce((best, index) => Math.abs(index - title.length / 2) < Math.abs(best - title.length / 2) ? index : best, spaces[0] ?? title.length)
|
||||
return [title.slice(0, cut), title.slice(cut + 1)].filter(Boolean)
|
||||
}
|
||||
|
||||
function Divisions({tree, route, link}: {tree: PracticeTree; route: Route; link: Link}) {
|
||||
const total = tree.total
|
||||
const hub = tree.areas.find(area => (route.area || '').split(',').some(id => id === area.id || area.children.some(child => child.id === id)))
|
||||
return <nav className="p-practice-divisions" aria-label="Деление практики">
|
||||
<div className="p-division-row"><span className="p-division-label">Производство</span>
|
||||
<a href={link({category: undefined})} aria-current={!route.category ? 'true' : undefined}>Все<span>{total.toLocaleString('ru-RU')}</span></a>
|
||||
{tree.productions.map(item => <a key={item.value} href={link({category: item.value})} aria-current={route.category === item.value ? 'true' : undefined}>{PRODUCTION[item.value] || item.value}<span>{item.count.toLocaleString('ru-RU')}</span></a>)}
|
||||
</div>
|
||||
<div className="p-division-row"><span className="p-division-label">Отрасли</span>
|
||||
<a href={link({area: undefined})} aria-current={!route.area ? 'true' : undefined}>Все отрасли</a>
|
||||
{tree.areas.map(area => <a key={area.id} href={link({area: area.id})} aria-current={hub?.id === area.id ? 'true' : undefined}>{area.title}<span>{area.count.toLocaleString('ru-RU')}</span></a>)}
|
||||
</div>
|
||||
</nav>
|
||||
}
|
||||
|
||||
function AreaGraph({data, selected, link}: {data: PracticeAreaGraph; selected: string[]; link: Link}) {
|
||||
const cx = 410, cy = 235, max = Math.max(1, ...data.children.map(child => child.count))
|
||||
const maxPair = Math.max(1, ...data.intersections.map(item => item.count))
|
||||
const place = new Map(data.children.map((child, index) => {
|
||||
const angle = -Math.PI / 2 + index * 2 * Math.PI / data.children.length
|
||||
return [child.id, {x: cx + 230 * Math.cos(angle), y: cy + 150 * Math.sin(angle), cos: Math.cos(angle), sin: Math.sin(angle), r: 20 + 18 * Math.sqrt(child.count / max)}]
|
||||
}))
|
||||
return <svg className="p-area-graph" viewBox="0 0 820 470" aria-hidden="true" focusable="false">
|
||||
{data.children.map(child => { const at = place.get(child.id)!; return <line key={child.id} className="p-area-spoke" x1={cx} y1={cy} x2={at.x} y2={at.y} /> })}
|
||||
{data.intersections.map(item => {
|
||||
const a = place.get(item.a), b = place.get(item.b)
|
||||
if (!a || !b) return null
|
||||
// Дуга выгибается наружу от центра; почти противоположные узлы - вбок, чтобы не идти сквозь центр.
|
||||
const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2, far = Math.hypot(mx - cx, my - cy) > 80
|
||||
const ux = far ? (mx - cx) / Math.hypot(mx - cx, my - cy) : (a.y - b.y) / Math.hypot(b.x - a.x, b.y - a.y)
|
||||
const uy = far ? (my - cy) / Math.hypot(mx - cx, my - cy) : (b.x - a.x) / Math.hypot(b.x - a.x, b.y - a.y)
|
||||
const qx = mx + ux * (far ? 60 : 150), qy = my + uy * (far ? 60 : 150)
|
||||
const on = selected.includes(item.a) && selected.includes(item.b)
|
||||
return <a key={item.a + item.b} href={link({area: `${item.a},${item.b}`})} tabIndex={-1}>
|
||||
<path className={`p-area-cross-edge${on ? ' is-on' : ''}`} d={`M${a.x},${a.y} Q${qx},${qy} ${b.x},${b.y}`} strokeWidth={1.5 + 4 * item.count / maxPair} />
|
||||
<circle className="p-area-badge" cx={(a.x + 2 * qx + b.x) / 4} cy={(a.y + 2 * qy + b.y) / 4} r="12" />
|
||||
<text className="p-area-badge-text" x={(a.x + 2 * qx + b.x) / 4} y={(a.y + 2 * qy + b.y) / 4 + 4}>{item.count}</text>
|
||||
</a>
|
||||
})}
|
||||
<a href={link({area: data.area.id})} tabIndex={-1}><circle className={`p-area-hub${selected.includes(data.area.id) ? ' is-on' : ''}`} cx={cx} cy={cy} r="62" />
|
||||
{lines(data.area.title, 10).map((line, index, all) => <text key={line} className="p-area-hub-text" x={cx} y={cy - 8 - (all.length - 1) * 9 + index * 18}>{line}</text>)}
|
||||
<text className="p-area-hub-count" x={cx} y={cy + 24}>{data.area.count}</text></a>
|
||||
{data.children.map(child => {
|
||||
const at = place.get(child.id)!, side = Math.abs(at.cos) > 0.3, words = lines(child.title)
|
||||
const anchor = side ? (at.cos > 0 ? 'start' : 'end') : 'middle'
|
||||
const x = side ? at.x + (at.r + 12) * Math.sign(at.cos) : at.x
|
||||
const y = side ? at.y - (words.length - 1) * 8 + 5 : at.sin < 0 ? at.y - at.r - 12 - (words.length - 1) * 16 : at.y + at.r + 22
|
||||
return <a key={child.id} href={link({area: child.id})} tabIndex={-1}>
|
||||
<circle className={`p-area-node${selected.includes(child.id) ? ' is-on' : ''}`} cx={at.x} cy={at.y} r={at.r} />
|
||||
<text className="p-area-node-count" x={at.x} y={at.y + 5}>{child.count}</text>
|
||||
{words.map((word, index) => <text key={word} className="p-area-node-text" textAnchor={anchor} x={x} y={y + index * 16}>{word}</text>)}
|
||||
</a>
|
||||
})}
|
||||
</svg>
|
||||
}
|
||||
|
||||
function AreaPanel({hub, route, link}: {hub: string; route: Route; link: Link}) {
|
||||
const {data} = useApi<PracticeAreaGraph>('/practice/area?' + new URLSearchParams({id: hub}))
|
||||
if (!data?.ready) return null
|
||||
const selected = (route.area || '').split(',')
|
||||
const title = (id: string) => data.children.find(child => child.id === id)?.title || id
|
||||
const atoms = data.articles.filter(item => selected.includes(item.node) || selected.includes(data.area.id))
|
||||
return <section className="p-area" aria-labelledby="area-title">
|
||||
<div className="p-area-head"><h2 id="area-title">{data.area.title}</h2>
|
||||
<p>{actsWord(data.area.count)}{data.productions.length ? ' · ' + data.productions.map(item => `${PRODUCTION[item.value] || item.value} ${item.count}`).join(' · ') : ''}</p></div>
|
||||
<AreaGraph data={data} selected={selected} link={link} />
|
||||
<nav className="p-area-children" aria-label="Подкатегории">
|
||||
<a href={link({area: data.area.id})} aria-current={route.area === data.area.id ? 'true' : undefined}>Все {data.area.title.toLocaleLowerCase('ru')}<span>{data.area.count}</span></a>
|
||||
{data.children.map(child => <a key={child.id} href={link({area: child.id})} aria-current={route.area === child.id ? 'true' : undefined}>{child.title}<span>{child.count}</span></a>)}
|
||||
</nav>
|
||||
{!!data.intersections.length && <div className="p-area-cross"><h3>Пересечения подкатегорий</h3>
|
||||
{data.intersections.map(item => <a key={item.a + item.b} href={link({area: `${item.a},${item.b}`})} aria-current={route.area === `${item.a},${item.b}` ? 'true' : undefined}>{title(item.a)} и {title(item.b)}<span>{actsWord(item.count)}</span></a>)}</div>}
|
||||
{!!atoms.length && <div className="p-area-cross"><h3>Чаще всего цитируют</h3>
|
||||
{atoms.map(item => <a key={item.node + item.article} href={link({area: item.node, code: item.code, article: item.article})}>{item.label}<small>{title(item.node)}</small><span>{item.count}</span></a>)}</div>}
|
||||
<p className="p-area-note">Акты отнесены машиной, без модели: по предмету требования в начале акта или по нескольким статьям главы СК. Причина видна в каждом акте.</p>
|
||||
</section>
|
||||
}
|
||||
|
||||
function NotLoaded() {
|
||||
return <p className="p-practice-note">Практика еще не загружена. Задача обновления каждый час забирает акты из Lynceuz и строит связи со статьями. Ее состояние — на странице «Состояние базы».</p>
|
||||
}
|
||||
|
||||
export function PracticeView({route}: {route: Route}) {
|
||||
const params = new URLSearchParams([...FILTERS.flatMap(key => route[key] ? [[key, route[key]]] : []), ...(route.page ? [['page', route.page]] : [])])
|
||||
const list = useApi<PracticeList>('/practice?' + params)
|
||||
const facets = useApi<PracticeFacets>('/practice/facets')
|
||||
const [query, setQuery] = useState(route.q || '')
|
||||
useEffect(() => setQuery(route.q || ''), [route.q])
|
||||
const tree = useApi<PracticeTree>('/practice/tree')
|
||||
const link: Link = patch => href({view: 'practice', ...Object.fromEntries(FILTERS.map(key => [key, route[key]])), ...patch, page: patch.page})
|
||||
const go = (patch: Record<string, string | undefined>) => { location.hash = link(patch) }
|
||||
const hub = tree.data?.areas.find(area => (route.area || '').split(',').some(id => id === area.id || area.children.some(child => child.id === id)))
|
||||
const node = route.area && !route.area.includes(',') ? [hub, ...(hub?.children || [])].find(item => item?.id === route.area) : undefined
|
||||
const submit = (event: FormEvent) => { event.preventDefault(); go({q: query.trim() || undefined}) }
|
||||
const data = list.data
|
||||
const byArticle = route.code && route.article ? data?.articles.find(item => item.code === route.code && item.article === route.article) : undefined
|
||||
const facet = (name: 'months' | 'kinds' | 'categories' | 'courts') => facets.data?.[name].map(({value, count}) => [value, `${name === 'months' ? monthLabel(value) : value} · ${count}`] as [string, string])
|
||||
return <section className="p-research p-practice" aria-labelledby="practice-title">
|
||||
<div className="p-page-head"><p className="p-eyebrow">Судебная практика · СудАкт</p><h1 id="practice-title">{byArticle ? `Практика по ${byArticle.label}` : route.q ? `«${route.q}»` : node?.title || 'Судебная практика'}</h1>
|
||||
<p>Акты судов 2026 года с полным текстом. Ищите словами или статьей: «неустойка», «ст. 333 ГК».</p></div>
|
||||
{tree.data?.ready && <Divisions tree={tree.data} route={route} link={link} />}
|
||||
{hub && <AreaPanel key={hub.id} hub={hub.id} route={route} link={link} />}
|
||||
<form className="p-practice-search" role="search" aria-label="Поиск по практике" onSubmit={submit}>
|
||||
<label className="p-field"><span>Слова или статья</span><input type="search" value={query} maxLength={300} onChange={event => setQuery(event.target.value)} placeholder="неустойка, ст. 333 ГК" /></label>
|
||||
<button className="p-button p-primary" type="submit"><Icon name="search" />Найти</button>
|
||||
</form>
|
||||
<div className="p-filterbar p-practice-filters">
|
||||
<Select label="Месяц" value={route.month} options={facet('months')} all="Все месяцы" onChange={month => go({month})} />
|
||||
<Select label="Вид акта" value={route.kind} options={facet('kinds')} all="Все виды" onChange={kind => go({kind})} />
|
||||
<Select label="Суд" value={route.court} options={facet('courts')} all="Все суды" onChange={court => go({court})} />
|
||||
<Select label="Порядок" value={route.sort} options={[['old', 'Сначала ранние']]} all="Сначала новые" onChange={sort => go({sort})} />
|
||||
</div>
|
||||
{!!data?.articles.length && <div className="p-practice-articles" aria-label="Статьи в запросе">{data.articles.map(item => <span className="p-chip" key={item.code + item.article}>{item.label}{item.reader && <a href={docHref(item.reader.id, item.reader.fragment)}>текст статьи</a>}</span>)}
|
||||
{route.code && <a className="p-practice-reset" href={href({view: 'practice'})}>Сбросить статью</a>}</div>}
|
||||
<div className="p-results-tools"><span role="status">{list.loading ? 'Ищем…' : data?.ready ? actsWord(data.total) : ''}</span></div>
|
||||
{list.error ? <p role="alert" className="p-notice">{list.error}</p>
|
||||
: !data ? <p className="p-loading" role="status">Открываем практику…</p>
|
||||
: !data.ready ? <NotLoaded />
|
||||
: !data.items.length ? <p className="p-empty">Актов по запросу нет. Уберите фильтр или измените слова.</p>
|
||||
: <><div className="p-results">{data.items.map(item => <Row key={item.doc} item={item} terms={data.terms} />)}</div>
|
||||
<div className="p-pagination" aria-label="Страницы"><span>Страница {data.page} из {data.pages}</span><div className="p-pagination-actions">
|
||||
<button type="button" disabled={data.page <= 1} onClick={() => go({page: String(data.page - 1)})}>Предыдущая</button>
|
||||
<button type="button" disabled={data.page >= data.pages} onClick={() => go({page: String(data.page + 1)})}>Следующая</button>
|
||||
</div></div></>}
|
||||
</section>
|
||||
}
|
||||
|
||||
function paragraphs(text: string, links: PracticeLink[], articles: PracticeArticle[]): ReactNode[] {
|
||||
const byKey = new Map(articles.map(item => [`${item.code}:${item.article}`, item]))
|
||||
const result: ReactNode[] = []
|
||||
let offset = 0
|
||||
for (const line of text.split('\n')) {
|
||||
const start = offset, end = offset + line.length
|
||||
offset = end + 1
|
||||
if (!line.trim()) continue
|
||||
const parts: ReactNode[] = []
|
||||
let cursor = start
|
||||
for (const link of links) {
|
||||
const from = Math.max(link.start, cursor), to = Math.min(link.end, end)
|
||||
if (from >= to) continue
|
||||
if (from > cursor) parts.push(text.slice(cursor, from))
|
||||
const article = byKey.get(`${link.code}:${link.article}`)
|
||||
parts.push(article?.reader
|
||||
? <a key={from} href={docHref(article.reader.id, article.reader.fragment)} title={`Открыть ${article.label}`}>{text.slice(from, to)}</a>
|
||||
: <span key={from} className="p-act-cite" title={article?.label}>{text.slice(from, to)}</span>)
|
||||
cursor = to
|
||||
}
|
||||
parts.push(text.slice(cursor, end))
|
||||
result.push(<p key={start}>{parts}</p>)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function PracticeAct({route}: {route: Route}) {
|
||||
const {data, error, loading} = useApi<PracticeActData>(route.act ? '/practice/act?' + new URLSearchParams({id: route.act}) : null)
|
||||
if (loading) return <section className="p-practice-act"><p className="p-loading" role="status">Открываем акт…</p></section>
|
||||
if (error || !data) return <section className="p-practice-act"><p className="p-notice" role="alert">{error || 'Акт не найден.'}</p></section>
|
||||
const {act} = data
|
||||
return <article className="p-practice-act" aria-labelledby="act-title">
|
||||
<header className="p-document-header"><div>
|
||||
<a className="p-practice-back" href={href({view: 'practice'})}><Icon name="back" />Судебная практика</a>
|
||||
<span className="p-kicker">{[act.category, act.kind].filter(Boolean).join(' · ')}</span>
|
||||
<h1 id="act-title">{data.heading || act.title}</h1>
|
||||
<p className="p-practice-court">{[act.court, act.area && `(${act.area})`].filter(Boolean).join(' ')}</p>
|
||||
</div></header>
|
||||
{act.removed_at && <p className="p-notice" role="status">Источник удалил акт {shortDate(act.removed_at)}{act.removed_code ? ` (${act.removed_code})` : ''}. Показана копия, сохраненная до удаления.</p>}
|
||||
<div className="p-act-layout">
|
||||
<div className="p-act-main">{data.text === null
|
||||
? <p className="p-notice" role="alert">Сохраненный текст не прошел сверку SHA-256 и не показан. Повторите импорт практики.</p>
|
||||
: <div className="p-reading p-act-text">{paragraphs(data.text, data.links, data.articles)}</div>}</div>
|
||||
<aside className="p-act-aside" aria-label="Источник и статьи акта">
|
||||
<section className="p-act-card" aria-labelledby="act-source"><h2 id="act-source">Источник</h2><dl>
|
||||
<div><dt>Адрес</dt><dd><a href={safeURL(act.url)} target="_blank" rel="noreferrer">{act.url.replace('https://', '').replace(/\/$/, '')}</a></dd></div>
|
||||
<div><dt>Загружено</dt><dd>{moment(act.fetched_at)}</dd></div>
|
||||
<div><dt>SHA-256</dt><dd><code className="p-hash">{act.sha256}</code><span className={act.verified ? 'p-chip' : 'p-chip p-chip-bad'}>{act.verified ? 'Хеш совпал' : 'Хеш не совпал'}</span></dd></div>
|
||||
</dl></section>
|
||||
{!!data.areas.length && <section className="p-act-card" aria-labelledby="act-areas"><h2 id="act-areas">Отрасль</h2><ul className="p-act-areas">
|
||||
{data.areas.map(item => <li key={item.id}><a href={href({view: 'practice', area: item.id})}>{item.parent_title ? `${item.parent_title} → ` : ''}{item.title}</a><small>{item.reason}</small></li>)}
|
||||
</ul></section>}
|
||||
<section className="p-act-card" aria-labelledby="act-articles"><h2 id="act-articles">Статьи в акте · {data.articles.length}</h2>
|
||||
{data.articles.length ? <ul>{data.articles.map(item => <li key={item.code + item.article}>
|
||||
{item.reader ? <a href={docHref(item.reader.id, item.reader.fragment)}>{item.label}</a> : <span>{item.label}</span>}
|
||||
<a className="p-act-more" href={href({view: 'practice', code: item.code, article: item.article})}>{actsWord(item.total || 0)} по статье</a>
|
||||
</li>)}</ul> : <p>Ссылок на статьи кодексов не найдено.</p>}
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
</article>
|
||||
}
|
||||
|
||||
export function NormPractice({documentId, fragmentId}: {documentId: string; fragmentId: string}) {
|
||||
const applies = documentId.includes(':code:') && fragmentId.includes('_article_')
|
||||
const {data} = useApi<PracticeNorm>(applies ? '/practice/norm?' + new URLSearchParams({id: documentId, fragment: fragmentId}) : null)
|
||||
if (!data?.total || !data.code || !data.article) return null
|
||||
return <a className="p-norm-practice" href={href({view: 'practice', code: data.code, article: data.article})}>
|
||||
<Icon name="document" /><span className="p-norm-practice-text"><strong>Судебная практика по {data.label}</strong><small>{actsWord(data.total)} 2026 года цитируют статью</small></span><Icon name="arrow" />
|
||||
</a>
|
||||
}
|
||||
|
||||
export function PracticeTeaser({status}: {status?: PracticeStatus}) {
|
||||
const acts = status?.acts || 0
|
||||
return <section className="p-practice-teaser" aria-labelledby="practice-teaser-title">
|
||||
<div><p className="p-eyebrow">Судебная практика</p><h2 id="practice-teaser-title">Акты судов 2026 года</h2>
|
||||
<p>{status?.ready && acts ? `${actsWord(acts)} с полным текстом, источником и ссылками на статьи кодексов. Новые акты приходят сами.` : 'Акты появятся после первого импорта из Lynceuz.'}</p></div>
|
||||
<a className="p-button p-primary" href={href({view: 'practice'})}>Открыть практику<Icon name="arrow" /></a>
|
||||
</section>
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import {useState} from 'react'
|
||||
import {docHref, href, kinds, shortDate, useApi, usePoll, type Action, type Bootstrap, type LegalDocument, type Route, type SearchData, type StatusData} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import type {Recent} from './storage'
|
||||
import {ActsCard, LawCard} from './Updates'
|
||||
export {Editions} from './Editions'
|
||||
|
||||
function Empty({title,children}:{title:string;children?:React.ReactNode}) {
|
||||
return <div className="p-empty-scene"><div><h2>{title}</h2><p>{children}</p><a className="p-button" href={href({view:'home'})}>Открыть библиотеку <Icon name="arrow"/></a></div><img src="/assets/pantheon/eunomia-marble.webp" alt="" onError={event => { event.currentTarget.hidden = true }}/></div>
|
||||
}
|
||||
export function Results({route}:{route:Route}) {
|
||||
const {data,error,loading}=useApi<SearchData>(route.q?'/search?'+new URLSearchParams({q:route.q,kind:route.kind||''}):null)
|
||||
const rows=data?.results||[]
|
||||
const pages=Math.max(1,Math.ceil(rows.length/12))
|
||||
const page=Math.min(pages,Math.max(1,Number(route.page)||1))
|
||||
const terms=(route.q||'').trim().split(/\s+/).filter(x=>x.length>1).map(x=>x.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'))
|
||||
const pattern=terms.length?new RegExp('('+terms.join('|')+')','gi'):null
|
||||
return <section className="p-research"><div className="p-page-head"><p className="p-eyebrow">Поиск по текстам</p><h1>{route.q?`«${route.q}»`:'Что найти в библиотеке?'}</h1><p>{route.q?'Статьи и фрагменты из сохраненных документов.':'Введите номер статьи, название или фразу в строке поиска.'}</p></div>
|
||||
<div className="p-results-tools"><span role="status">{loading?'Ищем…':`${data?.total||0} фрагментов`}</span><label className="p-field"><span>Тип документа</span><select value={route.kind||''} onChange={e=>{location.hash=href({...route,kind:e.target.value,page:1})}}><option value="">Все документы</option>{Object.entries(kinds).map(([key,[title]])=><option key={key} value={key}>{title}</option>)}</select></label></div>
|
||||
{error?<p role="alert" className="p-notice">{error}</p>:loading?<p role="status" className="p-loading">Открываем результаты…</p>:!rows.length?<Empty title={route.q?'Совпадений нет':'Начните с поиска'}>Попробуйте точное название или сокращение: например, «статья 395 ГК».</Empty>:<><div className="p-results">{rows.slice((page-1)*12,page*12).map(row=><article className="p-result" key={row.id}><div className="p-result-kind">{kinds[row.kind]?.[0]||'Документ'}</div><h2><a href={docHref(row.resource_id,row.id)}>{row.label||row.title}<Icon name="arrow"/></a></h2><p className="p-result-document">{row.document||row.title}</p><p className="p-result-excerpt">{pattern?row.snippet.split(pattern).map((s,i)=>i%2?<mark key={i}>{s}</mark>:s):row.snippet}</p><div className="p-result-meta"><span>Редакция: {shortDate(row.revision)}</span>{!!row.warnings?.length&&<span className="p-chip p-warning">Требует сверки</span>}</div></article>)}</div>{data && data.total>rows.length&&<p className="p-muted">Показаны первые {rows.length} совпадений. Уточните запрос, чтобы сузить результаты.</p>}{pages>1&&<nav className="p-pager" aria-label="Страницы результатов"><a className="p-button" aria-disabled={page===1} href={page>1?href({...route,page:page-1}):undefined}>Назад</a><span>{page} / {pages}</span><a className="p-button" aria-disabled={page===pages} href={page<pages?href({...route,page:page+1}):undefined}>Далее</a></nav>}</>}
|
||||
</section>
|
||||
}
|
||||
export function RecentView({documents,recent,onClear}:{documents:LegalDocument[];recent:Recent[];onClear:()=>void}) {
|
||||
const rows=recent.flatMap(item=>{const doc=documents.find(d=>d.id===item.id);return doc?[{...item,doc}]:[]})
|
||||
return <section className="p-research"><div className="p-page-head p-head-action"><div><p className="p-eyebrow">Продолжить работу</p><h1>Недавнее</h1><p>Последние открытые документы. История хранится в этом браузере.</p></div>{recent.length>0&&<button className="p-button" onClick={onClear}>Очистить историю</button>}</div>{rows.length?<div className="p-recent-list">{rows.map(row=><a key={row.id} href={docHref(row.id,row.fragment)}><Icon name="document"/><span><strong>{row.doc.subject||row.doc.title}</strong><small>{row.fragment?'Вернуться к открытому фрагменту':'Открыть документ'}</small></span><time dateTime={new Date(row.at).toISOString()}>{shortDate(new Date(row.at).toISOString())}</time><Icon name="arrow"/></a>)}</div>:<Empty title="Здесь продолжится ваша работа">Откройте документ из библиотеки или поиска — он появится здесь вместе с последним прочитанным фрагментом.</Empty>}</section>
|
||||
}
|
||||
const states:Record<string,string>={queued:'В очереди',running:'Обновляется',current:'Проверен',updated:'Обновлен',deferred:'Повтор позже',blocked:'Источник недоступен',failed:'Ошибка обновления',error:'Ошибка обновления'}
|
||||
const plainPath=(text:string)=>text.replace(/\/(?:Users|home)\/[^/\s'"]+/g,'~')
|
||||
const jobReason=(job:{state:string;detail?:string|null})=>{
|
||||
const d=job.detail||''
|
||||
if(/Errno 2|No such file or directory/.test(d))return 'Обновление остановилось: пропал рабочий файл задания. Сохранённый текст на месте. Нажмите «Обновить законодательство», чтобы начать заново.'
|
||||
if(/fetch failed|timed out|timeout|URLError|ConnectionError|HTTP Error|getaddrinfo/i.test(d))return 'Источник не отдал страницу. Сохранённый текст на месте. Проверка повторится сама, а запустить её сейчас можно кнопкой «Обновить законодательство».'
|
||||
if(/source check failed|refresh not activated/.test(d))return 'Источник не прошёл проверку, текст не заменён. Сохранённая редакция на месте, проверка повторится по расписанию.'
|
||||
if(/body too short|content container absent/.test(d))return 'Источник прислал пустую страницу, текст не заменён. Проверка повторится по расписанию. Если ошибка держится, у документа мог смениться адрес.'
|
||||
if(/candidate failed|ValueError/.test(d))return 'Новую редакцию не удалось разобрать, текст не заменён. Проверка повторится по расписанию.'
|
||||
if(/не запустился|превысил/.test(d))return 'Задание не уложилось во время и отложено. Проверка повторится сама, а запустить её сейчас можно кнопкой «Обновить законодательство».'
|
||||
if(/parser_not_verified/.test(d))return 'Разбор этого источника ещё не проверен, поэтому обновление приостановлено. Сохранённый текст доступен.'
|
||||
if(job.state==='current')return 'Источник проверен, текст в библиотеке актуален.'
|
||||
if(job.state==='updated'){const m=/source date (\d{2}\.\d{2}\.\d{4})/.exec(d);return 'Текст обновлён по источнику'+(m?' от '+m[1]:'')+'.'}
|
||||
if(job.state==='queued')return 'Задание ждёт своей очереди.'
|
||||
if(job.state==='running')return 'Задание выполняется.'
|
||||
return 'Задание остановилось с ошибкой, текст не заменён. Нажмите «Обновить законодательство», чтобы повторить.'
|
||||
}
|
||||
export function Service({data,onAction}:{data:Bootstrap;onAction:(kind:Action)=>Promise<void>}) {
|
||||
const [busy,setBusy]=useState(false)
|
||||
const [error,setError]=useState('')
|
||||
const [shown,setShown]=useState('attention')
|
||||
const [page,setPage]=useState(1)
|
||||
const live=usePoll<StatusData>('/status',15000)
|
||||
const status=live.data||data.status
|
||||
const rebuild=async()=>{setBusy(true);setError('');try{await onAction('graph');live.reload()}catch(e){setError((e as Error).message)}finally{setBusy(false)}}
|
||||
const warnings=data.documents.filter(d=>!d.available||d.warnings?.length)
|
||||
const jobs=status.jobs||[]
|
||||
const attention=(s:string)=>['deferred','blocked','failed','error'].includes(s)
|
||||
const counts=(f:(s:string)=>boolean)=>jobs.filter(j=>f(j.state)).length
|
||||
const filtered=shown==='attention'?jobs.filter(j=>attention(j.state)):shown==='failed'?jobs.filter(j=>j.state==='failed'||j.state==='error'):shown==='all'?jobs:jobs.filter(j=>j.state===shown)
|
||||
const pages=Math.max(1,Math.ceil(filtered.length/20))
|
||||
const cur=Math.min(Math.max(1,page),pages)
|
||||
const rows=filtered.slice((cur-1)*20,cur*20)
|
||||
return <section className="p-research"><div className="p-page-head"><p className="p-eyebrow">Состояние базы</p><h1>Библиотека под контролем</h1><p>Сохраненные тексты доступны, пока проверяются источники.</p></div>{(error||live.error)&&<p className="p-notice" role="alert">{error||live.error}</p>}<div className="p-service-grid"><ActsCard onAction={onAction}/><LawCard onAction={onAction}/><section className="p-service-card"><h2>Связи документов</h2><p>{status.graph?.available?`Сборка от ${shortDate(status.graph.built_at)}`:'Сохраненная карта пока недоступна.'}</p><p>Пересоберите карту после изменения текстов, чтобы обновить перекрестные ссылки.</p><button className="p-button" disabled={busy} onClick={rebuild}>{busy?'Запускаем…':'Пересобрать связи'}<Icon name="graph"/></button></section></div><section className="p-jobs"><div className="p-results-tools"><h2>Очередь заданий</h2><label className="p-field"><span>Показать</span><select value={shown} onChange={e=>{setShown(e.target.value);setPage(1)}}><option value="attention">Требуют внимания · {counts(attention)}</option>{['deferred','blocked','failed','queued','running','current','updated'].map(s=><option key={s} value={s}>{states[s]} · {s==='failed'?counts(x=>x==='failed'||x==='error'):counts(x=>x===s)}</option>)}<option value="all">Все задания · {jobs.length}</option></select></label></div>{jobs.length?rows.length?rows.map((job,i)=><div className="p-job" key={job.id+i}><div><strong>{data.documents.find(d=>d.id===job.id)?.title||'Каталог источников'}</strong>{job.detail&&<details><summary>Подробности</summary><p>{jobReason(job)}</p><details><summary>Техническая подробность</summary><pre className="whitespace-pre-wrap break-all"><code>{plainPath(job.detail)}</code></pre></details></details>}</div><span className="p-chip">{states[job.state]||job.state}</span></div>):<p className="p-muted">{shown==='attention'?'Заданий, требующих внимания, нет. Выберите «Все задания», чтобы увидеть всю очередь.':'Заданий в этом состоянии нет.'}</p>:<p className="p-muted">Очередь пуста. Задания появятся после запроса обновления.</p>}{pages>1&&<nav className="p-pager" aria-label="Страницы очереди"><button type="button" className="p-button" disabled={cur<=1} onClick={()=>setPage(cur-1)}>Назад</button><span>{cur} / {pages}</span><button type="button" className="p-button" disabled={cur>=pages} onClick={()=>setPage(cur+1)}>Далее</button></nav>}</section>{warnings.length>0&&<details className="p-source-warnings"><summary>Документы, требующие сверки · {warnings.length}</summary>{warnings.map(d=><a href={docHref(d.id)} key={d.id}>{d.subject||d.title}<Icon name="arrow"/></a>)}</details>}</section>
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import {useEffect, useLayoutEffect, useRef, useState} from 'react'
|
||||
import {Command as CommandPrimitive} from 'cmdk'
|
||||
import {Command, CommandItem, CommandList} from '@/components/ui/command'
|
||||
import {api, docHref, href, type SearchData} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
|
||||
export function SearchBox({large = false, initialQuery = ''}: {large?: boolean; initialQuery?: string}) {
|
||||
const [query, setQuery] = useState(initialQuery)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [data, setData] = useState<SearchData | null>(null)
|
||||
const [pending, setPending] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const input = useRef<HTMLInputElement>(null)
|
||||
const selectedByKeyboard = useRef(false)
|
||||
const listId = useRef('')
|
||||
const showList = open && query.trim().length > 0
|
||||
useEffect(() => {setQuery(initialQuery);setOpen(false);selectedByKeyboard.current=false},[initialQuery])
|
||||
const go = (url: string) => {setOpen(false); input.current?.blur(); location.hash = url.slice(1)}
|
||||
const search = () => {if (query.trim()) go(href({view:'search',q:query.trim()}))}
|
||||
useEffect(() => {
|
||||
const key = (event: KeyboardEvent) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') {
|
||||
event.preventDefault(); input.current?.focus(); setOpen(true)
|
||||
}
|
||||
}
|
||||
const outside = (event: PointerEvent) => {if (!box.current?.contains(event.target as Node)) setOpen(false)}
|
||||
document.addEventListener('keydown', key)
|
||||
document.addEventListener('pointerdown', outside)
|
||||
return () => {document.removeEventListener('keydown',key); document.removeEventListener('pointerdown',outside)}
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
if (!query.trim()) {setData(null);setPending(false);setError('');return}
|
||||
const controller = new AbortController()
|
||||
setPending(true); setError('')
|
||||
const timer = setTimeout(() => {
|
||||
api<SearchData>('/search?'+new URLSearchParams({q:query}), {signal:controller.signal})
|
||||
.then(value => {if (!controller.signal.aborted) setData(value)})
|
||||
.catch(e => {if (!controller.signal.aborted) setError(e.message)})
|
||||
.finally(() => {if (!controller.signal.aborted) setPending(false)})
|
||||
}, 200)
|
||||
return () => {controller.abort();clearTimeout(timer)}
|
||||
}, [query])
|
||||
// cmdk hardcodes aria-expanded/aria-controls on Command.Input (spread order beats our props),
|
||||
// so the popup contract is patched on the DOM node directly: no popup, no aria-controls.
|
||||
useLayoutEffect(() => {
|
||||
const el = input.current
|
||||
if (!el) return
|
||||
if (!listId.current) listId.current = el.getAttribute('aria-controls') || ''
|
||||
el.setAttribute('aria-expanded', String(showList))
|
||||
if (showList) el.setAttribute('aria-controls', listId.current)
|
||||
else el.removeAttribute('aria-controls')
|
||||
}, [showList])
|
||||
return <div className={`p-search ${large ? 'p-search-large' : ''}`} ref={box}>
|
||||
<Command shouldFilter={false} label="Поиск по библиотеке">
|
||||
<div className="p-search-field">
|
||||
<Icon name="search" />
|
||||
<CommandPrimitive.Input
|
||||
ref={input} value={query} aria-label="Поиск по библиотеке" enterKeyHint="search"
|
||||
placeholder={large ? 'Статья, номер документа или вопрос права' : 'Поиск по библиотеке'}
|
||||
onValueChange={value => {setQuery(value);setOpen(true);selectedByKeyboard.current=false}}
|
||||
onFocus={() => setOpen(true)}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Escape') {setOpen(false);event.stopPropagation()}
|
||||
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') selectedByKeyboard.current=true
|
||||
if (event.key === 'Enter' && !selectedByKeyboard.current) {event.preventDefault();event.stopPropagation();search()}
|
||||
}}
|
||||
/>
|
||||
{query && <button className="p-search-clear" aria-label="Очистить поиск" onClick={() => {setQuery('');input.current?.focus()}}><Icon name="close" /></button>}
|
||||
{large ? <button className="p-button p-primary" onClick={search}>Найти <Icon name="arrow" /></button> : <kbd aria-label="Command или Control K">⌘ K</kbd>}
|
||||
</div>
|
||||
{showList && <CommandList className="p-suggestions">
|
||||
<CommandItem value="all-results" onSelect={search}><Icon name="search" /><span>Все результаты по запросу «{query}»</span><kbd>↵</kbd></CommandItem>
|
||||
{pending ? <p className="p-search-note" role="status">Ищем в текстах…</p> : error ? <p className="p-search-note" role="alert">{error}</p> : data?.results.length ? data.results.slice(0,5).map(row =>
|
||||
<CommandItem key={row.id} value={row.id} onSelect={() => go(docHref(row.resource_id,row.id))}>
|
||||
<Icon name="document" /><span><strong>{row.label}</strong><small>{row.document || row.title}</small></span><Icon name="arrow" />
|
||||
</CommandItem>
|
||||
) : <p className="p-search-note">Совпадений нет. Уточните название или номер статьи.</p>}
|
||||
</CommandList>}
|
||||
</Command>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import {useState, type ReactNode} from 'react'
|
||||
import {href, usePoll, type Action, type LawFreshness, type LawProgress, type Load, type PracticeProgress} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import {plural} from './Practice'
|
||||
import './updates.css'
|
||||
|
||||
// Полосы «Состояния базы». Смысл и тексты - со страницы загрузки СудАкта (eunomia/status/index.html),
|
||||
// одобренной владельцем 02.10.2026: одна полоса от 0 до 100 %, скорость, остаток, «нет свежих данных».
|
||||
const POLL_MS = 5000
|
||||
const STALE_MS = 3 * 60 * 1000
|
||||
const SHOWN = 5 // пунктов недостачи на карточке, остальное - числом
|
||||
const num = (n: number) => n.toLocaleString('ru-RU')
|
||||
const of = (n: number, one: string, many: string) => n % 10 === 1 && n % 100 !== 11 ? one : many // «из 96 101 акта»
|
||||
const minutes = (m: number) => m < 60 ? `${m} мин` : `${Math.floor(m / 60)} ч ${m % 60} мин`
|
||||
const day = (value: string) => new Date(value).toLocaleString('ru-RU', {day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit'})
|
||||
const pace = (p: Load) => `${p.per_min >= 1 ? `${num(Math.round(p.per_min))} в минуту` : `${num(Math.round(p.per_min * 60))} в час`}, осталось около ${minutes(p.eta_min ?? 0)}`
|
||||
const OUTCOMES: [string, string][] = [['current', 'без изменений'], ['updated', 'обновлены'], ['deferred', 'повтор позже'], ['blocked', 'источник недоступен'], ['failed', 'ошибка']]
|
||||
|
||||
// Отметка свежести - первой строкой под заголовком: результат виден до процентов и кнопок.
|
||||
function Mark({ok, label, missing}: {ok: boolean; label: string; missing?: LawFreshness['missing']}) {
|
||||
const rest = (missing?.length ?? 0) - SHOWN
|
||||
return <>
|
||||
<p className={ok ? 'p-load-mark' : 'p-load-mark p-load-incomplete'}>{label}</p>
|
||||
{!!missing?.length && <ul className="p-load-missing" aria-label="Что не готово">
|
||||
{missing.slice(0, SHOWN).map(item => <li key={item.id}>{item.title} — {item.reason}</li>)}
|
||||
{rest > 0 && <li>И еще {num(rest)}</li>}
|
||||
</ul>}
|
||||
</>
|
||||
}
|
||||
|
||||
function Meter({id, title, label, load, count, mark, children}: {id: string; title: string; label: string; load: Load | null; count: string; mark?: ReactNode; children: ReactNode}) {
|
||||
const share = load?.total ? Math.min(load.done / load.total, 1) : 0
|
||||
return <section className="p-service-card p-load" aria-labelledby={id}>
|
||||
<h2 id={id} className="p-load-title">{title}</h2>
|
||||
{mark}
|
||||
<p className="p-load-pct">{load ? `${(share * 100).toLocaleString('ru-RU', {minimumFractionDigits: 1, maximumFractionDigits: 1})} %` : '—'}</p>
|
||||
<progress max={100} value={share * 100} aria-label={label}/>
|
||||
<p className="p-load-count">{count}</p>
|
||||
{children}
|
||||
</section>
|
||||
}
|
||||
|
||||
function Fresh({at, next}: {at?: string; next?: string | null}) {
|
||||
if (!at) return null
|
||||
const moment = new Date(at)
|
||||
if (Date.now() - +moment >= STALE_MS) return <p className="p-load-meta p-load-stale">Нет свежих данных. Последнее обновление: {day(at)}</p>
|
||||
return <p className="p-load-meta">Обновлено в {moment.toLocaleTimeString('ru-RU', {hour: '2-digit', minute: '2-digit'})}{next ? ` · следующий обход ${day(next)}` : ''}</p>
|
||||
}
|
||||
|
||||
// Во время работы кнопка остается в фокусе и в порядке Tab (aria-disabled), но вторую работу не запускает.
|
||||
function Run({idle, label, onRun}: {idle: boolean; label: string; onRun: () => void}) {
|
||||
return <button type="button" className={idle ? 'p-button p-primary' : 'p-button p-load-wait'} aria-disabled={!idle} onClick={idle ? onRun : undefined}><Icon name="updates"/>{label}</button>
|
||||
}
|
||||
|
||||
function useRun(onAction: (kind: Action) => Promise<void>, kind: Action, reload: () => void) {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const run = async () => {
|
||||
setBusy(true); setError('')
|
||||
try { await onAction(kind); reload() } catch (e) { setError((e as Error).message) } finally { setBusy(false) }
|
||||
}
|
||||
return {busy, error, run}
|
||||
}
|
||||
|
||||
export function ActsCard({onAction}: {onAction: (kind: Action) => Promise<void>}) {
|
||||
const poll = usePoll<PracticeProgress>('/practice/progress', POLL_MS)
|
||||
const {busy, error, run} = useRun(onAction, 'refresh', poll.reload)
|
||||
const p = poll.data, walk = p?.walk
|
||||
const waiting = walk?.requested_at && !walk.running ? Date.now() - +new Date(walk.requested_at) : null
|
||||
const found = walk?.found
|
||||
const state = !p ? poll.error || 'Считаем скачанное…' : p.error ? p.error
|
||||
: waiting !== null ? (waiting < STALE_MS ? 'Обход начнется в течение минуты' : 'Обход не начался за 3 минуты: задача частей не ответила')
|
||||
: p.per_min > 0 && p.done < p.total ? pace(p)
|
||||
: walk?.running ? (p.per_min > 0 ? 'Идет обход СудАкта, новые акты скачиваются' : 'Идет обход СудАкта, новых актов пока нет')
|
||||
: p.total && p.done >= p.total ? (found ? `Последний обход: ${num(found)} ${plural(found, 'новый акт', 'новых акта', 'новых актов')}` : found === 0 ? 'Последний обход: новых актов нет' : 'Загрузка завершена')
|
||||
: 'Сейчас загрузка стоит'
|
||||
const label = walk?.stopped ? 'Обход остановлен' : busy ? 'Запускаем…' : walk?.running ? 'Обход идет…' : walk?.requested_at ? 'Обход начнется…' : 'Обновить судебные акты'
|
||||
return <Meter id="load-acts" title="Судебные акты" label="Судебные акты: скачано, процентов" load={p}
|
||||
mark={p?.freshness && <Mark ok={p.freshness.fresh} label={p.freshness.label}/>}
|
||||
count={p ? `Скачано ${num(p.done)} из ${num(p.total)} ${of(p.total, 'акта', 'актов')}` : 'Загружаем данные'}>
|
||||
{walk?.stopped
|
||||
? <p className="p-notice" role="alert">Докачка остановлена: {walk.stopped}. Обход не начнется, пока остановку не снимут: удалите parts/state.json.</p>
|
||||
: <p className="p-load-pace">{state}</p>}
|
||||
{error && <p className="p-notice" role="alert">{error}</p>}
|
||||
<Fresh at={p?.updated_at} next={walk?.running || walk?.requested_at ? null : walk?.next_due}/>
|
||||
<div className="p-load-actions">
|
||||
<Run idle={!!p && !busy && !walk?.running && !walk?.requested_at && !walk?.stopped} label={label} onRun={run}/>
|
||||
<a className="p-button" href={href({view: 'practice'})}>Открыть практику<Icon name="arrow"/></a>
|
||||
</div>
|
||||
</Meter>
|
||||
}
|
||||
|
||||
export function LawCard({onAction}: {onAction: (kind: Action) => Promise<void>}) {
|
||||
const poll = usePoll<LawProgress>('/update/progress', POLL_MS)
|
||||
const {busy, error, run} = useRun(onAction, 'update', poll.reload)
|
||||
const p = poll.data, left = p ? p.total - p.done : 0
|
||||
const counts: Record<string, number> = p ? {...p.states, failed: (p.states.failed || 0) + (p.states.error || 0)} : {}
|
||||
const outcome = OUTCOMES.filter(([key]) => counts[key]).map(([key, title]) => `${title}: ${num(counts[key])}`).join(' · ')
|
||||
const state = !p ? poll.error || 'Считаем очередь…' : !p.total ? 'Очередь пуста. Кнопка поставит в нее все документы библиотеки.'
|
||||
: !left ? 'Очередь пройдена'
|
||||
: !p.running ? 'Очередь стоит 10 минут: обработчик не берет задания. Кнопка запустит проверку снова.'
|
||||
: p.per_min > 0 ? pace(p) : 'Проверка идет'
|
||||
return <Meter id="load-law" title="Законодательство" label="Законодательство: готово, процентов" load={p}
|
||||
mark={p?.freshness && <Mark ok={p.freshness.full} label={p.freshness.label} missing={p.freshness.missing}/>}
|
||||
count={p ? `Готово ${num(p.done)} из ${num(p.total)} ${of(p.total, 'документа', 'документов')}` : 'Загружаем данные'}>
|
||||
<p className="p-load-pace">{state}</p>
|
||||
{outcome && <p className="p-load-meta">{outcome.charAt(0).toUpperCase() + outcome.slice(1)}</p>}
|
||||
{error && <p className="p-notice" role="alert">{error}</p>}
|
||||
<Fresh at={p?.updated_at}/>
|
||||
<div className="p-load-actions">
|
||||
<Run idle={!!p && !busy && !p.running} label={busy ? 'Ставим в очередь…' : p?.running ? 'Идет обновление…' : 'Обновить законодательство'} onRun={run}/>
|
||||
</div>
|
||||
</Meter>
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/* The sculpture shares the page's ground and light, without an image card. */
|
||||
.p-hero{min-height:460px;margin:0 -20px 36px;display:flex;align-items:center}
|
||||
.p-hero-copy{width:55%;max-width:640px;padding:40px 20px 64px}
|
||||
.p-hero-figure{inset:-28px -12px -12px;overflow:visible;border-radius:0;background:none;pointer-events:none}
|
||||
.p-hero-figure:after{display:none}
|
||||
.p-hero-figure img{position:absolute;inset:0;width:100%;max-width:none;height:100%;object-fit:contain;object-position:right center;opacity:1;mix-blend-mode:multiply;mask-image:linear-gradient(90deg,transparent,#000 12%,#000 94%,transparent),linear-gradient(0deg,transparent,#000 9%,#000 91%,transparent);mask-composite:intersect}
|
||||
.p-empty-scene{display:flex;min-height:460px;overflow:visible;isolation:isolate}
|
||||
.p-empty-scene>div{width:52%;max-width:560px;z-index:1}
|
||||
.p-empty-scene img{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;object-position:right center;opacity:1;z-index:-1;mix-blend-mode:multiply;mask-image:linear-gradient(90deg,transparent,#000 15%,#000 94%,transparent),linear-gradient(0deg,transparent,#000 9%,#000 91%,transparent);mask-composite:intersect}
|
||||
.p-main-graph{max-width:none}
|
||||
.p-main-graph .p-connections{max-width:none;padding:0;margin:0}
|
||||
.p-stone-image{background:none;border-radius:0;overflow:visible}
|
||||
.p-stone-image img{mask-image:linear-gradient(90deg,transparent,#000 7%,#000 93%,transparent),linear-gradient(0deg,transparent,#000 12%,#000 88%,transparent);mask-composite:intersect}
|
||||
@media(min-width:1600px){.p-hero{min-height:530px}.p-hero-copy{padding-bottom:90px}}
|
||||
@media(max-width:1100px){
|
||||
.p-hero{display:block;min-height:0;margin:0 0 24px;padding-bottom:220px}
|
||||
.p-hero-copy{width:100%;max-width:none;padding:16px 0 0}
|
||||
.p-hero h1{font-size:36px}
|
||||
.p-hero-copy>p:not(.p-eyebrow){max-width:40ch}
|
||||
.p-hero-figure{inset:auto -16px -8px;height:240px;overflow:hidden}
|
||||
.p-hero-figure img{inset:0;right:0;left:auto;width:auto;height:100%;object-fit:contain;opacity:1;mask-image:linear-gradient(90deg,transparent,#000 10%,#000 95%,transparent),linear-gradient(0deg,transparent,#000 10%,#000 91%,transparent);mask-composite:intersect}
|
||||
.p-empty-scene{display:block;min-height:0;padding-bottom:260px}
|
||||
.p-empty-scene>div{width:100%;max-width:none}
|
||||
.p-empty-scene img{inset:auto -16px 0 auto;width:auto;height:250px;max-width:none;opacity:1}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
.p-structure-toggle{display:flex;align-items:center;gap:8px;min-height:44px;color:var(--muted);font-size:12px}
|
||||
.p-structure-toggle input{accent-color:var(--accent);width:16px;height:16px;flex:none}
|
||||
.p-atomic-relation{padding:20px 0;border-bottom:1px solid var(--line)}
|
||||
.p-atomic-relation>.p-eyebrow{margin-bottom:6px}
|
||||
.p-atomic-relation .p-related-node{border:0;padding:4px 0;align-items:flex-start}
|
||||
.p-atomic-relation .p-related-node small{display:block;font-size:11px;font-weight:400;color:var(--muted);line-height:1.5;margin-top:6px}
|
||||
.p-atomic-relation .p-network-evidence{margin:12px 0}
|
||||
.p-atomic-read{display:block;margin-top:12px;font-size:12px;color:var(--accent);line-height:1.5;text-decoration:underline;text-underline-offset:3px}
|
||||
.p-fragment-graph{display:inline-flex;align-items:center;gap:8px;min-height:44px;margin:-4px 0 16px;color:var(--accent);font:500 13px/1.4 var(--font-ui);text-decoration:none;border-bottom:1px solid var(--line)}
|
||||
.p-fragment-graph:hover{border-color:var(--accent)}
|
||||
.p-fragment-graph:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
||||
.p-atomic-relation .p-network-evidence blockquote{max-height:220px;overflow:auto}
|
||||
@media(min-width:1201px){.p-network-layout{grid-template-columns:minmax(0,1fr) 320px}}
|
||||
@@ -0,0 +1,4 @@
|
||||
.p-catalog{max-width:1320px;margin:auto;color:var(--ink)}.p-hero{position:relative;min-height:420px;isolation:isolate;margin-bottom:48px}.p-hero-copy{position:relative;z-index:2;width:61%;padding:44px 32px}.p-eyebrow{margin:0 0 12px;color:var(--accent);font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase}.p-hero h1{font-size:clamp(36px,3.4vw,50px);font-weight:500;line-height:1.12;letter-spacing:-.035em;margin:0 0 20px}.p-hero-copy>p:not(.p-eyebrow){max-width:44ch;color:var(--muted);font-size:15px;line-height:1.65}.p-hero-figure{position:absolute;inset:0;z-index:0;border-radius:20px;overflow:hidden;background:var(--paper)}.p-hero-figure:after{content:'';position:absolute;inset:0;background:linear-gradient(90deg,var(--paper) 0%,#fffffff2 25%,#ffffff75 48%,transparent 63%)}.p-hero-figure img{width:100%;height:100%;object-fit:cover;object-position:center 37%;mix-blend-mode:multiply}.p-catalog-head{display:flex;justify-content:space-between;align-items:center;gap:20px;margin:0 0 24px}.p-catalog-head h2{margin:0;font-size:26px;font-weight:500}.p-catalog-head .p-eyebrow{margin-bottom:8px}.p-catalog-total{font-size:13px;color:var(--muted);white-space:nowrap}.p-tabs{display:flex;align-items:stretch;gap:16px;overflow:auto;border-bottom:1px solid var(--line);scrollbar-width:thin}.p-tabs a{display:inline-flex;align-items:center;gap:8px;min-height:52px;padding:0 4px;color:var(--muted);font-size:13px;text-decoration:none;white-space:nowrap;border-bottom:2px solid transparent}.p-tabs a[aria-current=page]{color:var(--ink);border-color:var(--accent);font-weight:500}.p-tabs span{display:inline-flex;align-items:center;justify-content:center;min-width:24px;height:22px;padding:0 6px;border-radius:5px;background:var(--tint);color:var(--muted);font-size:11px;line-height:22px}.p-tabs a[aria-current=page] span{background:var(--tint);color:var(--accent)}.p-stone-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:32px 24px;padding:24px 0 32px}.p-stone{display:flex;flex-direction:column;min-width:0;color:var(--ink);text-decoration:none;border-radius:12px;transition:transform 180ms}.p-stone:hover{transform:translateY(-2px)}.p-stone-image{aspect-ratio:3/2;overflow:hidden;border-radius:12px;background:var(--paper)}.p-stone-image img{display:block;width:100%;height:100%;object-fit:contain;mix-blend-mode:multiply}.p-stone-face{display:flex;flex-direction:column;flex:1;padding:16px 4px 0}.p-stone-face strong{font-size:17px;font-weight:500;line-height:1.35;min-height:46px}.p-stone-face span{color:var(--muted);font-size:12px;line-height:1.5;margin-top:8px}.p-stone-face small{display:block;color:var(--muted);font-size:11px;line-height:1.55;margin-top:8px}.p-topic-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;padding:24px 0 8px}.p-topic{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;min-height:66px;padding:12px;text-align:left;background:#fff;border:1px solid var(--line);border-radius:10px;color:var(--ink);font-size:12px;line-height:1.4}.p-topic strong{font-weight:500}.p-topic span{color:var(--muted);font-size:11px}.p-topic:hover,.p-topic.is-active{border-color:var(--accent);background:var(--tint)}.p-filterbar{display:flex;gap:16px;align-items:end;padding:24px 0}.p-filterbar label{display:grid;gap:6px;color:var(--muted);font-size:12px}.p-filterbar select{min-height:44px;padding:0 12px;color:var(--ink);background:#fff;border:1px solid var(--line);border-radius:10px;font-size:13px}.p-document-list{border-top:1px solid var(--line)}.p-document-row{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:22px 0;color:var(--ink);text-decoration:none;border-bottom:1px solid var(--line)}.p-document-row:hover strong{color:var(--accent)}.p-document-row strong{display:block;font-size:15px;font-weight:500;line-height:1.5}.p-document-row small{display:block;margin-top:8px;color:var(--muted);font-size:12px}.p-row-meta{color:var(--muted);font-size:11px;white-space:nowrap}.p-pagination{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:24px 0;color:var(--muted);font-size:12px}.p-pagination-actions{display:flex;gap:8px}.p-pagination button{min-height:44px;padding:8px 14px;color:var(--ink);background:#fff;border:1px solid var(--line);border-radius:10px;font-size:13px}.p-empty{padding:32px 0;color:var(--muted)}.p-contents{max-width:900px;margin:0 auto;padding:24px 0 48px}.p-contents h1{max-width:30ch;font-size:36px;line-height:1.2}.p-contents-list{margin-top:32px;border-top:1px solid var(--line)}.p-contents-list a{display:grid;grid-template-columns:48px 1fr;align-items:baseline;gap:16px;padding:22px 0;color:var(--ink);text-decoration:none;border-bottom:1px solid var(--line)}.p-contents-list a:hover{color:var(--accent)}.p-contents-list strong{font-weight:500}.p-contents-list span{font-size:13px;color:var(--muted)}
|
||||
@media(max-width:1100px){.p-hero-copy{padding:32px 24px;width:65%}.p-hero h1{font-size:40px}.p-hero{min-height:400px}.p-stone-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.p-topic-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.p-tabs{gap:14px}}
|
||||
@media(max-width:767px){.p-hero{min-height:370px;margin-bottom:36px}.p-hero-copy{width:100%;padding:28px 16px}.p-hero h1{font-size:38px}.p-hero-copy>p:not(.p-eyebrow){max-width:31ch}.p-hero-figure img{opacity:.35;object-position:64% center}.p-hero-figure:after{background:linear-gradient(90deg,#ffffffef,#ffffff5a)}.p-catalog-head h2{font-size:23px}.p-catalog-total{font-size:11px}.p-tabs{gap:14px}.p-tabs a{font-size:12px}.p-topic-grid{gap:8px}.p-filterbar{flex-wrap:wrap}.p-document-row{display:block}.p-row-meta{display:block;margin-top:12px}.p-pagination{flex-wrap:wrap}.p-contents h1{font-size:30px}}
|
||||
@media(max-width:500px){.p-stone-grid{grid-template-columns:1fr;gap:28px}.p-stone-face strong{min-height:0}.p-stone-image{aspect-ratio:1.8}.p-stone-image img{object-fit:cover}.p-catalog-head{gap:8px}.p-hero-copy{padding-inline:12px}.p-hero h1{font-size:35px}.p-topic-grid{grid-template-columns:1fr 1fr}}
|
||||
@@ -0,0 +1,55 @@
|
||||
|
||||
.p-main-graph .p-connections{max-width:none;padding:0;color:var(--ink);font-variant-numeric:lining-nums tabular-nums}
|
||||
.p-connections-head{display:flex;justify-content:space-between;align-items:center;gap:24px;margin:0 0 24px}
|
||||
.p-connections-head h1{font-size:40px;font-weight:500;line-height:1.15;margin:0}
|
||||
.p-connections-head p:last-child{color:var(--muted);font-size:13px;max-width:66ch;margin:12px 0 0}
|
||||
.p-connection-actions{display:flex;gap:4px;padding:4px;background:var(--tint);border-radius:12px;flex:none}
|
||||
.p-connection-actions .p-button{background:transparent;border-color:transparent;min-width:46px}
|
||||
.p-connection-actions .p-button[aria-pressed=true]{color:var(--ink);background:white;border-color:var(--line)}
|
||||
.p-connections .p-button-primary{color:white;background:var(--accent);border-color:var(--accent)}
|
||||
.p-connection-filters{display:grid;grid-template-columns:minmax(180px,1fr) minmax(130px,180px) minmax(130px,180px) auto;gap:12px;align-items:end;padding-bottom:20px;border-bottom:1px solid var(--line)}
|
||||
.p-connections .p-field{display:flex;flex-direction:column;align-items:stretch;gap:6px;font-size:12px;min-width:0}
|
||||
.p-connections .p-field input,.p-connections .p-field select{width:100%;min-width:0;min-height:44px;padding:10px 12px;border:1px solid var(--line);border-radius:10px;color:var(--ink);background:#fff;font:inherit}
|
||||
.p-graph-scope{display:flex;gap:16px;font-size:13px;margin-top:14px;color:var(--muted)}
|
||||
.p-graph-scope a,.p-local-graph-link{color:var(--accent)}
|
||||
.p-connection-warnings{font-size:12px;color:var(--muted);margin-top:12px}
|
||||
.p-connection-warnings p{overflow-wrap:anywhere}
|
||||
.p-connection-notice{color:var(--muted);font-size:12px;margin:12px 0;line-height:1.5}
|
||||
.p-network-layout{display:grid;grid-template-columns:minmax(0,1fr) 280px;gap:20px;margin-top:20px;align-items:start}
|
||||
.p-network-main{min-width:0}
|
||||
.p-network-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;font-size:12px;color:var(--muted);min-height:44px;flex-wrap:wrap}
|
||||
.p-network-controls{display:flex;gap:6px;flex-wrap:wrap}
|
||||
.p-network-controls .p-button{font-size:12px;min-width:44px;padding:8px 12px;min-height:44px}
|
||||
.p-force-canvas{width:100%;height:calc(100svh - 520px);min-height:400px;overflow:hidden;border:1px solid var(--line);border-radius:12px;background:var(--paper);touch-action:none}
|
||||
.p-force-canvas canvas{display:block;max-width:100%}
|
||||
.p-network-panel{min-width:0;max-height:calc(100svh - 280px);min-height:300px;overflow:auto;padding:20px 0 20px 20px;border-left:1px solid var(--line);background:transparent}
|
||||
.p-network-panel .p-connection-state{padding:24px 8px}
|
||||
.p-connection-state{padding:48px 20px;text-align:center;color:var(--muted);font-size:14px}
|
||||
.p-connection-state h2,.p-connection-state strong{color:var(--ink);font-size:20px;font-weight:500}
|
||||
.p-connection-state .p-icon{margin:0 auto 16px}
|
||||
.p-connection-state p{line-height:1.65}
|
||||
.p-panel-heading{display:flex;align-items:center;justify-content:space-between;gap:10px}
|
||||
.p-panel-heading .p-eyebrow{margin:0}
|
||||
.p-selected-node h2{font-size:22px;font-weight:500;line-height:1.35;margin:12px 0 20px;overflow-wrap:anywhere}
|
||||
.p-selected-node>p{font-size:13px;color:var(--muted)}
|
||||
.p-selected-node h3{font-size:14px;font-weight:500;margin:28px 0 10px}
|
||||
.p-local-graph-link{display:flex;gap:8px;align-items:center;margin-top:16px;font-size:13px;line-height:1.5;text-decoration:none}
|
||||
.p-related-node{display:flex;align-items:center;justify-content:space-between;width:100%;gap:8px;padding:12px 0;border:0;border-bottom:1px solid var(--line);background:none;color:var(--accent);font:inherit;font-size:13px;line-height:1.5;text-align:left;cursor:pointer}
|
||||
.p-network-evidence{font-size:12px;margin-top:16px;line-height:1.6}
|
||||
.p-network-evidence blockquote{margin:10px 0;padding-left:12px;border-left:2px solid var(--red)}
|
||||
.p-network-evidence a{display:block;color:var(--accent);margin-top:8px}
|
||||
.p-network-legend{display:flex;gap:16px;flex-wrap:wrap;margin-top:14px;font-size:11px;color:var(--muted)}
|
||||
.p-network-legend span{display:flex;align-items:center;gap:6px}
|
||||
.p-network-legend i,.p-network-dot{width:8px;height:8px;border-radius:50%;flex:none;display:inline-block}
|
||||
.p-network-list{height:calc(100svh - 520px);min-height:400px;overflow:auto;border-block:1px solid var(--line)}
|
||||
.p-network-list-row{display:flex;align-items:center;gap:12px;width:100%;padding:14px 12px;background:none;border:0;border-bottom:1px solid var(--line);color:var(--ink);text-align:left;font:inherit;font-size:13px;cursor:pointer}
|
||||
.p-network-list-row[aria-pressed=true]{background:var(--tint)}
|
||||
.p-network-list-row>span:nth-child(2){flex:1;min-width:0}
|
||||
.p-network-list-row strong{display:block;font-weight:500;overflow-wrap:anywhere}
|
||||
.p-network-list-row small{display:block;color:var(--muted);font-size:11px;margin-top:6px}
|
||||
.p-connections button:focus-visible,.p-connections a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
||||
@media(max-width:1200px){.p-network-layout{grid-template-columns:minmax(0,1fr) 240px}.p-connection-filters{grid-template-columns:1fr 1fr auto}.p-connection-filters .p-field:first-child{grid-column:1/-1}.p-connections-head{align-items:flex-start}.p-connections-head h1{font-size:34px}}
|
||||
@media(max-width:1000px){.p-network-layout{grid-template-columns:1fr}.p-network-panel{border-left:0;border-top:1px solid var(--line);padding:20px 0;max-height:440px;min-height:0}.p-network-panel:has(.p-connection-state){display:none}.p-force-canvas,.p-network-list{height:55svh;min-height:400px}.p-connections-head{flex-wrap:wrap}}
|
||||
@media(max-width:500px){.p-connection-filters{grid-template-columns:1fr 1fr}.p-connection-filters>.p-button{grid-column:1/-1}.p-connections-head{gap:16px}.p-network-controls{gap:4px}.p-network-controls .p-button{padding:8px 10px}.p-network-legend{gap:10px}.p-force-canvas,.p-network-list{min-height:370px}}
|
||||
|
||||
.p-isolated-toggle{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--muted);min-height:32px;margin-bottom:8px}.p-isolated-toggle input{accent-color:var(--accent);width:16px;height:16px}.p-connections .p-button-primary .p-icon{filter:brightness(0) invert(1)}
|
||||
@@ -0,0 +1,10 @@
|
||||
|
||||
.p-document{min-width:0;color:var(--ink)}
|
||||
.p-document-header{display:flex;align-items:start;justify-content:space-between;gap:24px;padding:12px 0 16px}.p-document-header>div:first-child{min-width:0}.p-document-header h1{font:500 30px/1.2 var(--font-sans);letter-spacing:-.025em;margin:8px 0}.p-kicker{color:var(--accent);font-size:11px;font-weight:500;letter-spacing:.08em;text-transform:uppercase}.p-document-header details{max-width:750px;color:var(--muted);font-size:13px}.p-document-header summary{font-weight:400;color:var(--accent);padding:6px 0;min-height:36px}.p-document-header details p{margin:8px 0}.p-document-header dl{display:flex;gap:24px;flex-wrap:wrap;margin:12px 0}.p-document-header dt{font-size:11px;color:var(--muted)}.p-document-header dd{margin:4px 0;color:var(--ink)}.p-header-actions{display:flex;gap:8px;flex-shrink:0}.p-document-meta{display:flex;align-items:baseline;flex-wrap:wrap;gap:8px 24px;padding:12px 0;border-block:1px solid var(--line);font-size:12px;color:var(--muted)}.p-reader-warning{color:var(--red-ink)}.p-reader-warning summary{padding:0;min-height:24px}.p-reader-warning p{max-width:90ch;margin:8px 0;color:var(--muted)}
|
||||
.p-layout{display:grid;grid-template-columns:200px minmax(0,1fr) 240px;align-items:start;gap:24px;padding:24px 0 48px;max-width:1540px;margin:auto}.p-side,.p-reader-main{min-width:0}.p-toc,.p-context{position:sticky;top:96px}.p-panel-title{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:16px}.p-panel-title h2{font-size:16px;font-weight:500;margin:0}.p-panel-title>span{font-size:11px;color:var(--muted)}.p-toc .p-field{font-size:11px}.p-toc .p-field input{font-size:12px}.p-toc-list{margin-top:16px;max-height:calc(100svh - 260px);overflow:auto;scrollbar-width:thin}.p-toc-list details{border-bottom:1px solid var(--line)}.p-toc-list summary{padding:12px 4px;min-height:44px;font-size:12px;font-weight:500;line-height:1.5}.p-toc-link{display:block;min-height:44px;padding:10px 8px 10px 12px;border-left:2px solid transparent;color:var(--muted);text-decoration:none;font-size:12px;line-height:1.5}.p-toc-link:hover,.p-toc-link.is-active{border-left-color:var(--accent);color:var(--accent);background:var(--tint)}
|
||||
.p-reader-tools{position:sticky;top:72px;z-index:10;background:var(--paper);border-bottom:1px solid var(--line);padding-bottom:12px}.p-toolbar{display:flex;align-items:center;gap:4px;min-height:44px}.p-toolbar .p-button{font-size:13px;min-width:96px}.p-toolbar .p-icon-button{font-size:14px}.p-toolbar .p-icon-button[aria-pressed=true]{background:var(--tint);border-color:var(--accent)}.p-tool-divider{height:22px;width:1px;background:var(--line);margin:0 6px}.p-find-row{display:flex;align-items:center;gap:4px;margin-top:12px}.p-find-row .p-find{flex:1;min-width:0}.p-find-row input{font-size:13px}.p-counter{font-size:11px;color:var(--muted);white-space:nowrap;margin:0 4px}.p-reading{max-width:70ch;margin:24px auto 0;font:20px/1.75 var(--font-serif);overflow-wrap:break-word}.p-fragment{scroll-margin-top:148px;margin-bottom:36px}.p-fragment h2{font:500 24px/1.35 var(--font-sans);letter-spacing:-.02em;margin:0 0 24px}.p-fragment>div{white-space:pre-wrap}.p-anchor{display:block;scroll-margin-top:148px}.p-adjacent{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-top:32px}.p-adjacent .p-button{font-size:12px;padding-inline:12px}.p-whole-text{margin-top:24px}
|
||||
.p-context-intro{font-size:12px;line-height:1.6;color:var(--muted)}.p-related-list{max-height:calc(100svh - 300px);overflow:auto;scrollbar-width:thin}.p-relation{border-top:1px solid var(--line)}.p-relation summary{font-size:12px;font-weight:500;padding:12px 4px;color:var(--ink);line-height:1.6;min-height:44px}.p-relation>div{font-size:12px;line-height:1.6;padding:0 4px 16px}.p-relation p{margin:12px 0}.p-relation a{display:inline-flex;align-items:center;gap:4px;color:var(--accent);font-size:12px;margin-top:8px}.p-relation .p-button{white-space:normal}.p-context-graph{display:inline-flex;align-items:center;min-height:44px;margin-top:12px;color:var(--accent);font-size:12px}.p-mobile-actions{display:none}.p-sheet{overflow:auto;padding:24px;gap:12px}.p-sheet>.p-toc,.p-sheet>.p-context{position:static;margin-top:20px}.p-sheet .p-toc-list,.p-sheet .p-related-list{max-height:none;overflow:visible}
|
||||
.p-reading-focus .p-document-header,.p-reading-focus .p-document-meta,.p-reading-focus .p-layout>.p-side,.p-reading-focus .p-mobile-actions{display:none!important}.p-reading-focus .p-layout{display:block;max-width:840px;padding-top:0}.p-reading-focus .p-reader-main{max-width:840px;margin:auto}
|
||||
@media(min-width:1001px) and (max-width:1439px){.p-layout{grid-template-columns:200px minmax(0,1fr)}.p-layout>.p-side:last-child{display:none}.p-mobile-actions{display:flex;margin-top:16px;gap:8px}.p-mobile-actions>.p-toc-trigger{display:none}}
|
||||
@media(max-width:1000px){.p-layout{display:block;max-width:820px}.p-layout>.p-side{display:none}.p-mobile-actions{display:flex;gap:8px;margin-top:16px}.p-document-header h1{font-size:28px}.p-document-header{flex-wrap:wrap}.p-header-actions .p-button{font-size:12px}.p-reader-tools{top:72px}}
|
||||
@media(max-width:767px){.p-document-header h1{font-size:26px}.p-header-actions{gap:8px}.p-document-header{gap:8px}.p-document-meta{font-size:11px}.p-reading{margin-top:24px}.p-fragment h2{font-size:22px}.p-reader-tools{top:68px}.p-toolbar{gap:0}.p-toolbar .p-button{min-width:84px;padding-inline:10px}.p-toolbar .p-icon-button{width:40px;flex-basis:40px}.p-tool-divider{margin-inline:4px}.p-find-row{flex-wrap:wrap}.p-find-row .p-find{min-width:130px}.p-find-row>.p-icon-button{width:36px;flex-basis:36px}.p-adjacent{display:grid;grid-template-columns:1fr}.p-sheet{max-width:calc(100vw - 32px)}}
|
||||
@@ -0,0 +1,7 @@
|
||||
.p-editions { min-height: 100%; padding: 40px clamp(20px, 5vw, 72px) 72px; color: var(--ink); background: var(--paper); font-variant-numeric: lining-nums tabular-nums; }
|
||||
.p-editions *, .p-editions *::before, .p-editions *::after { box-sizing: border-box; }.p-editions-head { display: flex; align-items: start; justify-content: space-between; gap: 24px; max-width: 920px; margin-bottom: 30px; }.p-editions-head h1 { margin: 6px 0 8px; font: 500 34px/1.16 var(--font-sans, sans-serif); letter-spacing: -.02em; }.p-editions-full-title { max-width: 70ch; margin: 0; color: var(--muted); font-size: 14px; line-height: 1.45; }.p-editions-head p { max-width: 62ch; margin: 0; color: var(--muted); line-height: 1.6; }.p-kicker { color: var(--accent); font-size: 12px; font-weight: 800; letter-spacing: .12em; text-transform: uppercase; }
|
||||
.p-button { min-height: 44px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; padding: 9px 13px; border: 1px solid var(--line); border-radius: 10px; color: var(--ink); background: #fff; cursor: pointer; font: inherit; font-size: 14px; font-weight: 700; text-decoration: none; }.p-button:hover { color: var(--accent); border-color: var(--accent); }.p-button:focus-visible,.p-field input:focus-visible,.p-field select:focus-visible { outline: 3px solid color-mix(in srgb, var(--accent) 35%, transparent); outline-offset: 2px; }.p-button-primary { color: white; border-color: var(--accent); background: var(--accent); }.p-button-quiet { background: transparent; }
|
||||
.p-field { display: grid; gap: 6px; max-width: 620px; color: var(--muted); font-size: 12px; font-weight: 750; }.p-field input,.p-field select { min-height: 44px; width: 100%; padding: 9px 11px; border: 1px solid var(--line); border-radius: 10px; color: var(--ink); background: #fff; font: inherit; font-size: 14px; }.p-edition-picker { max-width: 920px; margin-top: 20px; }.p-edition-choice { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-height: 60px; padding: 14px 0; border-bottom: 1px solid var(--line); color: var(--ink); text-decoration: none; }.p-edition-choice:hover strong { color: var(--accent); }.p-edition-choice span,.p-edition-row span { color: var(--muted); font-size: 13px; }
|
||||
.p-edition-note,.p-status,.p-empty,.p-muted { max-width: 920px; color: var(--muted); line-height: 1.6; }.p-status { padding: 14px 0; }.p-warning { max-width: 920px; padding: 12px 14px; border: 1px solid var(--red); border-radius: 10px; color: var(--red-ink); background: var(--red-tint); }.p-edition-list,.p-compare,.p-diff { max-width: 1120px; margin-top: 30px; }.p-edition-list h2,.p-compare h2,.p-diff h2 { margin: 0 0 14px; font-size: 20px; }.p-edition-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-height: 72px; padding: 14px 0; border-top: 1px solid var(--line); }.p-edition-row > div { display: flex; flex-wrap: wrap; gap: 8px 20px; align-items: baseline; }.p-edition-row strong { min-width: 110px; }.p-edition-row .p-edition-detail { font-size: 12px; }.p-chip { display: inline-flex; padding: 5px 9px; border-radius: 999px; color: var(--accent); background: var(--tint); font-size: 12px; font-weight: 800; }.p-compare { padding-top: 26px; border-top: 1px solid var(--line); }.p-compare p { color: var(--muted); font-size: 14px; }.p-compare-fields { display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr) auto; gap: 12px; align-items: end; }.p-diff-change { margin-top: 22px; }.p-diff-change h3 { margin: 0 0 8px; font-size: 16px; }.p-diff-change > div { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 14px; }.p-diff-change section { min-width: 0; padding: 14px; border: 1px solid var(--line); border-radius: 10px; background: #fff; }.p-diff-change h4 { margin: 0 0 8px; color: var(--muted); font-size: 12px; }.p-diff-change pre { max-height: 420px; margin: 0; overflow: auto; white-space: pre-wrap; color: var(--ink); font: 15px/1.55 Georgia, 'Source Serif 4', serif; }
|
||||
@media (max-width: 700px) { .p-editions { padding: 24px 16px 48px; }.p-editions-head { display: block; }.p-editions-head .p-button { margin-top: 18px; }.p-edition-choice,.p-edition-row { align-items: start; flex-direction: column; }.p-compare-fields,.p-diff-change > div { grid-template-columns: 1fr; }.p-compare-fields .p-button { width: 100%; } }
|
||||
@media (prefers-reduced-motion: reduce) { .p-button { transition: none; } }
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2019 The Golos Text Project Authors (https://github.com/googlefonts/golos-text)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,93 @@
|
||||
Copyright 2014 The Source Serif 4 Project Authors (https://github.com/adobe-fonts/source-serif)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,33 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "./catalog.css";
|
||||
@import "./document.css";
|
||||
@import "./editions.css";
|
||||
@font-face{font-family:'Golos Text';src:url('./fonts/golos.woff2') format('woff2');font-weight:400 900;font-display:swap}
|
||||
@font-face{font-family:'Source Serif 4';src:url('./fonts/source-serif.woff2') format('woff2');font-weight:200 900;font-display:swap}
|
||||
@theme inline{
|
||||
--color-background:var(--background);--color-foreground:var(--ink);--color-card:var(--card);--color-card-foreground:var(--ink);--color-popover:var(--popover);--color-popover-foreground:var(--ink);--color-primary:var(--accent);--color-primary-foreground:#fff;--color-secondary:var(--tint);--color-secondary-foreground:var(--ink);--color-muted:var(--tint);--color-muted-foreground:var(--muted);--color-accent:var(--tint);--color-accent-foreground:var(--accent);--color-destructive:var(--red);--color-border:var(--line);--color-input:var(--line);--color-ring:var(--accent);--color-sidebar:var(--sidebar);--color-sidebar-foreground:var(--ink);--color-sidebar-primary:var(--accent);--color-sidebar-primary-foreground:#fff;--color-sidebar-accent:var(--tint);--color-sidebar-accent-foreground:var(--accent);--color-sidebar-border:var(--line);--color-sidebar-ring:var(--accent);--font-sans:'Golos Text',system-ui,sans-serif;--font-serif:'Source Serif 4',Georgia,serif;--radius-sm:6px;--radius-md:8px;--radius-lg:10px;--radius-xl:20px;
|
||||
}
|
||||
:root{--flag-white:#ffffff;--flag-blue:#0067b9;--flag-red:#e32620;--paper:var(--flag-white);--ink:#17243d;--muted:#586579;--line:#dce4ef;--control-border:#8292a8;--accent:var(--flag-blue);--accent-hover:#005397;--red:var(--flag-red);--red-ink:#ae201c;--red-tint:#fff2f1;--tint:#edf5ff;--graph-canvas:#f6f9ff;--graph-point:#ffffff;--background:var(--paper);--card:#fff;--popover:#fff;--sidebar:#f5f8fd;--radius:10px;--font-serif:'Source Serif 4',Georgia,serif;--font-sans:'Golos Text',system-ui,sans-serif}
|
||||
*{box-sizing:border-box}html{min-width:320px;scroll-behavior:auto}body{margin:0;min-width:320px;background:var(--paper);color:var(--ink);font-family:var(--font-sans);font-size:16px;line-height:1.5;font-variant-numeric:lining-nums tabular-nums}button,input,select,textarea{font:inherit}button,a,input,select{-webkit-tap-highlight-color:transparent}button{cursor:pointer}button:disabled,[aria-disabled=true]{opacity:.45;cursor:default;pointer-events:none}a{text-underline-offset:4px}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,[tabindex]:focus-visible{outline:3px solid var(--accent);outline-offset:3px}h1,h2,h3,p{margin-top:0}h1{font-size:40px;line-height:1.15;font-weight:500;letter-spacing:-.035em}h2{font-size:24px;line-height:1.3;font-weight:500;letter-spacing:-.02em}h3{font-size:18px;font-weight:500}img{max-width:100%}mark{background:var(--tint);color:var(--ink);border-radius:2px}summary{cursor:pointer;min-height:44px;padding:10px 0}.p-muted{color:var(--muted)}
|
||||
.p-app{min-height:100svh}.p-icon{width:28px;height:28px;flex:0 0 28px;display:inline-block;vertical-align:middle;background-image:url('/assets/pantheon/icons.webp');background-size:400% 400%;background-position:var(--ix) var(--iy);background-repeat:no-repeat}.p-button,.p-icon-button{display:inline-flex;min-height:44px;align-items:center;justify-content:center;gap:8px;border:1px solid var(--line);background:#fff;border-radius:10px;padding:9px 16px;color:var(--ink);font-size:14px;font-weight:500;line-height:24px;text-decoration:none;white-space:nowrap;transition:background-color 150ms,border-color 150ms}.p-button:hover,.p-icon-button:hover{border-color:var(--accent);background:var(--tint)}.p-primary{background:var(--accent);border-color:var(--accent);color:white}.p-primary:hover{background:var(--accent-hover);color:white;border-color:var(--accent-hover)}.p-primary .p-icon{filter:brightness(0) invert(1)}.p-icon-button{width:44px;flex:0 0 44px;padding:7px;background:transparent;border-color:transparent}.p-chip{display:inline-flex;align-items:center;gap:4px;min-height:26px;padding:2px 8px;border-radius:6px;background:var(--tint);color:var(--accent);font-size:12px;line-height:20px}.p-warning{color:var(--red-ink);background:var(--red-tint)}.p-field{display:flex;flex-direction:column;gap:6px;color:var(--muted);font-size:13px}.p-field input,.p-field select{min-width:0;min-height:44px;border:1px solid var(--line);border-radius:10px;background:#fff;padding:10px 12px;color:var(--ink)}.p-notice{padding:16px 20px;border-left:3px solid var(--red);background:var(--red-tint);color:var(--red-ink);border-radius:0 8px 8px 0}.p-loading{padding:48px 0;color:var(--muted)}
|
||||
.p-skip{position:fixed;top:12px;left:12px;z-index:100;transform:translateY(-200%);padding:12px 20px;background:var(--accent);color:#fff;border-radius:8px}.p-skip:focus{transform:none}.p-surface{flex:1;min-width:0}.p-topbar{position:sticky;top:0;z-index:30;display:flex;align-items:center;gap:16px;min-height:72px;padding:12px 32px;border-bottom:1px solid var(--line);background:color-mix(in srgb,var(--paper) 97%,transparent)}.p-breadcrumb{display:flex;align-items:center;gap:12px;color:var(--muted);font-size:13px;white-space:nowrap}.p-breadcrumb a{color:var(--ink);text-decoration:none}.p-breadcrumb>span:last-child{max-width:220px;overflow:hidden;text-overflow:ellipsis}.p-local-note{display:flex;align-items:center;gap:8px;margin-left:auto;color:var(--muted);font-size:12px}.p-local-note>span,.p-sidebar-note>span{width:6px;height:6px;flex:0 0 6px;border-radius:50%;background:var(--accent)}.p-main{max-width:1384px;padding:32px;margin:auto;outline:none}.p-main-reading{max-width:none;padding:24px 32px}.p-main>.p-catalog{padding:0}.p-monogram{display:grid;place-items:center;width:36px;height:40px;flex:0 0 36px;border:1px solid var(--accent);border-radius:8px;color:var(--accent);font-family:var(--font-serif);font-size:29px;line-height:1;background:var(--paper)}.p-brand{display:flex;align-items:center;gap:12px;min-height:72px;color:var(--ink);text-decoration:none}.p-brand-name{display:flex;flex-direction:column}.p-brand strong{font-size:20px;font-weight:500;letter-spacing:-.04em}.p-brand small{font-size:9px;letter-spacing:.12em;color:var(--muted);margin-top:1px}.p-sidebar [data-sidebar=header]{padding:0 20px;border-bottom:1px solid var(--line)}.p-sidebar [data-sidebar=content]{padding:28px 12px}.p-sidebar [data-sidebar=footer]{padding:12px 12px 20px}.p-sidebar [data-sidebar=menu]{gap:6px}.p-sidebar [data-sidebar=menu-button]{min-height:46px;height:auto;gap:10px;padding:9px 10px;font-size:13px;border-radius:10px;color:var(--muted)}.p-sidebar [data-sidebar=menu-button]:hover,.p-sidebar [data-sidebar=menu-button][data-active=true]{background:var(--tint);color:var(--accent)}.p-sidebar [data-sidebar=menu-button][data-active=true]{font-weight:500}.p-sidebar-note{display:flex;align-items:center;gap:8px;margin:20px 10px 0;font-size:10px;color:var(--muted);white-space:nowrap}.p-sidebar[data-state=collapsed] .p-brand-name,.p-sidebar[data-state=collapsed] .p-sidebar-note{display:none}.p-sidebar[data-state=collapsed] [data-sidebar=header]{padding:0 18px}.p-sidebar[data-state=collapsed] [data-sidebar=content],.p-sidebar[data-state=collapsed] [data-sidebar=footer]{padding-left:12px;padding-right:12px}.p-sidebar[data-state=collapsed] [data-sidebar=menu-button]{width:48px!important;min-width:48px;padding:10px!important;justify-content:center}
|
||||
.p-search{position:relative;width:min(480px,100%);margin-left:auto}.p-search>[cmdk-root]{overflow:visible;background:transparent;color:var(--ink)}.p-search-field{display:flex;align-items:center;gap:8px;height:46px;padding:4px 8px;background:#fff;border:1px solid var(--line);border-radius:10px}.p-search-field:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 10%,transparent)}.p-search-field input{min-width:0;flex:1;width:100%;height:40px;border:0;background:transparent;outline:none;font-size:14px}.p-search-field input::placeholder{color:var(--muted)}.p-search-field kbd{flex:0 0 auto;border:1px solid var(--line);border-radius:5px;padding:2px 5px;font:11px/18px var(--font-sans);color:var(--muted)}.p-search-clear{display:grid;place-items:center;min-width:36px;min-height:40px;background:none;border:0}.p-search-large{width:100%;max-width:580px;margin:28px 0 0}.p-search-large .p-search-field{height:64px;padding:7px 8px 7px 16px;box-shadow:0 8px 24px #17243d06}.p-search-large input{height:48px;font-size:15px}.p-search-large .p-primary{height:48px;padding-inline:18px}.p-suggestions{position:absolute;z-index:60;top:calc(100% + 8px);left:0;right:0;max-height:390px!important;border:1px solid var(--line);border-radius:12px;background:#fff;padding:6px;box-shadow:0 16px 40px #17243d20}.p-suggestions [cmdk-item]{display:flex;align-items:center;min-height:52px;gap:8px;padding:10px;border-radius:7px;color:var(--ink);font-size:13px}.p-suggestions [cmdk-item][data-selected=true]{background:var(--tint);color:var(--ink)}.p-suggestions [cmdk-item]>span:not(.p-icon){min-width:0;flex:1}.p-suggestions strong,.p-suggestions small{display:block}.p-suggestions strong{font-weight:500}.p-suggestions small{margin-top:3px;color:var(--muted);font-size:11px;max-height:34px;overflow:hidden}.p-search-note{padding:14px 12px;margin:0;font-size:13px;color:var(--muted)}
|
||||
.p-page-head{margin:12px 0 32px}.p-page-head h1{margin-bottom:12px}.p-page-head p:last-child{color:var(--muted);max-width:65ch;margin-bottom:0}.p-head-action{display:flex;align-items:center;justify-content:space-between;gap:24px}.p-research{max-width:1100px;margin:0 auto;padding:12px 0 40px}.p-results-tools{display:flex;justify-content:space-between;align-items:center;gap:16px;padding-bottom:24px;border-bottom:1px solid var(--line);font-size:14px;color:var(--muted)}.p-results-tools .p-field{flex-direction:row;align-items:center;gap:12px}.p-result{padding:28px 0;border-bottom:1px solid var(--line)}.p-result-kind{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--accent);margin-bottom:10px}.p-result h2{font-size:22px;margin:0 0 8px}.p-result h2 a{display:flex;align-items:center;gap:12px;color:var(--ink);text-decoration:none}.p-result h2 a:hover{color:var(--accent)}.p-result h2 .p-icon{margin-left:auto}.p-result-document{font-size:13px;color:var(--muted);margin-bottom:14px}.p-result-excerpt{max-width:85ch;line-height:1.7;margin-bottom:14px}.p-result-meta{display:flex;align-items:center;gap:16px;font-size:12px;color:var(--muted)}.p-pager{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:28px 0;color:var(--muted);font-size:13px}.p-empty-scene{position:relative;display:grid;grid-template-columns:1fr 1fr;align-items:center;min-height:350px;gap:24px;overflow:hidden}.p-empty-scene>div{position:relative;z-index:1}.p-empty-scene p{color:var(--muted);max-width:45ch}.p-empty-scene img{width:100%;mix-blend-mode:multiply}.p-recent-list>a{display:flex;align-items:center;gap:16px;min-height:100px;padding:20px 0;border-bottom:1px solid var(--line);text-decoration:none;color:var(--ink)}.p-recent-list>a>span:not(.p-icon){flex:1}.p-recent-list strong,.p-recent-list small{display:block}.p-recent-list strong{font-weight:500}.p-recent-list small{font-size:13px;color:var(--muted);margin-top:6px}.p-recent-list time{font-size:12px;color:var(--muted);white-space:nowrap}.p-service-grid{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin:32px 0 48px}.p-service-card{padding:28px;background:white;border:1px solid var(--line);border-radius:16px}.p-service-card h2{font-size:22px;margin-bottom:24px}.p-service-card dl{margin:0 0 20px}.p-service-card dl>div{display:flex;justify-content:space-between;align-items:baseline;gap:16px;padding:9px 0;border-bottom:1px solid #f0f0ec}.p-service-card dt,.p-service-card p{color:var(--muted);font-size:13px}.p-service-card dd{margin:0;font-size:14px;text-align:right}.p-job{display:flex;align-items:start;justify-content:space-between;gap:24px;padding:20px 0;border-bottom:1px solid var(--line)}.p-job strong{font-size:14px;font-weight:500}.p-job details{font-size:12px;color:var(--muted)}.p-job>.p-chip{white-space:nowrap}.p-source-warnings{margin-top:40px}.p-source-warnings>a{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:60px;padding:12px 0;border-top:1px solid var(--line);font-size:14px;color:var(--ink);text-decoration:none}.p-start-state{margin:auto;padding:48px;text-align:center}.p-start-state .p-monogram{margin:0 auto 24px}.p-start-state h1{font-size:30px}.p-toast{position:fixed;z-index:80;left:50%;bottom:24px;max-width:calc(100vw - 32px);padding:12px 20px;background:var(--ink);color:white;border-radius:10px;font-size:14px;transform:translate(-50%,120px);opacity:0;transition:transform 180ms,opacity 180ms;pointer-events:none}.p-toast.is-visible{transform:translate(-50%,0);opacity:1}
|
||||
@media(min-width:768px){.p-topbar>.p-icon-button{display:none}}
|
||||
@media(max-width:1100px){.p-topbar{padding-inline:24px}.p-main{padding:24px}.p-breadcrumb>a,.p-breadcrumb>span[aria-hidden]{display:none}.p-local-note{font-size:11px}}
|
||||
@media(max-width:767px){.p-main,.p-main-reading{padding:20px 16px}.p-topbar{min-height:68px;padding:10px 12px;gap:8px}.p-topbar:has(.p-search) .p-breadcrumb{display:none}.p-topbar .p-search{width:100%}.p-local-note{display:none}.p-breadcrumb{font-size:14px}.p-head-action{align-items:flex-start;flex-direction:column}.p-page-head{margin-top:12px}.p-page-head h1{font-size:32px}.p-service-grid{grid-template-columns:1fr;gap:16px}.p-service-card{padding:20px}.p-results-tools{align-items:flex-start;flex-direction:column}.p-results-tools .p-field{width:100%;justify-content:space-between}.p-empty-scene{grid-template-columns:1fr;min-height:320px}.p-empty-scene img{position:absolute;right:-20%;width:75%;opacity:.22}.p-empty-scene>div{max-width:90%}.p-recent-list time{display:none}.p-job{flex-direction:column;gap:10px}.p-search-large input{font-size:13px}.p-search-large .p-search-field{padding-left:8px;gap:3px}.p-search-large .p-primary{padding:8px 12px}.p-search-large .p-primary .p-icon{display:none}.p-search-large .p-search-field>.p-icon{width:24px;flex-basis:24px;height:24px}.p-result h2{font-size:20px}}
|
||||
@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}}
|
||||
/* Shared primitives are owned here; screen styles only supply layout. */
|
||||
.p-field{font-weight:400;max-width:none}.p-field input,.p-field select{font-weight:400}.p-chip{margin:0;font-weight:500;line-height:20px}.p-eyebrow{font-size:11px;font-weight:500;letter-spacing:.09em}.p-connections,.p-editions{padding:12px 0 40px;max-width:1100px;margin:auto}.p-connections h1,.p-editions-head h1{font-weight:500;font-size:40px;line-height:1.15}.p-hero-figure img{position:absolute;right:0;width:auto;max-width:none;height:100%;object-fit:contain;object-position:right center}.p-search-large input::placeholder{font-size:14px}.p-search-clear{min-width:44px;min-height:44px}.p-search-large .p-search-field{gap:8px}.p-search-field input{font-weight:400}.p-reading{font-family:var(--font-serif)}
|
||||
@media(max-width:900px){.p-hero-copy{width:100%;max-width:600px}.p-hero-figure img{opacity:.33}.p-hero-figure:after{background:linear-gradient(90deg,#fffffff0,#ffffff80)}.p-connections h1,.p-editions-head h1{font-size:32px}}
|
||||
@media(max-width:500px){.p-search-large input::placeholder{font-size:12px}.p-search-large .p-search-field{gap:3px}.p-hero-figure img{right:-90px}.p-search-large .p-search-clear{min-width:36px}.p-stone-face span{margin-top:6px}}
|
||||
|
||||
.p-hero-figure img{mask-image:linear-gradient(90deg,transparent,#000 22%)}.p-kicker{font-size:11px;font-weight:500}.p-evidence-route a{font-weight:500}.p-connection-notice{font-size:13px;margin-bottom:12px}.p-evidence-summary{font-size:13px}.p-evidence-summary strong{font-weight:500}
|
||||
|
||||
.p-toolbar .p-icon-button,.p-find-row>.p-icon-button{width:44px;flex-basis:44px;min-height:44px}.p-search-large .p-search-clear{min-width:44px;min-height:44px}.p-toolbar{flex-wrap:wrap}.p-relation summary{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3;overflow:hidden}.p-relation[open] summary{display:list-item;-webkit-line-clamp:unset}
|
||||
|
||||
.p-stone-face strong{min-height:69px}.p-reading{font-variant-numeric:lining-nums tabular-nums}.p-sidebar[data-mobile=true] .p-brand{padding-right:44px}.p-sidebar[data-mobile=true] [data-sidebar=content]{padding-top:24px}
|
||||
@media(max-width:500px){.p-stone-face strong{min-height:0}}
|
||||
|
||||
.p-icon{clip-path:inset(2px)}.p-sheet .p-panel-title{display:none}.p-relation summary{display:list-item;-webkit-line-clamp:unset}
|
||||
@@ -0,0 +1,79 @@
|
||||
.p-practice .p-page-head p:last-child{max-width:62ch}
|
||||
.p-practice-search{display:flex;gap:12px;align-items:end;margin:0}
|
||||
.p-practice-search .p-field{flex:1}
|
||||
.p-practice-search .p-field input{font-size:16px}
|
||||
.p-filterbar.p-practice-filters{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px 16px;padding:20px 0 24px}
|
||||
.p-practice-filters select{width:100%;min-width:0;text-overflow:ellipsis}
|
||||
.p-practice-articles{display:flex;flex-wrap:wrap;align-items:center;gap:8px 16px;margin:0 0 20px}
|
||||
.p-practice-articles .p-chip a{margin-left:10px;color:var(--accent)}
|
||||
.p-practice-reset{color:var(--muted);font-size:13px}
|
||||
.p-practice-note{padding:20px 24px;border:1px solid var(--line);border-radius:12px;background:var(--sidebar);color:var(--muted);max-width:70ch}
|
||||
.p-practice-row h2 a{font-weight:500}
|
||||
.p-result-excerpt mark{background:#fff1a8;color:inherit;border-radius:2px;padding:0 1px}
|
||||
.p-practice-teaser{display:flex;align-items:center;justify-content:space-between;gap:24px;margin:0 0 48px;padding:28px 32px;border:1px solid var(--line);border-radius:16px;background:var(--sidebar)}
|
||||
.p-practice-teaser h2{margin:0 0 8px;font-size:24px;font-weight:500;letter-spacing:-.01em}
|
||||
.p-practice-teaser p:last-child{margin:0;color:var(--muted);max-width:60ch}
|
||||
.p-practice-teaser .p-button{flex-shrink:0}
|
||||
.p-norm-practice{display:flex;align-items:center;gap:14px;max-width:70ch;margin:20px auto 0;padding:14px 18px;border:1px solid var(--line);border-radius:12px;color:var(--ink);background:#fff;text-decoration:none}
|
||||
.p-norm-practice:hover{border-color:var(--accent)}
|
||||
.p-norm-practice-text{display:grid;gap:2px;flex:1}
|
||||
.p-norm-practice small{color:var(--muted);font-size:13px}
|
||||
.p-practice-act{max-width:1180px;margin:0 auto;padding:4px 0 48px}
|
||||
.p-practice-act .p-kicker{display:block;margin-top:4px}
|
||||
.p-practice-back{display:flex;width:max-content;align-items:center;gap:8px;min-height:44px;color:var(--accent);font-size:13px;text-decoration:none}
|
||||
.p-practice-court{margin:4px 0 0;color:var(--muted);font-size:14px}
|
||||
.p-act-layout{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:48px;align-items:start;padding-top:8px;border-top:1px solid var(--line)}
|
||||
.p-act-text{margin-top:24px}
|
||||
.p-act-text p{margin:0 0 .9em}
|
||||
.p-act-text a{color:var(--accent);text-decoration-thickness:1px}
|
||||
.p-act-cite{border-bottom:1px dotted var(--muted)}
|
||||
.p-act-aside{position:sticky;top:96px;display:grid;gap:16px;padding-top:24px}
|
||||
.p-act-card{padding:20px;border:1px solid var(--line);border-radius:14px;background:#fff}
|
||||
.p-act-card h2{margin:0 0 12px;font-size:16px;font-weight:600}
|
||||
.p-act-card dl{display:grid;gap:12px;margin:0}
|
||||
.p-act-card dt{color:var(--muted);font-size:12px}
|
||||
.p-act-card dd{margin:2px 0 0;font-size:14px;overflow-wrap:anywhere}
|
||||
.p-act-card p{margin:0;color:var(--muted);font-size:14px}
|
||||
.p-hash{display:block;margin-bottom:6px;color:var(--ink);font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;word-break:break-all}
|
||||
.p-chip-bad{background:var(--red-tint);color:var(--red-ink)}
|
||||
.p-act-card ul{display:grid;gap:4px;max-height:60vh;margin:0;padding:0;overflow:auto;list-style:none}
|
||||
.p-act-card li{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:0 12px;font-size:14px}
|
||||
.p-act-card li>a,.p-act-card li>span{display:inline-flex;align-items:center;min-height:32px}
|
||||
.p-act-more{color:var(--muted);font-size:12px}
|
||||
@media(max-width:1000px){.p-act-layout{grid-template-columns:minmax(0,1fr);gap:8px}.p-act-aside{position:static}}
|
||||
@media(max-width:767px){.p-practice-search{flex-direction:column;align-items:stretch}.p-filterbar.p-practice-filters{grid-template-columns:1fr 1fr}.p-practice-teaser{flex-direction:column;align-items:stretch;padding:20px;margin-bottom:32px}}
|
||||
.p-practice-divisions{display:grid;gap:10px;margin:0 0 24px}
|
||||
.p-division-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
|
||||
.p-division-label{min-width:116px;color:var(--muted);font-size:12px;letter-spacing:.06em;text-transform:uppercase}
|
||||
.p-division-row a,.p-area-children a,.p-area-cross a{display:inline-flex;align-items:center;gap:8px;min-height:40px;padding:6px 14px;border:1px solid var(--line);border-radius:999px;color:var(--ink);background:#fff;font-size:14px;text-decoration:none}
|
||||
.p-division-row a span,.p-area-children a span,.p-area-cross a span{color:var(--muted);font-size:12px;font-variant-numeric:tabular-nums}
|
||||
.p-division-row a:hover,.p-area-children a:hover,.p-area-cross a:hover{border-color:var(--accent)}
|
||||
.p-division-row a[aria-current],.p-area-children a[aria-current],.p-area-cross a[aria-current]{border-color:var(--accent);background:var(--tint);color:var(--accent)}
|
||||
.p-area{margin:0 0 28px;padding:24px 28px;border:1px solid var(--line);border-radius:16px;background:var(--sidebar)}
|
||||
.p-area-head{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:space-between;gap:4px 16px}
|
||||
.p-area-head h2{margin:0;font-size:22px;font-weight:500}
|
||||
.p-area-head p{margin:0;color:var(--muted);font-size:14px}
|
||||
.p-area-graph{display:block;width:100%;max-width:860px;height:auto;margin:8px auto 4px}
|
||||
.p-area-spoke{stroke:var(--line);stroke-width:1.5}
|
||||
.p-area-cross-edge{fill:none;stroke:var(--accent);stroke-opacity:.35}
|
||||
.p-area-cross-edge.is-on{stroke:var(--red);stroke-opacity:.85}
|
||||
.p-area-badge{fill:#fff;stroke:var(--accent);stroke-width:1}
|
||||
.p-area-badge-text{fill:var(--accent);font:600 12px var(--font-sans);text-anchor:middle}
|
||||
.p-area-hub{fill:var(--tint);stroke:var(--accent);stroke-width:2}
|
||||
.p-area-hub.is-on{fill:#d9e9ff}
|
||||
.p-area-hub-text{fill:var(--ink);font:600 15px var(--font-sans);text-anchor:middle}
|
||||
.p-area-hub-count{fill:var(--accent);font:600 14px var(--font-sans);text-anchor:middle}
|
||||
.p-area-node{fill:#fff;stroke:var(--accent);stroke-width:1.5}
|
||||
.p-area-node.is-on{fill:var(--accent)}
|
||||
.p-area-node-count{fill:var(--accent);font:600 13px var(--font-sans);text-anchor:middle;pointer-events:none}
|
||||
.p-area-node.is-on+.p-area-node-count{fill:#fff}
|
||||
.p-area-node-text{fill:var(--ink);font:500 14px var(--font-sans)}
|
||||
.p-area-graph a:hover .p-area-node,.p-area-graph a:hover .p-area-hub{stroke-width:3}
|
||||
.p-area-children{display:flex;flex-wrap:wrap;gap:8px;margin:12px 0 0}
|
||||
.p-area-cross{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:16px 0 0}
|
||||
.p-area-cross h3{flex-basis:100%;margin:0;color:var(--muted);font-size:12px;font-weight:500;letter-spacing:.06em;text-transform:uppercase}
|
||||
.p-area-cross a small{color:var(--muted);font-size:12px}
|
||||
.p-area-note{margin:16px 0 0;color:var(--muted);font-size:13px;max-width:80ch}
|
||||
.p-act-areas li{display:grid;gap:2px;padding:4px 0}
|
||||
.p-act-areas small{color:var(--muted);font-size:12px;line-height:1.45}
|
||||
@media(max-width:767px){.p-area{padding:18px 16px}.p-area-graph{display:none}.p-division-label{flex-basis:100%;min-width:0}}
|
||||
@@ -0,0 +1,14 @@
|
||||
export interface Recent {id: string; fragment?: string; at: number}
|
||||
const key = 'eunomia:recent:v1'
|
||||
export function recentItems(): Recent[] {
|
||||
try {
|
||||
const data: unknown = JSON.parse(localStorage.getItem(key) || '[]')
|
||||
return Array.isArray(data) ? data.filter((x): x is Recent => x && typeof x.id === 'string' && typeof x.at === 'number' && (!x.fragment || typeof x.fragment === 'string')).slice(0, 12) : []
|
||||
} catch { return [] }
|
||||
}
|
||||
export function remember(id: string, fragment?: string) {
|
||||
const items = [{id, fragment, at: Date.now()}, ...recentItems().filter(x => x.id !== id)].slice(0, 12)
|
||||
try {localStorage.setItem(key, JSON.stringify(items))} catch { /* Reading also works when browser storage is unavailable. */ }
|
||||
return items
|
||||
}
|
||||
export function clearRecent() {try {localStorage.removeItem(key)} catch { /* Memory state can still be cleared. */ }}
|
||||
@@ -0,0 +1,12 @@
|
||||
/* Screen palette inspired by Art. Lebedev Studio's Flag of Russia project. */
|
||||
.p-monogram{box-shadow:0 3px 0 var(--red)}
|
||||
.p-hero-figure img,.p-empty-scene img{width:auto;left:auto;right:0}
|
||||
.p-sidebar [data-sidebar=menu-button][data-active=true]{box-shadow:inset 3px 0 0 var(--red)}
|
||||
.p-hero-copy>.p-eyebrow,.p-catalog-head .p-eyebrow{color:var(--red-ink)}
|
||||
.p-tabs a[aria-current=page]{color:var(--accent);border-bottom-color:var(--red)}
|
||||
.p-primary:hover,.p-button-primary:hover,.p-connections .p-button-primary:hover{background:var(--accent-hover);border-color:var(--accent-hover);color:var(--flag-white)}
|
||||
.p-search-field,.p-field input,.p-field select,.p-filterbar select,.p-main-graph .p-connections .p-field input,.p-main-graph .p-connections .p-field select{border-color:var(--control-border)}
|
||||
.p-search-field:focus-within{border-color:var(--accent)}
|
||||
.p-network-legend i,.p-network-dot{border:1px solid var(--accent)}
|
||||
.p-main-graph .p-connection-actions .p-button[aria-pressed=true]{color:var(--accent);box-shadow:inset 0 -2px 0 var(--red)}
|
||||
@media(min-width:1201px){.p-main-graph .p-network-layout{grid-template-columns:minmax(0,1fr) 320px}}
|
||||
@@ -0,0 +1,20 @@
|
||||
/* Полосы «Состояния базы»: пропорции страницы загрузки СудАкта — крупный процент, полоса, строки под ней.
|
||||
Стили идут в сборке раньше pantheon.css, поэтому селекторы на класс сильнее «.p-service-card p». */
|
||||
.p-load{display:flex;flex-direction:column}
|
||||
.p-load .p-load-title{margin-bottom:8px}
|
||||
.p-load .p-load-mark{align-self:flex-start;margin:0 0 12px;padding:2px 10px;border-radius:6px;background:var(--tint);color:var(--accent);font-size:13px;font-weight:600;line-height:22px}
|
||||
.p-load .p-load-incomplete{background:#fff4e5;color:#8a4b00}
|
||||
.p-load .p-load-missing{margin:-4px 0 12px;padding-left:18px;color:var(--muted);font-size:13px;line-height:1.5}
|
||||
.p-load .p-load-pct{margin:0 0 16px;color:var(--ink);font:400 clamp(40px,5vw,56px)/1 var(--font-serif);letter-spacing:-.02em;font-variant-numeric:tabular-nums}
|
||||
.p-load progress{display:block;width:100%;height:12px;border:0;border-radius:6px;overflow:hidden;background:var(--tint);-webkit-appearance:none;appearance:none}
|
||||
.p-load progress::-webkit-progress-bar{background:var(--tint)}
|
||||
.p-load progress::-webkit-progress-value{background:var(--accent);transition:width 240ms ease-out}
|
||||
.p-load progress::-moz-progress-bar{background:var(--accent)}
|
||||
.p-load .p-load-count{margin:16px 0 4px;color:var(--ink);font-size:15px}
|
||||
.p-load .p-load-pace{margin:0 0 4px;font-size:14px}
|
||||
.p-load .p-load-meta{margin:0 0 4px}
|
||||
.p-load .p-load-stale{color:#8a4b00}
|
||||
.p-load .p-notice{margin:12px 0 0;font-size:13px;line-height:1.5}
|
||||
.p-load-actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:auto;padding-top:20px}
|
||||
.p-load-actions .p-load-wait{opacity:1;color:var(--muted);cursor:default}
|
||||
@media (prefers-reduced-motion:reduce){.p-load progress::-webkit-progress-value{transition:none}}
|
||||
@@ -0,0 +1,269 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--font-sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
--font-serif: Georgia, "Times New Roman", serif;
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: #ffffff;
|
||||
--foreground: #202824;
|
||||
--card: #ffffff;
|
||||
--card-foreground: #202824;
|
||||
--popover: #ffffff;
|
||||
--popover-foreground: #202824;
|
||||
--primary: #244b40;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #f6f7f8;
|
||||
--secondary-foreground: #47534e;
|
||||
--muted: #f6f7f8;
|
||||
--muted-foreground: #6b756f;
|
||||
--accent: #edf4f0;
|
||||
--accent-foreground: #244b40;
|
||||
--destructive: #a23d35;
|
||||
--border: #dce4df;
|
||||
--input: #dce4df;
|
||||
--ring: #244b40;
|
||||
--sidebar-width: 15rem;
|
||||
--sidebar-width-icon: 3rem;
|
||||
--sidebar: #f6f7f8;
|
||||
--sidebar-foreground: #47534e;
|
||||
--sidebar-primary: #244b40;
|
||||
--sidebar-primary-foreground: #ffffff;
|
||||
--sidebar-accent: #edf4f0;
|
||||
--sidebar-accent-foreground: #244b40;
|
||||
--sidebar-border: #dce4df;
|
||||
--sidebar-ring: #244b40;
|
||||
--ease-out: cubic-bezier(.23, 1, .32, 1);
|
||||
--ease-drawer: cubic-bezier(.32, .72, 0, 1);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html { min-width: 320px; scroll-behavior: auto; }
|
||||
body { min-width: 320px; margin: 0; color: var(--foreground); background: var(--background); font-family: var(--font-sans); font-size: 16px; line-height: 1.5; }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
a { color: var(--primary); text-underline-offset: 3px; }
|
||||
:focus-visible { outline: 3px solid var(--ring); outline-offset: 3px; }
|
||||
.sr-only, .visually-hidden { position: absolute !important; width: 1px !important; height: 1px !important; padding: 0 !important; margin: -1px !important; overflow: hidden !important; clip: rect(0, 0, 0, 0) !important; white-space: nowrap !important; border: 0 !important; }
|
||||
|
||||
.eunomia-shell { min-height: 100vh; background: var(--background); --sidebar-width: 15rem !important; }
|
||||
.eunomia-main { min-width: 0; background: var(--background); }
|
||||
.skip-link { position: fixed; z-index: 100; top: 12px; left: 12px; padding: 12px 20px; color: white; background: var(--primary); border-radius: 8px; transform: translateY(-180%); }
|
||||
.skip-link:focus { transform: none; }
|
||||
.topbar { position: sticky; top: 0; z-index: 20; display: flex; min-height: 76px; align-items: center; gap: 1rem; padding: .75rem clamp(1rem, 4vw, 4rem); background: color-mix(in srgb, var(--background) 97%, transparent); border-bottom: 1px solid var(--border); }
|
||||
.topbar .menu-toggle { display: none; }
|
||||
.breadcrumb { display: flex; min-width: 0; align-items: center; gap: .5rem; color: var(--muted-foreground); font-size: .8125rem; white-space: nowrap; }
|
||||
.breadcrumb > :last-child { overflow: hidden; text-overflow: ellipsis; }
|
||||
.breadcrumb-link { color: var(--secondary-foreground); text-decoration: none; }
|
||||
.global-search { width: min(30rem, 100%); margin-left: auto; }
|
||||
.search-field { display: flex; height: 2.75rem; align-items: center; gap: .5rem; padding: 0 .5rem 0 .75rem; background: var(--secondary); border: 1px solid var(--border); border-radius: var(--radius-lg); }
|
||||
.search-field:focus-within { border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ring) 18%, transparent); }
|
||||
.search-field input { min-width: 0; flex: 1; height: 2.5rem; color: var(--foreground); background: transparent; border: 0; outline: 0; }
|
||||
.search-field button { min-height: 2rem; padding: .25rem .75rem; color: var(--primary-foreground); background: var(--primary); border: 0; border-radius: var(--radius-sm); cursor: pointer; font-size: .8125rem; font-weight: 700; }
|
||||
.refresh-button, .menu-toggle { display: grid; width: 2.75rem; height: 2.75rem; flex: 0 0 2.75rem; place-items: center; color: var(--primary); background: var(--background); border: 1px solid var(--border); border-radius: var(--radius-md); cursor: pointer; }
|
||||
|
||||
.content { width: 100%; margin: 0 auto; padding: 3.5rem clamp(1.5rem, 3vw, 3rem) 5.5rem; }
|
||||
.page { width: 100%; max-width: 1280px; margin: 0 auto; }
|
||||
.wide-page { width: 100%; max-width: 1440px; margin: 0 auto; }
|
||||
.page-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 1.5rem; margin-bottom: 2.125rem; }
|
||||
.page-heading h1, .page-title { margin: 0; color: var(--foreground); font: 400 clamp(2rem, 4vw, 3.125rem)/1.08 var(--font-serif); letter-spacing: -.035em; }
|
||||
.page-heading p { max-width: 62ch; margin: .625rem 0 0; color: var(--muted-foreground); }
|
||||
.heading-actions, .inline-actions { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; }
|
||||
.button { display: inline-flex; min-height: 2.75rem; align-items: center; justify-content: center; gap: .4375rem; padding: .5625rem .875rem; color: var(--primary); background: var(--background); border: 1px solid var(--border); border-radius: var(--radius-md); cursor: pointer; font-size: .875rem; font-weight: 700; text-decoration: none; transition: color 180ms var(--ease-out), background-color 180ms var(--ease-out), border-color 180ms var(--ease-out), transform 120ms var(--ease-out); }
|
||||
.button:hover { background: var(--accent); border-color: #b6cdc3; }
|
||||
.button:active { transform: scale(.98); }
|
||||
.button.primary { color: var(--primary-foreground); background: var(--primary); border-color: var(--primary); }
|
||||
.button.primary:hover { background: #17382f; border-color: #17382f; }
|
||||
|
||||
.home-intro { display: grid; grid-template-columns: minmax(0, 1fr) 18.75rem; gap: 3rem; min-height: 18.75rem; max-height: 20rem; align-items: center; margin-bottom: 3rem; }
|
||||
.home-intro-copy { min-width: 0; }
|
||||
.home-label { display: block; margin-bottom: 1.25rem; color: var(--primary); font-size: .75rem; font-weight: 800; letter-spacing: .13em; text-transform: uppercase; }
|
||||
.home-intro h1 { margin: 0; font: 400 clamp(3rem, 6vw, 3.75rem)/.98 var(--font-serif); letter-spacing: -.045em; }
|
||||
.home-intro-copy > p { margin: 1.125rem 0 0; color: var(--secondary-foreground); font-size: 1.125rem; }
|
||||
.home-search { display: flex; max-width: 42.5rem; margin-top: 1.875rem; }
|
||||
.home-search input { min-width: 0; height: 3.5rem; flex: 1; padding: 0 1.0625rem; color: var(--foreground); background: var(--background); border: 1px solid var(--border); border-right: 0; border-radius: 10px 0 0 10px; outline: 0; font-size: 1rem; }
|
||||
.home-search input:focus { border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ring) 18%, transparent); }
|
||||
.home-search .button { height: 3.5rem; padding-inline: 1.375rem; border-radius: 0 10px 10px 0; }
|
||||
.home-examples { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem .875rem; margin-top: .75rem; color: var(--muted-foreground); font-size: .875rem; }
|
||||
.home-art { display: grid; gap: .5625rem; }
|
||||
.goddess-art { display: block; width: 18.75rem; max-width: 100%; aspect-ratio: 1; object-fit: cover; background: #f5f7f6; border-radius: 20px; }
|
||||
.home-art figcaption { color: var(--muted-foreground); font-size: .75rem; }
|
||||
.collection-grid { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: .625rem; }
|
||||
.collection-link { display: grid; min-width: 0; min-height: 10.625rem; align-content: start; gap: .75rem; padding: 1.125rem; color: var(--foreground); background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-xl); text-decoration: none; transition: color 180ms var(--ease-out), background-color 180ms var(--ease-out), border-color 180ms var(--ease-out), transform 120ms var(--ease-out); }
|
||||
.collection-link:hover { background: var(--accent); border-color: #b6cdc3; transform: translateY(-2px); }
|
||||
.collection-icon { display: grid; width: 2.125rem; height: 2.125rem; place-items: center; color: var(--primary); background: var(--accent); border-radius: .5rem; font-weight: 800; }
|
||||
.collection-copy { display: grid; min-width: 0; gap: .3125rem; }
|
||||
.collection-copy strong { font-size: .9375rem; line-height: 1.25; }
|
||||
.collection-copy span { color: var(--muted-foreground); font-size: .8125rem; line-height: 1.35; }
|
||||
.collection-count { color: var(--muted-foreground); font-size: .75rem; }
|
||||
.collection-arrow { align-self: end; color: var(--primary); font-size: 1.125rem; }
|
||||
.home-shelf { margin-top: 3.625rem; }
|
||||
.section-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 1.25rem; margin: 2.125rem 0 1rem; }
|
||||
.section-heading h2 { margin: 0; font: 400 1.6875rem/1.2 var(--font-serif); }
|
||||
.book-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 1.5rem; }
|
||||
.book-card { display: flex; min-width: 0; flex-direction: column; overflow: hidden; color: var(--foreground); background: var(--card); border-radius: var(--radius-xl); text-decoration: none; transition: color 180ms var(--ease-out), background-color 180ms var(--ease-out), transform 120ms var(--ease-out); }
|
||||
.book-card:hover { background: var(--accent); transform: translateY(-3px); }
|
||||
.book-card-image { display: grid; width: 100%; aspect-ratio: 1; place-items: center; overflow: hidden; background: #f5f7f6; border-radius: var(--radius-xl); }
|
||||
.book-card-image img { display: block; width: 100%; height: 100%; object-fit: contain; mix-blend-mode: multiply; }
|
||||
.book-title { margin: .9375rem 0 0; font-size: 1.125rem; line-height: 1.25; }
|
||||
.book-caption { margin: .375rem 0 0; color: var(--muted-foreground); font-size: .875rem; }
|
||||
.book-open { display: inline-flex; min-height: 2.75rem; align-items: center; gap: .4375rem; margin-top: auto; color: var(--primary); font-size: .875rem; font-weight: 700; }
|
||||
|
||||
.category-tools, .history-controls { display: flex; align-items: end; gap: .75rem; margin-bottom: 2rem; padding: 1.125rem 0; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); }
|
||||
.field { display: grid; min-width: 10.625rem; gap: .375rem; }
|
||||
.field.grow, .field:first-child { flex: 1; }
|
||||
.field > span, .field label { color: var(--muted-foreground); font-size: .8125rem; font-weight: 700; }
|
||||
.field input, .field select { width: 100%; height: 2.75rem; min-width: 0; padding: 0 .75rem; color: var(--foreground); background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-md); outline: 0; }
|
||||
.field input:focus, .field select:focus { border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ring) 18%, transparent); }
|
||||
.topic-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem; }
|
||||
.topic-card, .part-card { display: block; padding: 1.125rem; color: var(--foreground); background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-lg); text-decoration: none; transition: color 180ms var(--ease-out), background-color 180ms var(--ease-out), border-color 180ms var(--ease-out), transform 120ms var(--ease-out); }
|
||||
.topic-card { min-height: 7.5rem; }.topic-card:hover,.part-card:hover { background: var(--accent); border-color: #b6cdc3; transform: translateY(-2px); }
|
||||
.topic-heading { display: flex; align-items: baseline; justify-content: space-between; gap: .75rem; }.topic-heading h3 { margin: 0; font-size: 1rem; }.topic-count { color: var(--muted-foreground); font-size: .8125rem; font-weight: 700; }.topic-card p { margin: .4375rem 0 0; color: var(--muted-foreground); font-size: .875rem; }
|
||||
.list-heading,.document-details { display: flex; flex-wrap: wrap; gap: .5rem 1.125rem; color: var(--muted-foreground); font-size: .875rem; }.list-heading { justify-content: space-between; margin-bottom: .625rem; }.document-list,.version-list { border-top: 1px solid var(--border); }.document-row { display: flex; min-height: 5.625rem; align-items: center; gap: 1.375rem; padding: 1rem 0; border-bottom: 1px solid var(--border); }.document-main { min-width: 0; flex: 1; }.document-title { display: block; color: var(--primary); font-size: 1rem; font-weight: 750; line-height: 1.35; text-decoration: none; }.document-title:hover { text-decoration: underline; }.document-subject { margin-top: .25rem; color: var(--secondary-foreground); font-size: .875rem; }.document-details { margin-top: .375rem; }.document-meta { display: flex; flex: 0 0 auto; align-items: center; gap: 1.125rem; }.document-date { color: var(--muted-foreground); white-space: nowrap; font-variant-numeric: tabular-nums; }.document-open { display: inline-flex; min-height: 2.75rem; align-items: center; padding: .5rem .8125rem; color: var(--primary); border: 1px solid var(--border); border-radius: var(--radius-md); font-size: .875rem; font-weight: 700; text-decoration: none; }.document-open:hover { background: var(--accent); border-color: #b6cdc3; }
|
||||
.status-tag { padding: .1875rem .5rem; color: var(--success, #2f684d); background: var(--accent); border-radius: .3125rem; font-size: .75rem; font-weight: 700; }.status-tag.warning { color: #80581d; background: #fbf2df; }.muted,.help-note { color: var(--muted-foreground); }.text-link { color: var(--primary); font-size: .875rem; font-weight: 700; }.empty-state { padding: 3.5rem 1.25rem; color: var(--muted-foreground); text-align: center; border: 1px dashed #b8c8c0; border-radius: var(--radius-lg); }.empty-state strong { display: block; margin-bottom: .4375rem; color: var(--foreground); font: 400 1.375rem var(--font-serif); }.notice,.error-state { padding: .875rem 1rem; color: var(--secondary-foreground); background: var(--accent); border: 1px solid #c7d9d0; border-radius: var(--radius-lg); font-size: .875rem; }.notice.warning { color: #80581d; background: #fbf2df; border-color: #e6c98e; }.error-state { color: #a23d35; background: #fff1ef; border-color: #e6b8b1; }.pagination { display: flex; justify-content: center; gap: .5rem; margin-top: 1.75rem; }
|
||||
|
||||
.reader-document-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 1.5rem; margin-bottom: 1.625rem; }.reader-document-head .eyebrow { margin: 0 0 .625rem; color: var(--primary); font-size: .75rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; }.reader-document-head h1 { max-width: 28ch; margin: 0; color: var(--foreground); font: 400 clamp(1.875rem,4vw,2.875rem)/1.1 var(--font-serif); letter-spacing: -.03em; }.reader-shell { display: grid; grid-template-columns: 15rem minmax(0,1fr); gap: 2rem; align-items: start; }.reader-desktop-panel { min-width: 0; }.reader-desktop-panel:first-child { grid-column: 1; }.reader-desktop-panel:last-child { grid-column: 3; }.reader-toc { position: sticky; top: 6.25rem; min-width: 0; }.reader-center { min-width: 0; grid-column: 2; }.reader-related { position: static; grid-column: auto; }.reader-panel-content > h2,.reader-toc h2 { margin: 0 0 .75rem; font: 400 1.25rem var(--font-serif); }.toc-scroll { max-height: calc(100vh - 15rem); overflow: auto; padding-right: .3125rem; }.toc-link { display: block; width: 100%; padding: .5rem .625rem; color: var(--muted-foreground); border-left: 2px solid transparent; text-decoration: none; font-size: .875rem; text-align: left; }.toc-link:hover,.toc-link.is-active { color: var(--primary); background: var(--accent); border-left-color: var(--primary); }.toc-link[data-level="2"] { padding-left: 1.25rem; }.document-toolbar { position: sticky; top: 4.75rem; z-index: 4; display: flex; align-items: center; gap: .625rem; margin-bottom: 1.25rem; padding: .75rem 0; background: color-mix(in srgb, var(--background) 97%, transparent); border-bottom: 1px solid var(--line-soft, #edf1ef); }.document-toolbar .inline-actions { flex: 1; }.reader-find { display: flex; align-items: end; gap: .5rem; margin-bottom: 1rem; }.reader-find .field { flex: 1; }.reader-find button,.size-controls button { width: 2.75rem; height: 2.75rem; padding: 0; color: var(--primary); background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-md); cursor: pointer; }.size-controls { display: flex; gap: .3125rem; }.reader-meta { display: flex; flex-wrap: wrap; gap: .375rem 1.5rem; padding: .8125rem 0 1.375rem; color: var(--muted-foreground); border-bottom: 1px solid var(--border); font-size: .875rem; }.reading-text { max-width: 72ch; margin-top: 1.875rem; color: var(--foreground); font: 20px/1.8 var(--font-serif); }.text-fragment { margin-bottom: 2.25rem; scroll-margin-top: 9.375rem; }.fragment-heading { margin: 0 0 .75rem; color: var(--foreground); font: 400 1.625rem/1.25 var(--font-serif); }.fragment-body { white-space: pre-wrap; }.point-anchor { scroll-margin-top: 9.375rem; }.reader-panel-toggle { display: none; }.relation-item { margin-bottom: .5625rem; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-md); }.relation-item summary { min-height: 2.75rem; padding: .625rem .75rem; color: var(--primary); cursor: pointer; font-size: .875rem; font-weight: 700; }.relation-detail { padding: 0 .75rem .8125rem; color: var(--muted-foreground); font-size: .8125rem; line-height: 1.55; }.relation-detail p { margin: 0 0 .5rem; }.contents-list { max-width: 56.25rem; margin-top: 1.5rem; }.contents-list .toc-link { padding: .875rem 1rem; font-size: 1.0625rem; }.contents-list .toc-group { margin: .625rem 0; border: 1px solid var(--border); border-radius: var(--radius-lg); }.contents-list summary { padding: 1rem; cursor: pointer; font: 400 1.125rem var(--font-serif); }.part-grid { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: .875rem; }.part-card { min-height: 9.375rem; }.part-number { color: var(--primary); font: 400 2.125rem var(--font-serif); }.part-card h2 { margin: .625rem 0; font: 400 1.375rem var(--font-serif); }
|
||||
.updates-summary { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 1.125rem; }.schedule-details { padding: 1.25rem 0; border-top: 2px solid var(--primary); }.schedule-details h2 { margin: 0 0 1.125rem; font: 400 1.375rem var(--font-serif); }.schedule-details dl { display: grid; grid-template-columns: 1fr auto; gap: .75rem 1.5rem; margin: 0; }.schedule-details dt { color: var(--muted-foreground); }.schedule-details dd { margin: 0; font-weight: 700; }.graph-workspace { display: grid; grid-template-columns: minmax(0,1fr) 18.75rem; min-height: 38.75rem; overflow: hidden; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-xl); }.graph-stage { min-width: 0; background: #f7faf8; }.graph-mount,.graph-mount svg { min-height: 36.25rem; }.graph-mount { overflow: hidden; background: var(--card); }.graph-mount svg { display: block; width: 100%; height: 36.25rem; }.graph-sidebar { padding: 1.25rem; border-left: 1px solid var(--border); }.graph-node-list { display: grid; max-height: 26.25rem; gap: .1875rem; margin-top: 1.125rem; overflow: auto; }.graph-node-button { min-height: 2.75rem; padding: .5625rem; color: var(--secondary-foreground); background: transparent; border: 0; border-radius: var(--radius-sm); cursor: pointer; text-align: left; }.graph-node-button:hover { color: var(--primary); background: var(--accent); }
|
||||
|
||||
.ui-icon { display: inline-block; width: 1.75rem; height: 1.75rem; flex: 0 0 1.75rem; background: url("/assets/icons.webp") no-repeat var(--icon-x,0%) var(--icon-y,0%); background-size: 400% 400%; }
|
||||
.eunomia-sidebar [data-sidebar="header"] { padding: 1.5rem; }.brand-link { display: flex; align-items: center; gap: .6875rem; color: var(--foreground); text-decoration: none; }.brand-mark { display: grid; width: 2.125rem; height: 2.125rem; place-items: center; color: #fff; background: var(--primary); border-radius: 999px; font: 1.25rem/1 var(--font-serif); }.brand-copy { display: grid; gap: .0625rem; }.brand-copy strong { font: 1.125rem/1.1 var(--font-serif); letter-spacing: -.02em; }.brand-copy small { color: var(--muted-foreground); font-size: .6875rem; }
|
||||
.sidebar-status { display: flex; min-height: 2.75rem; align-items: center; gap: .5rem; padding: .5rem .625rem; color: var(--muted-foreground); font-size: .75rem; }
|
||||
.connection-dot { width: .4375rem; height: .4375rem; flex: 0 0 .4375rem; background: #80581d; border-radius: 999px; }.connection-dot.ready { background: #2f684d; }
|
||||
.sidebar-brand-note { display: block; padding: .375rem .625rem 0; color: var(--muted-foreground); font-size: .6875rem; }
|
||||
.search-launcher { display: flex; width: 22.5rem; min-width: 0; height: 2.75rem; flex: 0 1 22.5rem; align-items: center; gap: .5rem; margin-left: auto; padding: 0 .625rem 0 .75rem; color: var(--muted-foreground); background: #f6f7f8; border: 1px solid var(--border); border-radius: 10px; cursor: pointer; text-align: left; }
|
||||
.search-launcher:hover { color: var(--primary); background: var(--accent); border-color: #b6cdc3; }.search-launcher > span:not(.ui-icon) { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.search-launcher kbd { padding: .125rem .375rem; color: var(--muted-foreground); background: var(--background); border: 1px solid var(--border); border-radius: .25rem; font-size: .6875rem; }
|
||||
.command-status { padding: 1rem; color: var(--muted-foreground); font-size: .875rem; text-align: center; }.command-footer { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: .75rem 1rem; padding: .625rem .75rem; color: var(--muted-foreground); border-top: 1px solid var(--border); font-size: .6875rem; }
|
||||
.command-footer span { white-space: nowrap; }
|
||||
[cmdk-item] strong,[cmdk-item] small { display: block; }[cmdk-item] > span:last-child { display: grid; min-width: 0; gap: .2rem; }[cmdk-item] small { overflow: hidden; color: var(--muted-foreground); font-size: .75rem; text-overflow: ellipsis; white-space: nowrap; }.command-status + [cmdk-group] small { color: var(--muted-foreground); font-size: .75rem; }
|
||||
[data-sidebar="sidebar"] { color: var(--sidebar-foreground); background: var(--sidebar); }
|
||||
[data-sidebar="menu-button"] { min-height: 2.75rem; color: var(--sidebar-foreground); border-radius: var(--radius-md); transition: color 180ms var(--ease-out), background-color 180ms var(--ease-out), transform 120ms var(--ease-out); }
|
||||
[data-sidebar="menu-button"]:hover,[data-sidebar="menu-button"][data-active="true"] { color: var(--sidebar-accent-foreground); background: var(--sidebar-accent); }
|
||||
[data-sidebar="footer"] { color: var(--muted-foreground); }
|
||||
.eunomia-sidebar .brand-copy,.eunomia-sidebar [data-sidebar="group-label"],.eunomia-sidebar [data-sidebar="menu-badge"] { transition: opacity 180ms var(--ease-out); }
|
||||
.group[data-collapsible="icon"] .eunomia-sidebar .brand-copy,.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="group-label"],.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="menu-badge"],.group[data-collapsible="icon"] .eunomia-sidebar .sidebar-footer-copy { display: none; }
|
||||
.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="menu-button"] { min-height: 2.75rem; justify-content: center; }
|
||||
body.reading-focus .eunomia-shell .group.peer:has(.eunomia-sidebar) { display: none; }
|
||||
body.reading-focus .eunomia-main { margin-left: 0; }
|
||||
.reader-mobile-actions { display: none; }
|
||||
.reader-mobile-overlay { display: none; }
|
||||
|
||||
@media (min-width:1600px) { .reader-shell { grid-template-columns: 15rem minmax(37.5rem,1fr) 17.5rem; gap: 2rem; }.reader-related { grid-column: 3; position: sticky; top: 6.25rem; }.reader-related .reader-panel-toggle { display: none; }.reader-related .reader-panel-content { display: block; } }
|
||||
@media (min-width:761px) and (max-width:1599px) { .reader-related.is-open { position: fixed; z-index: 40; top: 4.75rem; right: 0; bottom: 0; width: min(23.75rem,calc(100vw - 2rem)); padding: 1.5rem; overflow: auto; background: var(--card); border-left: 1px solid var(--border); box-shadow: -1rem 0 2rem #19382c20; animation: drawer-in 220ms var(--ease-drawer); }.reader-related.is-open .reader-panel-content { display: block; }.reader-related.is-open .reader-panel-toggle { display: flex; width: 100%; margin-bottom: .875rem; }.reader-related.is-open .reader-panel-toggle::after { margin-left: auto; content: "×"; font-size: 1.4375rem; } }
|
||||
@keyframes drawer-in { from { opacity: 0; transform: translateX(1.25rem); } to { opacity: 1; transform: none; } }
|
||||
@media (max-width:1100px) { .content { padding-inline: 1.75rem; }.topbar { padding-inline: 1.75rem; }.collection-grid { grid-template-columns: repeat(3,minmax(0,1fr)); }.book-grid { grid-template-columns: repeat(3,minmax(0,1fr)); } }
|
||||
@media (max-width:760px) { .topbar { flex-wrap: wrap; height: auto; min-height: 4.75rem; padding: .75rem 1rem; }.topbar .menu-toggle { display: grid; }.breadcrumb { order: 2; flex: 1; min-width: 0; }.refresh-button { order: 1; }.global-search { order: 3; flex-basis: 100%; width: auto; margin: 0; }.content { padding: 2.25rem 1.125rem 4rem; }.page-heading { display: block; }.heading-actions { margin-top: 1.125rem; }.page-heading h1 { font-size: 2.125rem; }.home-intro { display: block; margin-bottom: 2.875rem; }.home-intro h1 { font-size: 3.125rem; }.home-intro-copy > p { font-size: 1.0625rem; }.home-search { width: 100%; }.home-search input,.home-search .button { height: 3.25rem; }.home-art { margin-top: 1.875rem; }.goddess-art { max-width: none; }.collection-grid,.topic-grid,.updates-summary { grid-template-columns: repeat(2,minmax(0,1fr)); }.collection-grid { gap: .5rem; }.collection-link { min-height: 9.375rem; padding: .875rem; }.book-grid { grid-template-columns: repeat(2,minmax(0,1fr)); gap: 1.125rem .75rem; }.book-title { font-size: 1rem; }.category-tools,.history-controls { display: grid; grid-template-columns: 1fr; align-items: stretch; }.document-row { display: block; padding: 1.0625rem 0; }.document-meta { justify-content: space-between; margin-top: .625rem; }.document-open { width: 100%; margin-top: .4375rem; }.section-heading { align-items: flex-start; flex-direction: column; gap: .375rem; }.part-grid,.diff-grid { grid-template-columns: 1fr; }.reader-document-head { display: block; }.reader-document-head .heading-actions { margin-top: 1rem; }.reader-shell { display: block; }.reader-toc,.reader-related { position: static; margin-bottom: .875rem; }.reader-panel-toggle { display: flex; width: 100%; align-items: center; justify-content: space-between; }.reader-panel-toggle::after { content: "+"; font-size: 1.25rem; }.reader-panel-toggle[aria-expanded="true"]::after { content: "−"; }.reader-panel-content { display: none; padding-top: .75rem; }.reader-panel-content.is-open { display: block; }.toc-scroll { max-height: 18.75rem; padding: 0; }.document-toolbar { position: static; display: block; margin-bottom: 1.125rem; }.document-toolbar .inline-actions { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); }.document-toolbar .inline-actions .button { width: 100%; }.size-controls { margin-top: .5625rem; }.reader-find { display: grid; grid-template-columns: 1fr 2.75rem 2.75rem; }.reader-find .field { grid-column: 1/-1; }.reading-text { font-size: 20px; line-height: 1.8; }.graph-workspace { display: block; }.graph-sidebar { border-top: 1px solid var(--border); border-left: 0; }.graph-mount,.graph-mount svg { min-height: 27.5rem; height: 27.5rem; }.version-item { display: grid; gap: .25rem; } }
|
||||
@media (max-width:430px) { .collection-grid { grid-template-columns: 1fr 1fr; }.collection-link { min-height: 8.875rem; }.home-intro h1 { font-size: 2.875rem; }.book-grid { gap: 1.125rem .625rem; }.book-caption { font-size: .8125rem; } }
|
||||
@media (forced-colors:active) { .button,.collection-link,.topic-card,.part-card,.field input,.field select { border: 1px solid ButtonText; }.brand-mark { border: 1px solid ButtonText; }.status-tag { border: 1px solid currentColor; } }
|
||||
@media (prefers-reduced-motion:reduce) { *,*::before,*::after { scroll-behavior: auto !important; animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; } }
|
||||
|
||||
@media (min-width:761px) {
|
||||
.reader-mobile-actions,.reader-mobile-overlay { display: none; }
|
||||
}
|
||||
@media (max-width:760px) {
|
||||
.reader-mobile-actions { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: .5rem; margin-bottom: 1rem; }
|
||||
.reader-mobile-actions .button { width: 100%; }
|
||||
.reader-desktop-panel { display: none; }
|
||||
.reader-mobile-overlay { position: fixed; inset: 0; z-index: 60; display: grid; align-items: end; background: #17382f66; }
|
||||
.reader-mobile-overlay > div { max-height: 86vh; overflow: auto; padding: 1.25rem; background: var(--card); border-top: 1px solid var(--border); border-radius: 1rem 1rem 0 0; box-shadow: 0 -1rem 2rem #19382c20; animation: drawer-up 220ms var(--ease-drawer); }
|
||||
.reader-mobile-overlay .reader-toc,.reader-mobile-overlay .reader-related { display: block; margin: 0 0 1rem; }
|
||||
.reader-mobile-overlay .reader-panel-content { display: block; }
|
||||
.reader-mobile-overlay .toc-scroll { max-height: 45vh; }
|
||||
}
|
||||
@keyframes drawer-up { from { opacity: 0; transform: translateY(1.25rem); } to { opacity: 1; transform: none; } }
|
||||
|
||||
/* shadcn collapsible=icon keeps controls usable at touch size. */
|
||||
.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="menu-button"] { width: 2.75rem !important; min-width: 2.75rem; min-height: 2.75rem; padding: .375rem !important; }
|
||||
.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="menu-button"] > span:last-child { display: none; }
|
||||
.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="header"] { padding: .5rem; }
|
||||
|
||||
@media (min-width:1101px) and (max-width:1599px) {
|
||||
.reader-shell { grid-template-columns: 15rem minmax(0,1fr); }
|
||||
.reader-desktop-panel:last-child { display: none; }
|
||||
.reader-mobile-actions { display: flex; justify-content: flex-end; margin-bottom: 1rem; }
|
||||
.reader-mobile-actions .button:first-child { display: none; }
|
||||
}
|
||||
@media (max-width:1100px) {
|
||||
.reader-desktop-panel { display: none; }
|
||||
.reader-shell { display: block; }
|
||||
.reader-mobile-actions { display: flex; gap: .5rem; margin-bottom: 1rem; }
|
||||
.reader-mobile-actions .button { flex: 1; }
|
||||
}
|
||||
@media (max-width:760px) {
|
||||
.search-launcher { min-width: 0; flex: 1; margin-left: 0; }
|
||||
.search-launcher > span:not(.ui-icon) { font-size: 0; }.search-launcher > span:not(.ui-icon)::before { content: "Поиск"; font-size: .875rem; }.search-launcher kbd { display: none; }
|
||||
.home-intro { max-height: none; }
|
||||
.reader-document-head h1 { max-width: none; font-size: 2rem; }
|
||||
}
|
||||
|
||||
.reader-mobile-sheet { max-height: 100dvh; overflow-y: auto; }
|
||||
.reader-mobile-sheet .reader-toc,.reader-mobile-sheet .reader-related,.reader-mobile-sheet .reader-panel-content { display: block; position: static; max-height: none; overflow: visible; }
|
||||
.reader-mobile-sheet .toc-scroll { max-height: min(55vh, 34rem); overflow-y: auto; }
|
||||
.reader-mobile-sheet .reader-panel-content > h2 { font-size: 1.375rem; }
|
||||
|
||||
body.reading-focus .reader-desktop-panel { display: none; }
|
||||
body.reading-focus .reader-shell { display: block; }
|
||||
body.reading-focus .reader-center { max-width: 52rem; margin-inline: auto; }
|
||||
body.reading-focus .reader-document-head .inline-actions { display: flex; }
|
||||
|
||||
.graph-scroll { width: 100%; overflow: auto; overscroll-behavior: contain; }
|
||||
.legal-graph { display: block; width: 100%; min-width: 42.5rem; height: auto; }
|
||||
.graph-node-label { color: var(--foreground); font-family: var(--font-sans); line-height: 1.25; }
|
||||
.graph-node-label strong,.graph-node-label small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.graph-node-label strong { font-size: .875rem; font-weight: 750; }.graph-node-label small { margin-top: .25rem; color: var(--muted-foreground); font-size: .6875rem; }
|
||||
.graph-accessible-list { padding: .75rem 1rem; border-top: 1px solid var(--border); }.graph-accessible-list summary { cursor: pointer; color: var(--primary); font-size: .875rem; font-weight: 700; }
|
||||
.diff-columns { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 1px; overflow: hidden; background: var(--border); border: 1px solid var(--border); border-radius: var(--radius-md); }.diff-columns > div { min-width: 0; padding: 1rem; background: var(--card); }.diff-columns h3 { margin: 0 0 .5rem; color: var(--muted-foreground); font-size: .8125rem; }.diff-columns pre { margin: 0; overflow: auto; white-space: pre-wrap; font: .875rem/1.7 var(--font-sans); }
|
||||
@media (max-width:600px) { .diff-columns { grid-template-columns: 1fr; }.legal-graph { min-width: 36rem; } }
|
||||
|
||||
/* The icon is part of the search field, not a separate column. */
|
||||
.home-search { position: relative; }
|
||||
.home-search > .ui-icon { position: absolute; left: .65rem; top: .875rem; pointer-events: none; }
|
||||
.home-search input { padding-left: 2.75rem; }
|
||||
.home-art a { text-decoration: none; }
|
||||
.home-art figcaption { display: flex; align-items: center; gap: .5rem; margin-top: .4rem; }
|
||||
.graph-entry { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-top: 2.5rem; padding: 1.25rem 0; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); text-decoration: none; }
|
||||
.graph-entry > span { display: inline-flex; align-items: center; gap: .5rem; }
|
||||
.graph-entry:hover { color: var(--primary); background: var(--accent); }
|
||||
.home-page > .help-note { margin-top: 1rem; }
|
||||
.collection-link > .ui-icon:last-child { margin-top: auto; }
|
||||
[data-sidebar="menu-button"] { font-size: .9375rem; }
|
||||
@media(max-width:760px) { .graph-entry { align-items: flex-start; flex-direction: column; } .home-search > .ui-icon { top: .75rem; } }
|
||||
|
||||
.legal-graph { touch-action: none; cursor: grab; user-select: none; }
|
||||
.legal-graph.is-panning { cursor: grabbing; }
|
||||
|
||||
.reader-find button:not([aria-label]) { width: auto; min-width: 4.75rem; padding-inline: .875rem; }
|
||||
.reader-find-count { white-space: nowrap; align-self: center; }
|
||||
@media (min-width: 641px) and (max-width: 1100px) { .reader-document-head { display: block; } .reader-document-head .heading-actions { margin-top: 1rem; } }
|
||||
@@ -0,0 +1,159 @@
|
||||
import {useMemo, useState} from 'react'
|
||||
import {Icon} from '../components/Icon'
|
||||
import {docCount, docHref, href, kinds, normalized, shortDate, useApi, type LegalDocument, type Route} from '../lib/api'
|
||||
|
||||
const CODE_SUFFIXES = ['gk-rf', 'gpk-rf', 'apk-rf', 'sk-rf', 'kas-rf', 'koap-rf', 'nk-rf-gosposhlina', 'tk-rf', 'zhk-rf', 'zk-rf', 'uk-rf', 'upk-rf']
|
||||
const TOPICS = [
|
||||
['civil', 'Гражданское право', 'Договоры, собственность, обязательства', /договор|собственност|обязательств|гражданск.{0,12}кодекс|наслед|сдел[ок]|жилищ|вещн|вред|потребител/i],
|
||||
['process', 'Судебный процесс', 'Иски, доказательства, обжалование', /процесс|производств|судебн.{0,14}решени|подсудност|апелляц|кассац|доказательств|расход|судебн.{0,12}приказ|арбитражн/i],
|
||||
['criminal', 'Уголовное право', 'Преступления и назначение наказания', /уголовн|преступлен|наказани|осужден|приговор|хищени|взяточ|убийств|мошеннич|наркот/i],
|
||||
['admin', 'Административное право', 'Правонарушения и публичные споры', /административн|правонарушени|публичн|государственн.{0,8}служб|избирательн/i],
|
||||
['work', 'Труд и социальные права', 'Работа, пенсии, социальные выплаты', /трудов|работник|работодател|пенси|социальн|заработн|забастов/i],
|
||||
['family', 'Семья и дети', 'Брак, алименты, защита прав детей', /семейн|брачн|алимент|родител|детей|ребенк|усыновл|расторжени.{0,8}брак/i],
|
||||
['business', 'Экономические споры', 'Банкротство, налоги, деятельность компаний', /банкрот|несостоятельн|налог|таможен|экономическ|корпоративн|акционер|предпринимател|конкуренц/i],
|
||||
['other', 'Другие вопросы', 'Документы вне выбранных направлений', null],
|
||||
] as const
|
||||
|
||||
const idSuffix = (doc: LegalDocument) => doc.id.split(':').at(-1) || doc.id
|
||||
const shortName = (doc: LegalDocument) => (doc.subject || doc.title)
|
||||
.replace(/\s+Российской Федерации/g, '')
|
||||
.replace(/\s+от\s+\d{2}\.\d{2}\.\d{4}.*$/, '')
|
||||
.replace(/[«»]/g, '')
|
||||
const exactTitle = (doc: LegalDocument) => doc.subject || doc.title
|
||||
const isCode = (doc: LegalDocument) => doc.kind === 'code' && CODE_SUFFIXES.includes(idSuffix(doc))
|
||||
const kindLabel = (kind: LegalDocument['kind']) => kinds[kind]?.[0] || 'Документы'
|
||||
const titleDate = (doc: LegalDocument) => doc.act_date || doc.effective_date || doc.revision
|
||||
|
||||
function coverageCaption(doc: LegalDocument) {
|
||||
if (!doc.available) return 'Текст пока не загружен'
|
||||
if (doc.coverage?.status === 'partial') return 'Доступна часть текста'
|
||||
if (doc.warnings?.length) return 'Требует сверки'
|
||||
if (idSuffix(doc) === 'gk-rf') return 'Четыре части'
|
||||
if (doc.coverage?.status === 'full') return 'Текст загружен'
|
||||
return 'Полнота требует проверки'
|
||||
}
|
||||
|
||||
export function BookCard({doc}: {doc: LegalDocument}) {
|
||||
const cover = isCode(doc) ? `/assets/books/${idSuffix(doc)}.webp` : null
|
||||
return <a className={`book-card ${cover ? '' : 'book-card-text'}`} href={href({view: 'contents', id: doc.id})} data-title={exactTitle(doc)}>
|
||||
{cover ? <div className="book-card-image"><img src={cover} alt={`Обложка: ${shortName(doc)}`} width="320" height="220" loading="lazy" /></div> : <span className="law-symbol"><Icon name={doc.kind} /></span>}
|
||||
<h2 className="book-title">{shortName(doc)}</h2>
|
||||
<p className="book-caption">{coverageCaption(doc)}</p>
|
||||
<span className="book-open">Открыть <Icon name="arrow" /></span>
|
||||
</a>
|
||||
}
|
||||
|
||||
function CollectionLink({kind, count}: {kind: LegalDocument['kind']; count: number}) {
|
||||
const [label, description] = kinds[kind]
|
||||
return <a className="collection-link" href={href({view: 'category', kind})}>
|
||||
<Icon name={kind} />
|
||||
<span className="collection-copy"><strong>{label}</strong><span>{description}</span></span>
|
||||
<span className="collection-count">{count}</span><Icon name="arrow" />
|
||||
</a>
|
||||
}
|
||||
|
||||
export function Home({docs}: {docs: LegalDocument[]}) {
|
||||
const [query, setQuery] = useState('')
|
||||
const count = (kind: LegalDocument['kind']) => docs.filter(doc => doc.kind === kind).length
|
||||
const shelf = ['gk-rf', 'gpk-rf', 'apk-rf', 'sk-rf'].map(suffix => docs.find(doc => idSuffix(doc) === suffix)).filter(Boolean) as LegalDocument[]
|
||||
return <div className="page home-page">
|
||||
<section className="home-intro">
|
||||
<div className="home-intro-copy">
|
||||
<span className="home-label">Эвномия · Themiz</span>
|
||||
<h1>Библиотека</h1>
|
||||
<p>Нормативные акты и судебная практика</p>
|
||||
<form className="home-search" onSubmit={event => {event.preventDefault(); const q = query.trim(); if (q) window.location.hash = href({view: 'search', q}).slice(1)}}>
|
||||
<label className="sr-only" htmlFor="home-query">Поиск по библиотеке</label>
|
||||
<Icon name="search" /><input id="home-query" type="search" value={query} onChange={event => setQuery(event.target.value)} placeholder="Название, статья или фраза" autoComplete="off" />
|
||||
<button className="button primary" type="submit">Найти</button>
|
||||
</form>
|
||||
<div className="home-examples"><span>Например:</span><a href={href({view: 'search', q: 'ст. 131 ГПК'})}>ст. 131 ГПК</a><a href={href({view: 'search', q: 'ст. 395 ГК'})}>ст. 395 ГК</a></div>
|
||||
</div>
|
||||
<figure className="home-art"><a href={href({view: 'contents', id: docs.find(doc => idSuffix(doc) === 'gk-rf')?.id})}><img className="goddess-art" src="/assets/books/gk-rf.webp" alt="Обложка Гражданского кодекса Российской Федерации" width="280" height="280" /><figcaption><span>Гражданский кодекс</span><Icon name="arrow" /></figcaption></a></figure>
|
||||
</section>
|
||||
<div className="section-heading"><h2>Разделы библиотеки</h2><span>{docCount(docs.length)}</span></div>
|
||||
<div className="collection-grid"><CollectionLink kind="code" count={count('code')} /><CollectionLink kind="federal-law" count={count('federal-law')} /><CollectionLink kind="bylaw" count={count('bylaw')} /><CollectionLink kind="plenum" count={count('plenum')} /><CollectionLink kind="review" count={count('review')} /></div>
|
||||
<section className="home-shelf"><div className="section-heading"><h2>Кодексы</h2><a className="text-link" href={href({view: 'category', kind: 'code'})}>Все кодексы <Icon name="arrow" /></a></div><div className="book-grid">{shelf.map(doc => <BookCard key={doc.id} doc={doc} />)}</div></section>
|
||||
<a className="graph-entry" href={href({view: 'graph'})}><strong>Связи статей и разъяснений</strong><span>Открыть граф связей <Icon name="arrow" /></span></a>
|
||||
<p className="help-note">Тексты хранятся на компьютере. Полнота и дата проверки указаны в документе.</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
function matchesTopic(doc: LegalDocument, topic: string) {
|
||||
if (!topic || topic === 'all') return true
|
||||
const text = `${doc.subject || ''} ${doc.title}`
|
||||
if (topic === 'other') return !TOPICS.some(item => item[3] && item[3].test(text))
|
||||
return TOPICS.find(item => item[0] === topic)?.[3]?.test(text) || false
|
||||
}
|
||||
|
||||
function identity(doc: LegalDocument) {
|
||||
const text = [doc.act_date, doc.number, doc.title].filter(Boolean).join(' ')
|
||||
const match = text.match(/\b(\d{2})\.(\d{2})\.(\d{4})\b/)
|
||||
const key = match ? `${match[3]}-${match[2]}-${match[1]}` : ''
|
||||
return {date: match ? `${match[1]}.${match[2]}.${match[3]}` : null, key, year: match?.[3] || '', number: doc.number || ''}
|
||||
}
|
||||
|
||||
function DocumentRow({doc}: {doc: LegalDocument}) {
|
||||
const meta = identity(doc)
|
||||
const warning = !doc.available ? 'Текст пока не загружен' : doc.coverage?.status === 'partial' ? 'Неполный текст' : doc.warnings?.length ? 'Нужна сверка' : ''
|
||||
return <article className="document-row" data-act-date={meta.key}>
|
||||
<div className="document-main"><a className="document-title" href={docHref(doc.id)}>{exactTitle(doc)}</a><div className="document-details"><span>{kindLabel(doc.kind)}{meta.number ? ` № ${meta.number}` : ''}</span><span>Редакция: {shortDate(doc.revision)}</span>{warning && <span className="status-tag warning">{warning}</span>}</div></div>
|
||||
<div className="document-meta"><span className="document-date">{meta.date ? <time dateTime={meta.key}>{meta.date}</time> : 'Дата не указана'}</span><a className="document-open" href={docHref(doc.id)} aria-label={`Читать: ${exactTitle(doc)}`}>Читать <Icon name="arrow" /></a></div>
|
||||
</article>
|
||||
}
|
||||
|
||||
function Pagination({page, total, route}: {page: number; total: number; route: Route}) {
|
||||
const pages = Math.max(1, Math.ceil(total / 12))
|
||||
if (pages <= 1) return null
|
||||
return <nav className="pagination" aria-label="Страницы документов"><a className={`button quiet ${page === 1 ? 'is-disabled' : ''}`} aria-disabled={page === 1 || undefined} href={page === 1 ? undefined : href({...route, page: page - 1})}>Назад</a><span>Страница {page} из {pages}</span><a className={`button quiet ${page === pages ? 'is-disabled' : ''}`} aria-disabled={page === pages || undefined} href={page === pages ? undefined : href({...route, page: page + 1})}>Далее</a></nav>
|
||||
}
|
||||
|
||||
function YearGroups({docs}: {docs: LegalDocument[]}) {
|
||||
const groups = new Map<string, LegalDocument[]>()
|
||||
docs.forEach(doc => {const year = identity(doc).year || 'Дата не указана'; groups.set(year, [...(groups.get(year) || []), doc])})
|
||||
return <>{[...groups].map(([year, rows]) => <section className="year-group" key={year}><h2>{year}{/^\d/.test(year) ? ' год' : ''}</h2><div className="document-list">{rows.map(doc => <DocumentRow key={doc.id} doc={doc} />)}</div></section>)}</>
|
||||
}
|
||||
|
||||
export function Category({docs, route}: {docs: LegalDocument[]; route: Route}) {
|
||||
const kind = route.kind && route.kind in kinds ? route.kind as LegalDocument['kind'] : 'code'
|
||||
const all = docs.filter(doc => doc.kind === kind)
|
||||
const isBooks = kind === 'code' || kind === 'federal-law'
|
||||
const query = normalized(route.q)
|
||||
const books = all.filter(doc => normalized(`${doc.title} ${doc.subject || ''}`).includes(query))
|
||||
const hasTopics = ['plenum', 'review', 'bylaw'].includes(kind)
|
||||
const showTopics = hasTopics && !route.topic && !route.q && !route.year
|
||||
const years = [...new Set(all.map(doc => identity(doc).year).filter(Boolean))].sort()
|
||||
const sort = route.sort === 'new' ? 'new' : 'old'
|
||||
const filtered = all.filter(doc => matchesTopic(doc, route.topic || 'all') && (!route.year || identity(doc).year === route.year) && (!query || normalized(`${doc.title} ${doc.subject || ''} ${doc.number || ''} ${identity(doc).date || ''}`).includes(query))).sort((a, b) => {
|
||||
const aa = identity(a), bb = identity(b)
|
||||
if (!aa.key) return bb.key ? 1 : a.title.localeCompare(b.title, 'ru')
|
||||
if (!bb.key) return -1
|
||||
return (sort === 'new' ? -1 : 1) * aa.key.localeCompare(bb.key) || aa.number.localeCompare(bb.number, 'ru', {numeric: true})
|
||||
})
|
||||
const page = Math.min(Math.max(1, Number(route.page) || 1), Math.max(1, Math.ceil(filtered.length / 12)))
|
||||
if (isBooks) return <div className="page book-library"><div className="page-heading"><div><h1>{kindLabel(kind)}</h1><p>{kind === 'code' ? 'Откройте кодекс и выберите нужную статью.' : 'Законы по отдельным вопросам.'}</p></div></div><form id="book-filter" className="book-filter category-tools" onSubmit={event => {event.preventDefault(); const form = new FormData(event.currentTarget); window.location.hash = href({view: 'category', kind, q: String(form.get('q') || '')}).slice(1)}}><label className="field grow"><span>Найти {kind === 'code' ? 'кодекс' : 'закон'}</span><input name="q" type="search" defaultValue={route.q || ''} placeholder="Название или сокращение" /></label><button className="button primary" type="submit">Найти</button></form><div className="book-grid">{books.map(doc => <BookCard key={doc.id} doc={doc} />)}</div>{!books.length && <p className="empty-state"><strong>Ничего не найдено</strong><span>Попробуйте другое название или сокращение.</span></p>}</div>
|
||||
const topic = TOPICS.find(item => item[0] === route.topic)
|
||||
return <div className="page"><div className="page-heading"><div><h1>{topic?.[1] || kindLabel(kind)}</h1><p>{showTopics ? 'Выберите направление или найдите документ по названию, номеру и дате.' : `${docCount(filtered.length)} · Дата акта и редакция показаны отдельно.`}</p></div></div><form className="category-tools" onSubmit={event => {event.preventDefault(); const form = new FormData(event.currentTarget); const value = (name: string) => String(form.get(name) || ''); window.location.hash = href({view: 'category', kind, topic: value('topic'), q: value('q'), year: value('year'), sort: value('sort')}).slice(1)}}><label className="field grow"><span>Поиск в разделе</span><input name="q" type="search" defaultValue={route.q || ''} placeholder="Название, номер или дата" /></label>{hasTopics && <label className="field"><span>Направление</span><select name="topic" defaultValue={route.topic || ''}><option value="">Любое направление</option>{TOPICS.map(item => <option key={item[0]} value={item[0]}>{item[1]}</option>)}</select></label>}<label className="field"><span>Год акта</span><select name="year" defaultValue={route.year || ''}><option value="">Все годы</option>{years.map(year => <option key={year} value={year}>{year}</option>)}</select></label><label className="field"><span>По дате акта</span><select name="sort" defaultValue={sort}><option value="old">Сначала ранние</option><option value="new">Сначала новые</option></select></label><button className="button primary" type="submit">Найти</button></form>{showTopics ? <><div className="section-heading"><h2>По направлениям</h2><a className="text-link" href={href({view: 'category', kind, topic: 'all'})}>Все {docCount(all.length)} <Icon name="arrow" /></a></div><div className="topic-grid">{TOPICS.map(item => <a className="topic-card" key={item[0]} href={href({view: 'category', kind, topic: item[0]})}><div className="topic-heading"><h3>{item[1]}</h3><span className="topic-count">{all.filter(doc => matchesTopic(doc, item[0])).length}</span></div><p>{item[2]}</p></a>)}</div><p className="help-note">Направления определены по названиям документов. Один документ может относиться к нескольким направлениям.</p></> : <><div className="list-heading"><span>{docCount(filtered.length)}</span><span>{sort === 'new' ? 'От поздних дат к ранним' : 'От ранних дат к поздним'}</span></div>{filtered.length ? <YearGroups docs={filtered.slice((page - 1) * 12, page * 12)} /> : <p className="empty-state"><strong>Документы не найдены</strong><span>Попробуйте другое направление, год или название.</span></p>}<Pagination page={page} total={filtered.length} route={route} /></>}</div>
|
||||
}
|
||||
|
||||
function tocRows(rows: Array<{id: string; label: string; kind?: string}>, id: string, query: string) {
|
||||
const filtered = rows.filter(row => !query || normalized(row.label).includes(normalized(query)))
|
||||
return <div className="contents-list">{filtered.map(row => /^Глава\s/i.test(row.label) ? <details className="toc-group" key={row.id} open={Boolean(query)}><summary>{row.label}</summary><a className="toc-link" href={docHref(id, row.id)}>{row.label}</a></details> : <a className="toc-link" key={row.id} href={docHref(id, row.id)} data-level={row.kind === 'article' || row.kind === 'point' ? '2' : '1'}>{row.label}</a>)}</div>
|
||||
}
|
||||
|
||||
export function Contents({docs, route}: {docs: LegalDocument[]; route: Route}) {
|
||||
const doc = docs.find(item => item.id === route.id || item.id === route.doc)
|
||||
const id = doc?.id || route.id || route.doc || ''
|
||||
const {data, error, loading} = useApi<{toc: Array<{id: string; label: string; kind?: string}>}>(id ? `/reader?${new URLSearchParams({id})}` : null)
|
||||
const [query, setQuery] = useState('')
|
||||
const toc = data?.toc || []
|
||||
const parts = useMemo(() => toc.filter(row => /^Часть\s+(первая|вторая|третья|четвертая|четвёртая)/i.test(row.label)), [toc])
|
||||
if (!doc) return <div className="page"><p className="empty-state"><strong>Документ не найден</strong><span>Откройте библиотеку.</span></p></div>
|
||||
if (loading) return <div className="page"><h1>{shortName(doc)}</h1><p className="help-note">Открываем оглавление…</p></div>
|
||||
if (error) return <div className="page"><h1>{shortName(doc)}</h1><p className="empty-state"><strong>Оглавление пока недоступно</strong><span>{error}</span></p></div>
|
||||
const partStart = route.part ? toc.findIndex(row => row.id === route.part) : -1
|
||||
const nextPart = partStart >= 0 ? toc.findIndex((row, index) => index > partStart && parts.some(part => part.id === row.id)) : -1
|
||||
const rows = partStart >= 0 ? toc.slice(partStart, nextPart < 0 ? toc.length : nextPart) : toc
|
||||
const choosePart = parts.length > 1 && !route.part
|
||||
return <div className="page contents-page"><div className="page-heading"><div><h1>{shortName(doc)}</h1><p>{exactTitle(doc)}</p></div></div>{choosePart ? <><p className="contents-intro">Выберите часть кодекса</p><div className="part-grid">{parts.slice(0, 4).map((part, index) => <a className="part-card" key={part.id} href={href({view: 'contents', id: doc.id, part: part.id})}><span className="part-number">{['I', 'II', 'III', 'IV'][index]}</span><h2>{part.label}</h2><span>Разделы и статьи <Icon name="arrow" /></span></a>)}</div></> : <><div className="section-heading"><h2>{rows[0]?.label?.startsWith('Часть ') ? rows[0].label : 'Оглавление'}</h2><a className="button quiet" href={docHref(doc.id, rows[0]?.id)}>Читать с начала</a></div>{parts.length > 1 && <a className="text-link" href={href({view: 'contents', id: doc.id})}>← Все части кодекса</a>}<label className="field"><span>Статья, пункт или слово в заголовке</span><input type="search" value={query} onChange={event => setQuery(event.target.value)} placeholder="Например, 395" /></label>{tocRows(rows, doc.id, query)}</>}</div>
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
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>
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022", "lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext", "moduleResolution": "bundler",
|
||||
"jsx": "react-jsx", "strict": true, "skipLibCheck": true,
|
||||
"esModuleInterop": true, "resolveJsonModule": true,
|
||||
"noEmit": true, "allowImportingTsExtensions": true,
|
||||
"paths": {"@/*": ["./src/*"]}
|
||||
},
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
|
||||
publicDir: false,
|
||||
build: { outDir: '../web/dist', emptyOutDir: true },
|
||||
server: { proxy: { '/api': 'http://127.0.0.1:18765', '/assets/books': 'http://127.0.0.1:18765', '/assets/icons.webp': 'http://127.0.0.1:18765' } },
|
||||
})
|
||||
Reference in New Issue
Block a user