import { useState } from 'react';
import { formatBytes, formatDateTime } from '../lib/format';
import { downloadSection, useLastSynced, useOnline, useSectionOffline } from '../lib/offline';
import type { SectionView } from '../lib/tree';
import { CodeTag } from './ui';
/** Жёлтая полоса сверху, когда сети нет. */
export function OfflineBanner() {
const online = useOnline();
const synced = useLastSynced();
if (online) return null;
return (
Нет сети: показана сохранённая версия
{synced ? `от ${formatDateTime(synced)} · ` : ''}обновится при подключении
);
}
/** Зелёная метка «Офлайн» у статьи, которая есть в кеше. */
export function OfflinePill({ long }: { long?: boolean }) {
return (
{long ? 'Доступно офлайн' : 'Офлайн'}
);
}
function useDownload(section: SectionView) {
const [failed, setFailed] = useState(false);
const start = async () => {
setFailed(false);
setFailed(!(await downloadSection(section)));
};
return { failed, start };
}
/** Строка на экране раздела: «Сохранено для офлайна · 14 МБ · Обновить». */
export function SectionOfflineRow({ section }: { section: SectionView }) {
const state = useSectionOffline(section.id);
const { failed, start } = useDownload(section);
if (state.kind === 'done') {
return (
Сохранено для офлайна · {formatBytes(state.bytes)}
);
}
if (state.kind === 'loading') {
return (
Загрузка {state.pct}%
);
}
return (
);
}
/** Карточка раздела на экране «Офлайн-разделы». */
export function SectionOfflineCard({ section }: { section: SectionView }) {
const state = useSectionOffline(section.id);
const { failed, start } = useDownload(section);
const bytes = section.articles.reduce((n, a) => n + a.bytes, 0);
return (
{section.name}
{formatBytes(state.kind === 'done' ? state.bytes : bytes)}
{state.kind === 'done' ? (
Сохранено · {formatDateTime(state.at)}
) : state.kind === 'loading' ? (
Загрузка {state.pct}%
) : (
)}
);
}