feat(админка): спайк Preact+htm — решение P0.5
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
# Admin v2 — решения (P0.5)
|
||||
|
||||
## 2026-11-06 — стек фронта: Preact + htm без сборки
|
||||
|
||||
**Спайк:** `sandbox/admin-spike/` — один экран «таблица клиентов + drawer» на двух
|
||||
реализациях, одни данные, один CSS, CSP `script-src 'self'` (без `unsafe-inline`).
|
||||
|
||||
| Метрика | Vanilla ES-модули | Preact 10.25.4 + htm 3.1.1 |
|
||||
|---|---|---|
|
||||
| gzip (html+js+css+data) | **3 345 Б** | 8 650 Б |
|
||||
| JS+HTML+CSS, строк | 116 | **106** |
|
||||
| первый рендер, медиана 3× | **34,5 мс** | 37,2 мс |
|
||||
| клик по строке → drawer | ок | ок |
|
||||
| CSP-ошибки | 0 | 0 |
|
||||
| сборка | нет | нет |
|
||||
| зависимости | 0 | 2 (MIT / Apache-2.0, вендорены) |
|
||||
|
||||
**Решение: Preact + htm** для экранов v2.
|
||||
|
||||
Почему не vanilla, хотя он легче и на 3 мс быстрее:
|
||||
|
||||
- 8,7 КБ gzip на весь экран — шум на фоне 176 КБ старой админки; 3 мс — в пределах шума;
|
||||
- 106 против 116 строк при одном экране, и разрыв растёт на формах, фильтрах, drawer,
|
||||
ошибках и повторном использовании — там ручной DOM начнёт дублировать состояние;
|
||||
- компонентный слой даёт единый способ рисовать «загрузка/ошибка/пусто/данные» и
|
||||
переиспользовать таблицу/бейджи/карточку;
|
||||
- обе реализации проходят CSP без `unsafe-inline`, клик/drawer проверены Playwright;
|
||||
- сборки нет: ES-модули + вендоренные файлы, импорты абсолютные (`/static/admin2/...`).
|
||||
|
||||
**Когда пересмотреть:** если gzip экрана превысит 20 КБ, первый рендер на целевом
|
||||
1280/390 станет > 50 мс, или Preact начнёт требовать сборку/транспиляцию. Тогда fallback —
|
||||
vanilla ES-модули с шаблонными функциями; решение фиксируется здесь.
|
||||
|
||||
**Что спайк НЕ проверил:** формы, фокус-ловушку drawer, длинные списки (1000+),
|
||||
мобильную раскладку 390, a11y-аудит axe, Safari/Firefox. Это P1.1b и UI-тесты.
|
||||
|
||||
**Вендоринг:** `sandbox/admin-spike/vendor/preact.module.js`, `htm.module.js` + лицензии.
|
||||
В прод — только после проверки версии/лицензий и с фиксированной версией.
|
||||
@@ -11,8 +11,9 @@
|
||||
- P0.0 — design-gate: 6 записей в `docs/DESIGN_LOG.md`.
|
||||
- P0.1 — прод-бэкап `2026-11-06_1632.gz` (2,7 МБ gz / 12 МБ), `integrity_check=ok`, users 24, messages 5397; `SMETA_USER/PASS` заданы (env-вход — реальный); индекс на копии 46 мс. Админка на копии открыта (`/admin` 200, users/stats/overview 200). Осталось: 5 вопросов владельца.
|
||||
- P0.2 — выравнивание сделано; pre-release `feat/topup` проверен: 155 тестов зелёные, отчёт `docs/ADMIN_V2_TOPUP_PRERELEASE.md`; **релиз не начинался** (нужен go/no-go и тест-магазин).
|
||||
- **P0.5 — готово:** спайк в `sandbox/admin-spike/`; Preact+htm: 8,7 КБ gzip, 106 строк, 37,2 мс; vanilla: 3,3 КБ, 116 строк, 34,5 мс; CSP 0 ошибок у обоих; решение — Preact+htm, fallback vanilla. `docs/ADMIN_V2_DECISIONS.md`.
|
||||
- **P1.1a — готово:** `/api/admin/users` — `q`, `status`, `sort/order`, `page/per_page`, `last_seen`; старый вызов без параметров отдаёт прежний список; тесты `tests/test_admin_users_api.py` + limits — 46 passed; ревью Зайкой 3 круга, последний **ACCEPT** (P2 закрыты).
|
||||
- P0.6 — `admin_smoke.py` + 20 тестов + прогон на проде localhost (legacy ok); `install_health_cron.sh` ставит строку 15 мин, тесты 4; cron/деплой — после выката. Code review: 6 кругов `admin_smoke` (последний — без дефектов), 3 круга установщика (P2 — ротация health.log, не блокирует). P0.4 — политика данных (`docs/ADMIN_V2_DATA_POLICY.md`), черновик. P0.3/P0.5 — не начаты.
|
||||
- P0.6 — `admin_smoke.py` + 20 тестов + прогон на проде localhost (legacy ok); `install_health_cron.sh` ставит строку 15 мин, тесты 4; cron/деплой — после выката. Code review: 6 кругов `admin_smoke` (последний — без дефектов), 3 круга установщика (P2 — ротация health.log, не блокирует). P0.4 — политика данных (`docs/ADMIN_V2_DATA_POLICY.md`), черновик. P0.3 — не начат; P0.5 — закрыт.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# P0.5 spike: таблица клиентов + drawer
|
||||
|
||||
Два одинаковых экрана на одних данных: `vanilla.html` (ES-модули) и `preact.html`
|
||||
(Preact 10.25.4 + htm 3.1.1, без сборки, вендорены в `vendor/`).
|
||||
|
||||
Запуск:
|
||||
|
||||
```
|
||||
python3 -m http.server 8123 --directory sandbox/admin-spike
|
||||
# http://127.0.0.1:8123/vanilla.html
|
||||
# http://127.0.0.1:8123/preact.html
|
||||
```
|
||||
|
||||
Замер (Playwright, Chromium из ms-playwright, 3 прогона, медиана):
|
||||
|
||||
```
|
||||
python3 sandbox/admin-spike/measure.py
|
||||
```
|
||||
|
||||
Результат — `results.json`. Проверяется: первый рендер, клик по строке, drawer,
|
||||
CSP-ошибки, gzip-вес, LOC. Данные — 12 синтетических клиентов, `data.json`.
|
||||
@@ -0,0 +1,14 @@
|
||||
[
|
||||
{"email":"anna@example.ru","name":"Анна Петрова","status":"active","last_seen":"2026-11-06T09:12:00+10:00","spent_24h":120,"balance":2400,"access":"полный"},
|
||||
{"email":"bob@example.ru","name":"Борис Ким","status":"trial","last_seen":"2026-11-06T08:40:00+10:00","spent_24h":0,"balance":0,"access":"пробный"},
|
||||
{"email":"vera@example.ru","name":"Вера Соколова","status":"exhausted","last_seen":"2026-11-05T18:05:00+10:00","spent_24h":64,"balance":0,"access":"по счёту"},
|
||||
{"email":"gleb@example.ru","name":"Глеб Орлов","status":"blocked","last_seen":"2026-10-28T12:00:00+10:00","spent_24h":0,"balance":0,"access":"закрыт"},
|
||||
{"email":"dina@example.ru","name":"Дина Волк","status":"active","last_seen":"2026-11-06T07:55:00+10:00","spent_24h":310,"balance":5100,"access":"полный"},
|
||||
{"email":"egor@example.ru","name":"Егор Лес","status":"unverified","last_seen":null,"spent_24h":0,"balance":0,"access":"нет"},
|
||||
{"email":"zhanna@example.ru","name":"Жанна Мир","status":"active","last_seen":"2026-11-04T10:30:00+10:00","spent_24h":18,"balance":900,"access":"полный"},
|
||||
{"email":"ivan@example.ru","name":"Иван Даль","status":"read_only","last_seen":"2026-11-01T14:20:00+10:00","spent_24h":0,"balance":0,"access":"чтение"},
|
||||
{"email":"klara@example.ru","name":"Клара Нокс","status":"active","last_seen":"2026-11-06T09:30:00+10:00","spent_24h":42,"balance":1500,"access":"полный"},
|
||||
{"email":"lev@example.ru","name":"Лев Тень","status":"deleted","last_seen":"2026-10-20T16:00:00+10:00","spent_24h":0,"balance":0,"access":"удалён"},
|
||||
{"email":"marina@example.ru","name":"Марина Свет","status":"active","last_seen":"2026-11-03T11:11:00+10:00","spent_24h":96,"balance":760,"access":"полный"},
|
||||
{"email":"nina@example.ru","name":"Нина Тихая","status":"trial","last_seen":"2026-11-06T06:15:00+10:00","spent_24h":0,"balance":0,"access":"пробный"}
|
||||
]
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Замер спайка: вес gzip, LOC, первый рендер, клик/ drawer, CSP-ошибки.
|
||||
|
||||
Запуск: python3 sandbox/admin-spike/measure.py
|
||||
Пишет results.json рядом; цифры — медиана 3 прогонов.
|
||||
"""
|
||||
import gzip
|
||||
import json
|
||||
import statistics
|
||||
import threading
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
class Quiet(SimpleHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
return
|
||||
|
||||
|
||||
def _chrome():
|
||||
base = Path.home() / "Library" / "Caches" / "ms-playwright"
|
||||
for pat in ("chromium_headless_shell-*/chrome-headless-shell-mac-*/chrome-headless-shell",
|
||||
"chromium-*/chrome-mac*/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"):
|
||||
hits = sorted(base.glob(pat))
|
||||
if hits:
|
||||
return str(hits[-1])
|
||||
raise SystemExit("chromium не найден в ms-playwright")
|
||||
|
||||
|
||||
def _gzip(files):
|
||||
blob = b""
|
||||
for f in files:
|
||||
blob += (ROOT / f).read_bytes() + b"\n"
|
||||
return len(gzip.compress(blob, 9))
|
||||
|
||||
|
||||
def main():
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), partial(Quiet, directory=str(ROOT)))
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
base = f"http://127.0.0.1:{server.server_port}/"
|
||||
out = {"base": base, "runs": {}}
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(executable_path=_chrome(), headless=True)
|
||||
try:
|
||||
for html, js, vendor in (
|
||||
("vanilla.html", "vanilla.js", []),
|
||||
("preact.html", "preact.js", ["vendor/preact.module.js", "vendor/htm.module.js"]),
|
||||
):
|
||||
times, csp_errors = [], []
|
||||
for _ in range(3):
|
||||
page = browser.new_page()
|
||||
console = []
|
||||
page.on("console", lambda m: console.append(m.text) if m.type == "error" else None)
|
||||
page.goto(base + html, wait_until="load")
|
||||
page.wait_for_selector("#rows tr[data-email]", timeout=5000)
|
||||
times.append(page.evaluate("performance.now()"))
|
||||
page.locator("#rows tr[data-email]").first.click()
|
||||
assert page.get_attribute("[data-testid=drawer]", "aria-hidden") == "false"
|
||||
assert page.locator("[data-testid=drawer] h2").inner_text().strip()
|
||||
page.close()
|
||||
csp_errors += [c for c in console if "Content Security Policy" in c]
|
||||
files = [html, js, "styles.css", "data.json"] + vendor
|
||||
loc = sum(len((ROOT / f).read_text(encoding="utf-8").splitlines())
|
||||
for f in (html, js, "styles.css"))
|
||||
out["runs"][html] = {
|
||||
"files": files,
|
||||
"gzip_bytes": _gzip(files),
|
||||
"js_html_css_loc": loc,
|
||||
"first_render_ms_median": round(statistics.median(times), 1),
|
||||
"csp_errors": csp_errors,
|
||||
}
|
||||
finally:
|
||||
browser.close()
|
||||
finally:
|
||||
server.shutdown()
|
||||
(ROOT / "results.json").write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(out, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'">
|
||||
<title>Клиенты — preact+htm spike</title>
|
||||
<link rel="stylesheet" href="./styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="./preact.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,62 @@
|
||||
import { h, render } from './vendor/preact.module.js';
|
||||
import htm from './vendor/htm.module.js';
|
||||
const html = htm.bind(h);
|
||||
let users = [];
|
||||
let q = '';
|
||||
let selected = null;
|
||||
let loading = true;
|
||||
let error = null;
|
||||
|
||||
const labels = { active: 'активен', trial: 'пробный', exhausted: 'исчерпан', blocked: 'заблокирован',
|
||||
unverified: 'не подтверждён', read_only: 'только чтение', deleted: 'удалён' };
|
||||
const fmt = (iso) => iso ? new Date(iso).toLocaleString('ru-RU', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) : '—';
|
||||
const visible = () => users.filter((u) => !q || (u.name + ' ' + u.email).toLowerCase().includes(q.toLowerCase()));
|
||||
|
||||
const Row = ({ u, onPick }) => html`
|
||||
<tr data-email=${u.email} tabindex="0" onClick=${() => onPick(u)} onKeyDown=${(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onPick(u); }
|
||||
}}>
|
||||
<td><div class="row-client"><b>${u.name}</b><small>${u.email}</small></div></td>
|
||||
<td><span class=${'badge ' + u.status}>${labels[u.status] || u.status}</span></td>
|
||||
<td>${fmt(u.last_seen)}</td>
|
||||
<td class="num">${u.spent_24h} ₽</td>
|
||||
<td class="num">${u.balance} ₽</td>
|
||||
<td>${u.access}</td>
|
||||
</tr>`;
|
||||
|
||||
const Drawer = ({ u, onClose }) => html`
|
||||
<aside class=${'drawer' + (u ? ' open' : '')} data-testid="drawer" aria-hidden=${u ? 'false' : 'true'}
|
||||
inert=${u ? null : ''} aria-label="Карточка клиента">
|
||||
<button type="button" onClick=${onClose}>Закрыть</button>
|
||||
<h2>${u ? u.name : ''}</h2>
|
||||
<p>${u ? u.email : ''}</p>
|
||||
${u && html`<dl>
|
||||
<dt>Статус</dt><dd>${labels[u.status] || u.status}</dd>
|
||||
<dt>Был(а)</dt><dd>${fmt(u.last_seen)}</dd>
|
||||
<dt>Потрачено за 24 ч</dt><dd>${u.spent_24h} ₽</dd>
|
||||
<dt>Баланс</dt><dd>${u.balance} ₽</dd>
|
||||
<dt>Доступ</dt><dd>${u.access}</dd>
|
||||
</dl>`}
|
||||
</aside>`;
|
||||
|
||||
const App = () => html`
|
||||
<header><h1>Клиенты</h1><input type="search" placeholder="Поиск по имени или адресу" aria-label="Поиск"
|
||||
value=${q} onInput=${(e) => { q = e.currentTarget.value; draw(); }} /></header>
|
||||
<main><div class="table-wrap"><table>
|
||||
<thead><tr><th>Клиент</th><th>Статус</th><th>Был(а)</th><th>24 ч</th><th>Баланс</th><th>Доступ</th></tr></thead>
|
||||
<tbody id="rows">${loading
|
||||
? html`<tr><td colspan="6" class="empty">Загрузка…</td></tr>`
|
||||
: error
|
||||
? html`<tr><td colspan="6" class="empty" role="alert">Не удалось загрузить: ${error}</td></tr>`
|
||||
: visible().length
|
||||
? visible().map((u) => html`<${Row} key=${u.email} u=${u} onPick=${(x) => { selected = x; draw(); }} />`)
|
||||
: html`<tr><td colspan="6" class="empty">Никого не нашлось</td></tr>`}</tbody>
|
||||
</table></div></main>
|
||||
<${Drawer} u=${selected} onClose=${() => { selected = null; draw(); }} />`;
|
||||
|
||||
function draw() { render(html`<${App} />`, document.querySelector('#app')); }
|
||||
draw(); // сразу видно «Загрузка…», а не пустоту/ложное «никого»
|
||||
fetch('./data.json')
|
||||
.then((r) => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
|
||||
.then((data) => { users = data; loading = false; draw(); })
|
||||
.catch((e) => { console.error(e); error = e.message || 'сеть'; loading = false; draw(); });
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"base": "http://127.0.0.1:52155/",
|
||||
"runs": {
|
||||
"vanilla.html": {
|
||||
"files": [
|
||||
"vanilla.html",
|
||||
"vanilla.js",
|
||||
"styles.css",
|
||||
"data.json"
|
||||
],
|
||||
"gzip_bytes": 3345,
|
||||
"js_html_css_loc": 116,
|
||||
"first_render_ms_median": 34.5,
|
||||
"csp_errors": []
|
||||
},
|
||||
"preact.html": {
|
||||
"files": [
|
||||
"preact.html",
|
||||
"preact.js",
|
||||
"styles.css",
|
||||
"data.json",
|
||||
"vendor/preact.module.js",
|
||||
"vendor/htm.module.js"
|
||||
],
|
||||
"gzip_bytes": 8650,
|
||||
"js_html_css_loc": 106,
|
||||
"first_render_ms_median": 37.2,
|
||||
"csp_errors": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
:root{--bg:#f6f7f9;--card:#fff;--ink:#1d2433;--muted:#667085;--line:#e4e7ec;--accent:#2457d6;--bad:#b42318;--warn:#b54708;--ok:#067647}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
|
||||
header{display:flex;gap:12px;align-items:center;padding:14px 20px;background:var(--card);border-bottom:1px solid var(--line)}
|
||||
h1{font-size:18px;margin:0 12px 0 0}
|
||||
input[type=search]{flex:1;max-width:360px;padding:8px 10px;border:1px solid var(--line);border-radius:8px;font:inherit}
|
||||
main{padding:18px 20px}
|
||||
.table-wrap{overflow:auto;max-height:520px;background:var(--card);border:1px solid var(--line);border-radius:10px}
|
||||
table{border-collapse:separate;border-spacing:0;width:100%;min-width:760px}
|
||||
th,td{padding:9px 10px;border-bottom:1px solid var(--line);text-align:left;white-space:nowrap}
|
||||
th{position:sticky;top:0;background:#f9fafb;font-size:12px;color:var(--muted);z-index:1}
|
||||
th:first-child,td:first-child{position:sticky;left:0;background:var(--card);z-index:2}
|
||||
th:first-child{background:#f9fafb;z-index:3}
|
||||
tbody tr{cursor:pointer}
|
||||
tbody tr:hover td,tbody tr:focus td{background:#f3f6ff}
|
||||
.row-client{display:flex;flex-direction:column;gap:1px;max-width:240px}
|
||||
.row-client small{color:var(--muted);overflow:hidden;text-overflow:ellipsis}
|
||||
.badge{display:inline-block;padding:2px 8px;border-radius:999px;font-size:12px;background:#eef2f6;color:var(--muted)}
|
||||
.badge.active{background:#e7f6ec;color:var(--ok)}.badge.blocked{background:#fde8e7;color:var(--bad)}
|
||||
.badge.exhausted,.badge.trial{background:#fff4e5;color:var(--warn)}
|
||||
.num{font-variant-numeric:tabular-nums}
|
||||
.drawer{position:fixed;inset:0 0 0 auto;width:min(420px,100%);background:var(--card);border-left:1px solid var(--line);transform:translateX(100%);transition:transform .15s ease;padding:18px;box-shadow:-12px 0 30px rgba(16,24,40,.08);z-index:10;overflow:auto}
|
||||
.drawer.open{transform:none}
|
||||
.drawer h2{font-size:16px;margin:0 0 4px}
|
||||
.drawer p{color:var(--muted);margin:0 0 14px}
|
||||
.drawer dl{display:grid;grid-template-columns:1fr auto;gap:8px 12px;margin:0 0 18px}
|
||||
.drawer dt{color:var(--muted)}.drawer dd{margin:0;text-align:right;font-variant-numeric:tabular-nums}
|
||||
button{font:inherit;padding:8px 12px;border:1px solid var(--line);border-radius:8px;background:var(--card);cursor:pointer}
|
||||
button.primary{background:var(--accent);color:#fff;border-color:var(--accent)}
|
||||
.empty{padding:24px;color:var(--muted);text-align:center}
|
||||
@@ -0,0 +1,34 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'">
|
||||
<title>Клиенты — vanilla spike</title>
|
||||
<link rel="stylesheet" href="./styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<header><h1>Клиенты</h1><input id="q" type="search" placeholder="Поиск по имени или адресу" aria-label="Поиск"></header>
|
||||
<main>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Клиент</th><th>Статус</th><th>Был(а)</th><th>24 ч</th><th>Баланс</th><th>Доступ</th></tr></thead>
|
||||
<tbody id="rows"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</main>
|
||||
<aside class="drawer" id="drawer" data-testid="drawer" aria-hidden="true" aria-label="Карточка клиента">
|
||||
<button id="close" type="button">Закрыть</button>
|
||||
<h2 id="drawer-title"></h2>
|
||||
<p id="drawer-email"></p>
|
||||
<dl>
|
||||
<dt>Статус</dt><dd id="d-status"></dd>
|
||||
<dt>Был(а)</dt><dd id="d-seen"></dd>
|
||||
<dt>Потрачено за 24 ч</dt><dd id="d-spent"></dd>
|
||||
<dt>Баланс</dt><dd id="d-balance"></dd>
|
||||
<dt>Доступ</dt><dd id="d-access"></dd>
|
||||
</dl>
|
||||
</aside>
|
||||
<script type="module" src="./vanilla.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,52 @@
|
||||
const rows = document.querySelector('#rows');
|
||||
const drawer = document.querySelector('#drawer');
|
||||
const q = document.querySelector('#q');
|
||||
let users = [];
|
||||
let selected = null;
|
||||
|
||||
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => (
|
||||
{ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]
|
||||
));
|
||||
const labels = { active: 'активен', trial: 'пробный', exhausted: 'исчерпан', blocked: 'заблокирован',
|
||||
unverified: 'не подтверждён', read_only: 'только чтение', deleted: 'удалён' };
|
||||
const fmt = (iso) => iso ? new Date(iso).toLocaleString('ru-RU', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) : '—';
|
||||
const visible = () => users.filter((u) => !q.value || (u.name + ' ' + u.email).toLowerCase().includes(q.value.toLowerCase()));
|
||||
|
||||
function renderRows() {
|
||||
const list = visible();
|
||||
rows.innerHTML = list.length ? list.map((u) => `
|
||||
<tr data-email="${esc(u.email)}" tabindex="0">
|
||||
<td><div class="row-client"><b>${esc(u.name)}</b><small>${esc(u.email)}</small></div></td>
|
||||
<td><span class="badge ${esc(u.status)}">${esc(labels[u.status] || u.status)}</span></td>
|
||||
<td>${esc(fmt(u.last_seen))}</td>
|
||||
<td class="num">${u.spent_24h} ₽</td>
|
||||
<td class="num">${u.balance} ₽</td>
|
||||
<td>${esc(u.access)}</td>
|
||||
</tr>`).join('') : '<tr><td colspan="6" class="empty">Никого не нашлось</td></tr>';
|
||||
}
|
||||
|
||||
function renderDrawer() {
|
||||
const u = selected;
|
||||
drawer.classList.toggle('open', Boolean(u));
|
||||
drawer.setAttribute('aria-hidden', u ? 'false' : 'true');
|
||||
if (!u) return;
|
||||
document.querySelector('#drawer-title').textContent = u.name;
|
||||
document.querySelector('#drawer-email').textContent = u.email;
|
||||
document.querySelector('#d-status').textContent = labels[u.status] || u.status;
|
||||
document.querySelector('#d-seen').textContent = fmt(u.last_seen);
|
||||
document.querySelector('#d-spent').textContent = `${u.spent_24h} ₽`;
|
||||
document.querySelector('#d-balance').textContent = `${u.balance} ₽`;
|
||||
document.querySelector('#d-access').textContent = u.access;
|
||||
}
|
||||
|
||||
function pick(tr) {
|
||||
selected = users.find((u) => u.email === tr.dataset.email) || null;
|
||||
renderDrawer();
|
||||
}
|
||||
|
||||
rows.addEventListener('click', (e) => { const tr = e.target.closest('tr[data-email]'); if (tr) pick(tr); });
|
||||
rows.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { const tr = e.target.closest('tr[data-email]'); if (tr) { e.preventDefault(); pick(tr); } } });
|
||||
q.addEventListener('input', renderRows);
|
||||
document.querySelector('#close').addEventListener('click', () => { selected = null; renderDrawer(); });
|
||||
|
||||
fetch('./data.json').then((r) => r.json()).then((data) => { users = data; renderRows(); });
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2018 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-present Jason Miller
|
||||
|
||||
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.
|
||||
+1
@@ -0,0 +1 @@
|
||||
var n=function(t,s,r,e){var u;s[0]=0;for(var h=1;h<s.length;h++){var p=s[h++],a=s[h]?(s[0]|=p?1:2,r[s[h++]]):s[++h];3===p?e[0]=a:4===p?e[1]=Object.assign(e[1]||{},a):5===p?(e[1]=e[1]||{})[s[++h]]=a:6===p?e[1][s[++h]]+=a+"":p?(u=t.apply(a,n(t,a,r,["",null])),e.push(u),a[0]?s[0]|=2:(s[h-2]=0,s[h]=u)):e.push(a)}return e},t=new Map;export default function(s){var r=t.get(this);return r||(r=new Map,t.set(this,r)),(r=n(this,r.get(s)||(r.set(s,r=function(n){for(var t,s,r=1,e="",u="",h=[0],p=function(n){1===r&&(n||(e=e.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?h.push(0,n,e):3===r&&(n||e)?(h.push(3,n,e),r=2):2===r&&"..."===e&&n?h.push(4,n,0):2===r&&e&&!n?h.push(5,0,!0,e):r>=5&&((e||!n&&5===r)&&(h.push(r,0,e,s),r=6),n&&(h.push(r,n,0,s),r=6)),e=""},a=0;a<n.length;a++){a&&(1===r&&p(),p(a));for(var l=0;l<n[a].length;l++)t=n[a][l],1===r?"<"===t?(p(),h=[h],r=3):e+=t:4===r?"--"===e&&">"===t?(r=1,e=""):e=t+e[0]:u?t===u?u="":e+=t:'"'===t||"'"===t?u=t:">"===t?(p(),r=1):r&&("="===t?(r=5,s=e,e=""):"/"===t&&(r<5||">"===n[a][l+1])?(p(),3===r&&(h=h[0]),r=h,(h=h[0]).push(2,0,r),r=0):" "===t||"\t"===t||"\n"===t||"\r"===t?(p(),r=2):e+=t),3===r&&"!--"===e&&(r=4,h=h[0])}return p(),h}(s)),r),arguments,[])).length>1?r:r[0]}
|
||||
+2
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user