feat(админка): переходы между разделами без перезагрузки
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
+42
-7
@@ -1,4 +1,5 @@
|
|||||||
import { h, render } from '/static/admin2/vendor/preact.module.js';
|
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 htm from '/static/admin2/vendor/htm.module.js';
|
||||||
import { SECTIONS, sectionFromPath, hrefFor } from '/static/admin2/router.js';
|
import { SECTIONS, sectionFromPath, hrefFor } from '/static/admin2/router.js';
|
||||||
import { DayPage } from '/static/admin2/pages/day.js';
|
import { DayPage } from '/static/admin2/pages/day.js';
|
||||||
@@ -15,20 +16,53 @@ const TITLES = {
|
|||||||
work: ["Работа", "Очередь, прогоны и сбои"],
|
work: ["Работа", "Очередь, прогоны и сбои"],
|
||||||
system: ["Система", "Здоровье службы и настройки"],
|
system: ["Система", "Здоровье службы и настройки"],
|
||||||
};
|
};
|
||||||
const section = sectionFromPath(location.pathname);
|
const App = () => {
|
||||||
const [title, subtitle] = TITLES[section]
|
const [section, setSection] = useState(sectionFromPath(location.pathname));
|
||||||
|| [SECTIONS.find(([key]) => key === section)?.[1] || 'Раздел', ''];
|
const firstRender = useRef(true);
|
||||||
|
const [title, subtitle] = TITLES[section]
|
||||||
|
|| [SECTIONS.find(([key]) => key === section)?.[1] || 'Раздел', ''];
|
||||||
|
|
||||||
const App = () => html`
|
// Назад/вперёд в браузере меняют адрес без клика по меню — забираем тот же переход.
|
||||||
|
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">
|
<div class="shell">
|
||||||
<nav class="side" aria-label="Разделы">
|
<nav class="side" aria-label="Разделы">
|
||||||
<a class="brand" href=${hrefFor('today')}>smeta<span>·</span>кокпит</a>
|
<a class="brand" href=${hrefFor('today')}
|
||||||
|
onClick=${(e) => go(e, hrefFor('today'))}>smeta<span>·</span>кокпит</a>
|
||||||
${SECTIONS.map(([key, label, href]) => html`
|
${SECTIONS.map(([key, label, href]) => html`
|
||||||
<a key=${key} href=${href} class=${'nav-link' + (key === section ? ' active' : '')}
|
<a key=${key} href=${href} onClick=${(e) => go(e, href)}
|
||||||
|
class=${'nav-link' + (key === section ? ' active' : '')}
|
||||||
aria-current=${key === section ? 'page' : null}>${label}</a>`)}
|
aria-current=${key === section ? 'page' : null}>${label}</a>`)}
|
||||||
</nav>
|
</nav>
|
||||||
<main class="main">
|
<main class="main">
|
||||||
<header class="top"><div><h1>${title}</h1><p>${subtitle}</p></div></header>
|
<header class="top"><div><h1 tabIndex="-1">${title}</h1><p>${subtitle}</p></div></header>
|
||||||
${section === 'today' ? html`<${DayPage} />`
|
${section === 'today' ? html`<${DayPage} />`
|
||||||
: section === 'customers' ? html`<${CustomersPage} />`
|
: section === 'customers' ? html`<${CustomersPage} />`
|
||||||
: section === 'money' ? html`<${MoneyPage} />`
|
: section === 'money' ? html`<${MoneyPage} />`
|
||||||
@@ -40,6 +74,7 @@ const App = () => html`
|
|||||||
</section>`}
|
</section>`}
|
||||||
</main>
|
</main>
|
||||||
</div>`;
|
</div>`;
|
||||||
|
};
|
||||||
|
|
||||||
render(html`<${App} />`, document.getElementById('app'));
|
render(html`<${App} />`, document.getElementById('app'));
|
||||||
|
|
||||||
|
|||||||
@@ -102,6 +102,28 @@ def test_sections_render(browser, site, path, title):
|
|||||||
page.close()
|
page.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_nav_keeps_shell_without_reload(browser, site):
|
||||||
|
"""Переключение раздела не перезагружает страницу и не пересоздаёт левую панель.
|
||||||
|
|
||||||
|
Метка на панели и на window живёт только в текущем документе: после настоящей
|
||||||
|
загрузки её нет. Мутация: вернуть обычные ссылки без перехвата — проверка падает."""
|
||||||
|
page = browser.new_page(viewport={"width": 1280, "height": 800})
|
||||||
|
page.add_init_script("localStorage.setItem('token','t')")
|
||||||
|
page.goto(site + "/admin/v2")
|
||||||
|
page.wait_for_selector("h1")
|
||||||
|
page.evaluate("window.__noReload = true; document.querySelector('nav').setAttribute('data-marker','keep')")
|
||||||
|
page.click("a[href='/admin/v2/customers']")
|
||||||
|
page.wait_for_function("document.querySelector('h1')?.textContent === 'Клиенты'")
|
||||||
|
assert page.evaluate("location.pathname") == "/admin/v2/customers"
|
||||||
|
assert page.evaluate("window.__noReload === true")
|
||||||
|
assert page.evaluate("document.querySelector('nav').getAttribute('data-marker')") == "keep"
|
||||||
|
page.go_back()
|
||||||
|
page.wait_for_function("document.querySelector('h1')?.textContent === 'Мой день'")
|
||||||
|
assert page.evaluate("location.pathname") == "/admin/v2"
|
||||||
|
assert page.evaluate("window.__noReload === true")
|
||||||
|
page.close()
|
||||||
|
|
||||||
|
|
||||||
def test_money_charts_stay_inside_card(browser, site):
|
def test_money_charts_stay_inside_card(browser, site):
|
||||||
"""Один закрытый месяц не должен растягивать графики на несколько экранов.
|
"""Один закрытый месяц не должен растягивать графики на несколько экранов.
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user