import { useCallback, useEffect, useState } from 'react';
import { Link, Navigate, useParams } from 'react-router-dom';
import { ArticleBody, type Figure } from '../components/ArticleBody';
import { IconList, IconPrint, IconStar, IconTheme, IconUp } from '../components/Icons';
import { Lightbox } from '../components/Lightbox';
import { PrintSheet } from '../components/PrintSheet';
import { Screen } from '../components/Shell';
import { BackLink, Notice, Sheet, Skeleton } from '../components/ui';
import { ApiError, useArticle } from '../lib/api';
import { fileExt, formatBytes, formatDate, num2 } from '../lib/format';
import { pushRecent, useFavorites } from '../lib/store';
import { useTheme } from '../lib/theme';
import { useNav } from '../lib/tree';
/** Прокрутка страницы: показывать ли липкую шапку (после 160 px) и прогресс чтения шагами по 2%. */
function useReadProgress() {
const [state, setState] = useState({ scrolled: false, progress: 0 });
useEffect(() => {
let frame = 0;
const update = () => {
frame = 0;
const max = document.documentElement.scrollHeight - window.innerHeight;
const p = max > 0 ? Math.min(1, window.scrollY / max) : 0;
const next = { scrolled: window.scrollY > 160, progress: Math.round(p * 50) / 50 };
setState((s) => (s.scrolled === next.scrolled && s.progress === next.progress ? s : next));
};
const onScroll = () => {
if (!frame) frame = requestAnimationFrame(update);
};
update();
window.addEventListener('scroll', onScroll, { passive: true });
return () => {
window.removeEventListener('scroll', onScroll);
cancelAnimationFrame(frame);
};
}, []);
return state;
}
const scrollToHeading = (id: string) => document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
export function ArticlePage() {
const { slug = '' } = useParams();
// key: при переходе на другую статью состояние (оглавление, просмотр фото) создаётся заново
return ;
}
function ArticleView({ slug }: { slug: string }) {
const nav = useNav();
const { data: art, isLoading, error } = useArticle(slug);
const fav = useFavorites();
const theme = useTheme();
const { scrolled, progress } = useReadProgress();
const [tocOpen, setTocOpen] = useState(false);
const [printOpen, setPrintOpen] = useState(false);
const [lightbox, setLightbox] = useState<{ figures: Figure[]; start: number } | null>(null);
const listItem = nav.article(slug);
const section = nav.sectionOf(art ?? listItem);
useEffect(() => {
if (art) pushRecent(art.slug);
}, [art]);
// При переходе на другую статью начинаем чтение сверху
useEffect(() => {
window.scrollTo(0, 0);
}, [slug]);
const onImage = useCallback((start: number, figures: Figure[]) => setLightbox({ figures, start }), []);
const titles = useCallback((s: string) => nav.article(s)?.title, [nav]);
// Закреплённая статья-шпаргалка открывается на своём экране
if (art?.pinned && art.cheat) return ;
const isFav = fav.has(slug);
const title = art?.title ?? listItem?.title ?? '';
const backTo = section ? `/s/${section.slug}` : '/';
const bar = (
);
if (!art) {
const notFound = error instanceof ApiError && error.status === 404;
return (
{section?.name ?? 'Главная'}
{title ?
{title}
: null}
{isLoading ? (
) : notFound ? (
Возможно, её переименовали или сняли с публикации.
) : (
Нет сети, и эта статья ещё не сохранена на устройстве. Откройте её при связи или скачайте раздел заранее.
)}
);
}
const meta = (