98 lines
5.0 KiB
JavaScript
98 lines
5.0 KiB
JavaScript
import { h, render } from '/static/admin2/vendor/preact.module.js';
|
|
import { useEffect, useRef, useState } from '/static/admin2/vendor/hooks.module.js';
|
|
import htm from '/static/admin2/vendor/htm.module.js';
|
|
import { SECTIONS, sectionFromPath, hrefFor } from '/static/admin2/router.js';
|
|
import { DayPage } from '/static/admin2/pages/day.js';
|
|
import { CustomersPage } from '/static/admin2/pages/customers.js';
|
|
import { MoneyPage } from '/static/admin2/pages/money.js';
|
|
import { WorkPage } from '/static/admin2/pages/work.js';
|
|
import { SystemPage } from '/static/admin2/pages/system.js';
|
|
|
|
const html = htm.bind(h);
|
|
const TITLES = {
|
|
today: ["Мой день", "Что требует внимания сегодня"],
|
|
customers: ["Клиенты", "Кто платит, кто ушёл и кого надо вернуть"],
|
|
money: ["Деньги", "Поступления, поток и обязательства"],
|
|
work: ["Работа", "Очередь, прогоны и сбои"],
|
|
system: ["Система", "Здоровье службы и настройки"],
|
|
};
|
|
const App = () => {
|
|
const [section, setSection] = useState(sectionFromPath(location.pathname));
|
|
const firstRender = useRef(true);
|
|
const [title, subtitle] = TITLES[section]
|
|
|| [SECTIONS.find(([key]) => key === section)?.[1] || 'Раздел', ''];
|
|
|
|
// Назад/вперёд в браузере меняют адрес без клика по меню — забираем тот же переход.
|
|
useEffect(() => {
|
|
const onPop = () => setSection(sectionFromPath(location.pathname));
|
|
window.addEventListener('popstate', onPop);
|
|
return () => window.removeEventListener('popstate', onPop);
|
|
}, []);
|
|
|
|
// Заголовок вкладки и фокус на заголовок раздела — только при переходе, не при
|
|
// первой загрузке: иначе фокус отбирается у адресной строки на пустом месте.
|
|
useEffect(() => {
|
|
document.title = title + ' — Кокпит';
|
|
if (firstRender.current) { firstRender.current = false; return; }
|
|
const h1 = document.querySelector('main h1');
|
|
if (h1) h1.focus();
|
|
window.scrollTo(0, 0);
|
|
}, [section, title]);
|
|
|
|
// Оболочка остаётся, меняется только правая часть: обычный переход перезагружал
|
|
// документ и пересоздавал меню. Средний клик и Ctrl/Cmd/Shift оставляем браузеру —
|
|
// человек вправе открыть раздел в новой вкладке.
|
|
const go = (event, href) => {
|
|
if (event.defaultPrevented || event.button !== 0
|
|
|| event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
event.preventDefault();
|
|
if (location.pathname === href) return;
|
|
history.pushState({}, '', href);
|
|
setSection(sectionFromPath(href));
|
|
};
|
|
|
|
return html`
|
|
<div class="shell">
|
|
<nav class="side" aria-label="Разделы">
|
|
<a class="brand" href=${hrefFor('today')}
|
|
onClick=${(e) => go(e, hrefFor('today'))}>smeta<span>·</span>кокпит</a>
|
|
${SECTIONS.map(([key, label, href]) => html`
|
|
<a key=${key} href=${href} onClick=${(e) => go(e, href)}
|
|
class=${'nav-link' + (key === section ? ' active' : '')}
|
|
aria-current=${key === section ? 'page' : null}>${label}</a>`)}
|
|
</nav>
|
|
<main class="main">
|
|
<header class="top"><div><h1 tabIndex="-1">${title}</h1><p>${subtitle}</p></div></header>
|
|
${section === 'today' ? html`<${DayPage} />`
|
|
: section === 'customers' ? html`<${CustomersPage} />`
|
|
: section === 'money' ? html`<${MoneyPage} />`
|
|
: section === 'work' ? html`<${WorkPage} />`
|
|
: section === 'system' ? html`<${SystemPage} />` : html`
|
|
<section class="card" aria-labelledby="placeholder">
|
|
<h2 id="placeholder">Раздел готовится</h2>
|
|
<p>Данные и действия подключит следующий этап.</p>
|
|
</section>`}
|
|
</main>
|
|
</div>`;
|
|
};
|
|
|
|
render(html`<${App} />`, document.getElementById('app'));
|
|
|
|
// P4.8: ошибки браузера — без PII, не мешают работе страницы.
|
|
function reportClientError(message, stack) {
|
|
if (!localStorage.getItem('token')) return;
|
|
try {
|
|
fetch('/api/client-error', {
|
|
method: 'POST',
|
|
headers: {'Content-Type': 'application/json',
|
|
Authorization: 'Bearer ' + localStorage.getItem('token')},
|
|
body: JSON.stringify({message: String(message).slice(0, 2000),
|
|
stack: String(stack || '').slice(0, 2000),
|
|
path: location.pathname}),
|
|
}).catch(() => {});
|
|
} catch (e) { /* отчёт об ошибке не должен ронять страницу */ }
|
|
}
|
|
window.addEventListener('error', (e) => reportClientError(e.message, e.error && e.error.stack));
|
|
window.addEventListener('unhandledrejection', (e) =>
|
|
reportClientError(e.reason && e.reason.message || e.reason, e.reason && e.reason.stack));
|