Panel redesign, per-server I1 masking, node minimum version 0.5.0, installer output
ci / check (push) Successful in 23m54s
ci / check (push) Successful in 23m54s
- UI: settings tab with sections (server, API keys, Prometheus, audit, migrate, about); server settings moved there; master keys table rework (menu, chips, version, compact phone cards); three-state node version chip - I1: random per-server template (DNS / QUIC Initial / STUN) kept in users.db, GET/POST /api/masking, change from the master keys banner - Hub rejects nodes older than 0.5.0 (close 4026), /ui/nodes reports outdated - install.sh: spinner for long commands (full output in the log), step progress bar, cards; installs older than 0.5.0 require a full reinstall with data reset - Bump to Beta 0.5.0
This commit is contained in:
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"id": "apikeys",
|
||||
"label": "API-ключи",
|
||||
"icon": "key",
|
||||
"group": "main",
|
||||
"order": 2
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"id": "audit",
|
||||
"label": "Аудит",
|
||||
"icon": "shield",
|
||||
"group": "server",
|
||||
"order": 1.8,
|
||||
"chrome": {
|
||||
"serverBar": false,
|
||||
"restart": false
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
// Автообнаружение вкладок. Каждая вкладка — самодостаточная папка tabs/<name>/:
|
||||
// index.tsx — компонент + логика
|
||||
// <name>.css — стили вкладки (импортит сам компонент)
|
||||
// metadata.json — { id, label, icon, group?, order?, chrome? } (манифест: описание, группа меню, порядок)
|
||||
// metadata.json — { id, label, icon, group?, order?, requires?, chrome? } (манифест: описание, группа меню, порядок)
|
||||
// Реестр сам находит все папки через import.meta.glob и собирает «живые» части
|
||||
// (Page-компонент, Icon по имени из ICONS) к метадате. Добавить вкладку = просто
|
||||
// создать папку с index.tsx и metadata.json — этот файл трогать НЕ нужно.
|
||||
@@ -35,6 +35,7 @@ export interface TabMeta {
|
||||
icon: string; // имя иконки → ICONS
|
||||
group: TabGroupId; // группа меню; без поля — 'main'
|
||||
order?: number; // порядок внутри группы (по возрастанию; без него — 0)
|
||||
requires?: 'prometheus'; // вкладка в меню только при условии: 'prometheus' — встроенный Prometheus установлен
|
||||
chrome?: TabChrome;
|
||||
}
|
||||
|
||||
@@ -66,6 +67,9 @@ function toMeta(name: string, raw: unknown): TabMeta {
|
||||
if (m.chrome !== undefined && (typeof m.chrome !== 'object' || m.chrome === null)) {
|
||||
throw new Error(`tabs/${name}/metadata.json: "chrome" должно быть объектом`);
|
||||
}
|
||||
if (m.requires !== undefined && m.requires !== 'prometheus') {
|
||||
throw new Error(`tabs/${name}/metadata.json: "requires" может быть только "prometheus"`);
|
||||
}
|
||||
const group = (m.group ?? 'main') as string;
|
||||
if (!TAB_GROUPS.some(g => g.id === group)) {
|
||||
throw new Error(`tabs/${name}/metadata.json: "group" должно быть одним из: ${TAB_GROUPS.map(g => g.id).join(', ')}`);
|
||||
@@ -76,6 +80,7 @@ function toMeta(name: string, raw: unknown): TabMeta {
|
||||
icon: str('icon'),
|
||||
group: group as TabGroupId,
|
||||
order: m.order as number | undefined,
|
||||
requires: m.requires as 'prometheus' | undefined,
|
||||
chrome: m.chrome as TabChrome | undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -109,12 +109,12 @@ export default function BulkServersModal({ token, nodes, keys, defaults, onClose
|
||||
{preview?.hidden.map(h => (
|
||||
<p className="mk-notice" key={h.id}>
|
||||
Ключ API «{h.label}» перестанет видеть {h.keys} мастер-ключ(ей): у них появится сервер вне его области.
|
||||
Расширьте его область на вкладке «API-ключи», если он ими управляет.
|
||||
Расширьте его область в «Настройках», на вкладке «API-ключи», если он ими управляет.
|
||||
</p>
|
||||
))}
|
||||
{error && <p className="login-error">{error}</p>}
|
||||
<div className="node-modal-actions">
|
||||
<button className="btn btn--outline" onClick={onClose}>Отмена</button>
|
||||
<button className="btn btn--text" onClick={onClose}>Отмена</button>
|
||||
<button className="btn btn--primary" disabled={busy || nothing || !!error} onClick={apply}>
|
||||
{busy ? 'Применяем…' : 'Применить'}
|
||||
</button>
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// This source code is licensed under the MIT license found in the
|
||||
// LICENSE file in the root directory of this source tree.
|
||||
import { Fragment, useState, useEffect, useCallback, useMemo, useRef } from 'react';
|
||||
import QRCode from 'qrcode';
|
||||
import { apiFetch, copyText, bytes, timeAgo, getServerId, type NodeInfo, type PageProps, type Priority } from '../../lib/shared';
|
||||
import { IcoPlus, IcoTrash, IcoCopy, IcoQR, IcoKey, IcoRefresh, IcoSettings, IcoGlobe } from '../../components/icons';
|
||||
import { apiFetch, copyText, bytes, timeAgo, getServerId, cmpVersion, type NodeInfo, type PageProps, type Priority } from '../../lib/shared';
|
||||
import { qrDataUrl } from '../../lib/qr';
|
||||
import { IcoPlus, IcoTrash, IcoCopy, IcoQR, IcoKey, IcoRefresh, IcoSettings, IcoMore } from '../../components/icons';
|
||||
import ServerPicker, { serverName } from '../../components/ServerPicker';
|
||||
import PriorityChip from '../../components/PriorityChip';
|
||||
import TorrentChip from '../../components/TorrentChip';
|
||||
@@ -23,18 +23,12 @@ interface Device {
|
||||
ips?: { server_id: number; ip: string }[]; // IP на каждом сервере ключа (старая панель не отдаёт)
|
||||
}
|
||||
|
||||
// Устройство ещё не на всех серверах ключа (нода не в сети при регистрации или смене ключа) —
|
||||
// панель догонит, когда нода появится.
|
||||
const syncLabel = (d: Device): string =>
|
||||
d.servers_ok < d.servers_total ? ` · на ${d.servers_ok} из ${d.servers_total} серверов` : '';
|
||||
|
||||
// Платформа и версия клиента: «macOS-0.6.5»; без версии — просто платформа.
|
||||
const platformLabel = (d: Device): string =>
|
||||
d.platform ? (d.version ? `${d.platform}-${d.version}` : d.platform) : '—';
|
||||
|
||||
const errText = (e: any): string => e?.response?.data?.error ?? 'Ошибка запроса';
|
||||
|
||||
// Статус — как у пользователей: «онлайн», иначе сколько прошло с последнего handshake.
|
||||
// Приоритет показываем, только когда он не обычный: «обычный» в каждой строке — шум
|
||||
const bgOnly = (p?: Priority) => p === 'background' ? p : undefined;
|
||||
|
||||
const statusChip = (d: Device) => (
|
||||
<span className={`chip chip--${d.online ? 'online' : 'offline'}`}>
|
||||
<span className="chip-dot" />
|
||||
@@ -55,11 +49,18 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
const [enabled, setEnabled] = useState(true);
|
||||
const [tls, setTls] = useState(false);
|
||||
const [nodes, setNodes] = useState<NodeInfo[]>([]); // серверы, которые можно включить в ключ
|
||||
// Маскировка первого пакета (I1) сервера из шапки: false — сервер её не умеет (старый awg-ctrl) или недоступен
|
||||
const [masking, setMasking] = useState<'ready' | 'busy' | false>(false);
|
||||
const [label, setLabel] = useState('');
|
||||
const [limit, setLimit] = useState('3');
|
||||
const [devs, setDevs] = useState<Record<number, Device[]>>({});
|
||||
const [folded, setFolded] = useState<Set<number>>(new Set()); // свёрнутые узлы
|
||||
const [tools, setTools] = useState<number | null>(null); // узел с открытыми настройками
|
||||
// Меню «⋮» ключа или устройства. position: fixed по кнопке: .table-card прокручивается вбок
|
||||
// и обрезал бы меню у нижних строк. full — в меню ключа и «Скопировать ссылку» (в таблице;
|
||||
// в карточке на телефоне ссылка — отдельной кнопкой).
|
||||
const [menu, setMenu] = useState<{ kind: 'key' | 'device'; id: number; full: boolean; top: number; right: number; up: boolean } | null>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const [limitEdit, setLimitEdit] = useState('');
|
||||
const [failed, setFailed] = useState<Set<number>>(new Set()); // ключи, чьи устройства не загрузились
|
||||
const [down, setDown] = useState<Record<number, number[]>>({}); // серверы ключа, не ответившие на статистику
|
||||
@@ -121,6 +122,21 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
}, [label, limit, nodes, defaults, token, act]);
|
||||
const live = useMemo(() => keys.filter(k => !k.deleting), [keys]);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
apiFetch('GET', '/api/masking', token).then(() => { if (alive) setMasking('ready'); }).catch(() => {});
|
||||
return () => { alive = false; };
|
||||
}, [token]);
|
||||
|
||||
// Новый случайный I1 на сервере из шапки. Интерфейс не трогается: I1 нужен только клиентам,
|
||||
// sen:// подхватят его со следующим обновлением профиля (≤ 60 с), выданные vpn:// остаются со старым.
|
||||
const regenMasking = async () => {
|
||||
setMasking('busy');
|
||||
try { await apiFetch('POST', '/api/masking', token); showMsg('Маскировка сменена'); }
|
||||
catch (e: any) { showMsg(e?.response?.data?.error ?? 'Не удалось сменить маскировку'); }
|
||||
finally { setMasking('ready'); }
|
||||
};
|
||||
|
||||
const serverNames = useCallback((ids: number[]) => ids.map(id => serverName(nodes, id)).join(', '), [nodes]);
|
||||
|
||||
const remove = useCallback(async (k: MasterKey) => {
|
||||
@@ -141,8 +157,7 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
const showQR = useCallback(async (k: MasterKey) => {
|
||||
try {
|
||||
const { link, tls: t } = await fetchLink(k);
|
||||
const dataUrl = await QRCode.toDataURL(link, { width: 560, margin: 2, errorCorrectionLevel: 'H' });
|
||||
setModal({ label: k.label, link, tls: t, dataUrl });
|
||||
setModal({ label: k.label, link, tls: t, dataUrl: qrDataUrl(link, 'H') });
|
||||
} catch (e) { showMsg(errText(e)); }
|
||||
}, [fetchLink, showMsg]);
|
||||
|
||||
@@ -195,12 +210,48 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
</span>
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!menu) return;
|
||||
menuRef.current?.querySelector<HTMLButtonElement>('button')?.focus();
|
||||
const close = () => setMenu(null);
|
||||
const down = (e: MouseEvent) => { if (!menuRef.current?.contains(e.target as Node)) close(); };
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') { close(); document.querySelector<HTMLButtonElement>(`[data-menu-for="${menu.kind}-${menu.id}"]`)?.focus(); return; }
|
||||
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
|
||||
e.preventDefault();
|
||||
const items = [...(menuRef.current?.querySelectorAll<HTMLButtonElement>('button') ?? [])];
|
||||
const i = items.indexOf(document.activeElement as HTMLButtonElement);
|
||||
items[(i + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length]?.focus();
|
||||
};
|
||||
document.addEventListener('mousedown', down);
|
||||
document.addEventListener('keydown', key);
|
||||
window.addEventListener('scroll', close, true);
|
||||
window.addEventListener('resize', close);
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', down);
|
||||
document.removeEventListener('keydown', key);
|
||||
window.removeEventListener('scroll', close, true);
|
||||
window.removeEventListener('resize', close);
|
||||
};
|
||||
}, [menu]);
|
||||
|
||||
const openMenu = (kind: 'key' | 'device', id: number, el: HTMLElement, full = false) => {
|
||||
if (menu?.kind === kind && menu.id === id) return setMenu(null);
|
||||
const r = el.getBoundingClientRect();
|
||||
const up = r.bottom + 160 > window.innerHeight; // у нижнего края — вверх от кнопки
|
||||
setMenu({ kind, id, full, top: up ? r.top - 4 : r.bottom + 4, right: window.innerWidth - r.right, up });
|
||||
};
|
||||
const moreButton = (kind: 'key' | 'device', id: number, label: string, full = false) => (
|
||||
<button className="btn-icon mk-more" aria-label={label} aria-haspopup="menu" aria-expanded={menu?.kind === kind && menu.id === id}
|
||||
data-menu-for={`${kind}-${id}`} onClick={e => openMenu(kind, id, e.currentTarget, full)}><IcoMore /></button>
|
||||
);
|
||||
|
||||
// В таблице — QR и «⋮» (остальное в меню), чтобы колонка действий всегда помещалась.
|
||||
// Подсказки — .tip-wrap, не title: нативная появляется с задержкой и бесполезна на тач-экране.
|
||||
const actions = (k: MasterKey) => (
|
||||
<div className="actions">
|
||||
<button className="btn-icon" title="QR-код" aria-label="QR-код" onClick={() => showQR(k)}><IcoQR /></button>
|
||||
<button className="btn-icon" title="Скопировать ссылку" aria-label="Скопировать ссылку" onClick={() => copyLink(k)}><IcoCopy /></button>
|
||||
<button className="btn-icon" title="Настройки мастер-ключа" aria-label="Настройки мастер-ключа" aria-expanded={tools === k.id} onClick={() => openTools(k)}><IcoSettings /></button>
|
||||
<button className="btn-icon btn-icon--danger" title="Удалить мастер-ключ" aria-label="Удалить мастер-ключ" onClick={() => remove(k)}><IcoTrash /></button>
|
||||
<span className="tip-wrap tip-wrap--end" data-tip="QR-код"><button className="btn-icon" aria-label="QR-код" onClick={() => showQR(k)}><IcoQR /></button></span>
|
||||
{moreButton('key', k.id, `Ещё: ${k.label}`, true)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -275,7 +326,7 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
|
||||
// Полоска занятых слотов: числа по краям внутри; цвет по заполнению.
|
||||
const meter = (k: MasterKey, n: number) => (
|
||||
<div className={`mk-meter${n >= k.device_limit ? ' mk-meter--full' : n * 3 >= k.device_limit * 2 ? ' mk-meter--warn' : ''}`}
|
||||
<div className={`mk-meter${n >= k.device_limit ? ' mk-meter--full' : ''}`}
|
||||
role="progressbar" aria-label="Устройства" aria-valuemin={0}
|
||||
aria-valuemax={k.device_limit} aria-valuenow={n}
|
||||
title={`Устройств: ${n} из ${k.device_limit}`}>
|
||||
@@ -288,22 +339,35 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
</div>
|
||||
);
|
||||
|
||||
const newPsk = async (d: Device) => {
|
||||
try {
|
||||
const r = await apiFetch('POST', `/ui/devices/${d.id}/psk`, token);
|
||||
showMsg(r.pending ? `PSK обновлён; ещё на ${r.pending} — когда сервер будет на связи` : 'PSK обновлён');
|
||||
await load();
|
||||
} catch (e) { showMsg(errText(e)); }
|
||||
};
|
||||
const revoke = (d: Device) => {
|
||||
if (confirm('Отозвать устройство «' + (d.device_name || d.id) + '»?'))
|
||||
act(() => apiFetch('DELETE', `/ui/devices/${d.id}`, token), 'Устройство отозвано');
|
||||
};
|
||||
|
||||
const deviceActions = (d: Device) => (
|
||||
<div className="actions">
|
||||
<button className="btn-icon" title="Новый PSK" aria-label="Новый PSK" onClick={async () => {
|
||||
try {
|
||||
const r = await apiFetch('POST', `/ui/devices/${d.id}/psk`, token);
|
||||
showMsg(r.pending ? `PSK обновлён; ещё на ${r.pending} — когда сервер будет на связи` : 'PSK обновлён');
|
||||
await load();
|
||||
} catch (e) { showMsg(errText(e)); }
|
||||
}}><IcoRefresh /></button>
|
||||
<button className="btn-icon btn-icon--danger" title="Отозвать устройство" aria-label="Отозвать устройство" onClick={() => {
|
||||
if (confirm('Отозвать устройство «' + (d.device_name || d.id) + '»?'))
|
||||
act(() => apiFetch('DELETE', `/ui/devices/${d.id}`, token), 'Устройство отозвано');
|
||||
}}><IcoTrash /></button>
|
||||
<span className="tip-wrap tip-wrap--end" data-tip="Новый PSK"><button className="btn-icon" aria-label="Новый PSK" onClick={() => newPsk(d)}><IcoRefresh /></button></span>
|
||||
<span className="tip-wrap tip-wrap--end" data-tip="Отозвать устройство"><button className="btn-icon btn-icon--danger" aria-label="Отозвать устройство" onClick={() => revoke(d)}><IcoTrash /></button></span>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Короткий ID устройства: полностью — в подсказке, по клику копируется
|
||||
const deviceId = (d: Device) => (
|
||||
<span className="tip-wrap tip-wrap--start" data-tip={`ID устройства ${d.device_id} · нажми, чтобы скопировать`}>
|
||||
<button className="copy-id" aria-label={`Скопировать ID устройства ${d.device_id}`}
|
||||
onClick={() => copyText(d.device_id).then(() => showMsg('ID устройства скопирован'), () => showMsg('Не удалось скопировать'))}>
|
||||
{d.device_id.slice(0, 8)}…
|
||||
</button>
|
||||
</span>
|
||||
);
|
||||
|
||||
// Метка ключа и под ней UUID — коротко, чтобы не раздувать колонку «Имя». Полностью — в подсказке,
|
||||
// по клику копируется.
|
||||
const nameCell = (k: MasterKey) => (
|
||||
@@ -325,72 +389,146 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
return d?.length ? <span className="mk-flag" title="Онлайн и трафик с этих серверов не получены"> · нет связи: {serverNames(d)}</span> : null;
|
||||
};
|
||||
|
||||
// Сводка по устройствам ключа в его строке — видна и у свёрнутого ключа.
|
||||
const summary = (list: Device[]) => {
|
||||
if (!list.length) return <><td></td><td></td><td colSpan={2}></td><td></td><td></td></>;
|
||||
// Серверы ключа, куда ещё не добавлено устройство: был не в сети, когда оно подключалось или меняло
|
||||
// ключ; панель добавит его сама, когда сервер появится (reconcile). Без ips (старая панель) — неизвестно.
|
||||
const missingOn = (k: MasterKey, d: Device) => d.ips ? k.servers.filter(s => !d.ips!.some(x => x.server_id === s)) : [];
|
||||
// «из 3 серверов», «из 21 сервера»
|
||||
const ofServers = (n: number) => `${n} ${n % 10 === 1 && n % 100 !== 11 ? 'сервера' : 'серверов'}`;
|
||||
const syncFlag = (k: MasterKey, d: Device) => {
|
||||
const miss = missingOn(k, d);
|
||||
if (miss.length) return `${k.servers.length - miss.length} из ${ofServers(k.servers.length)}`;
|
||||
return d.servers_ok < d.servers_total ? `${d.servers_ok} из ${ofServers(d.servers_total)}` : '';
|
||||
};
|
||||
const syncTip = (k: MasterKey, d: Device) => {
|
||||
const miss = missingOn(k, d);
|
||||
return miss.length ? `Нет на ${miss.map(s => serverName(nodes, s)).join(', ')} — добавится само, когда сервер будет на связи`
|
||||
: 'Не на всех серверах ключа — добавится само, когда они будут на связи';
|
||||
};
|
||||
|
||||
// Серверы ключа — в его строке под колонками IP и «Платформа»: «все серверы» (у ключа с одним
|
||||
// сервером — его имя) светло-зелёным или «2 из 3 серверов» тёплым, если на каком-то ещё нет всех
|
||||
// устройств ключа.
|
||||
// Имена — в подсказке.
|
||||
const keyServers = (k: MasterKey, list: Device[]) => {
|
||||
const behind = (s: number) => list.some(d => missingOn(k, d).includes(s));
|
||||
const late = k.servers.filter(behind);
|
||||
const ready = k.servers.filter(s => !behind(s));
|
||||
const names = (ids: number[]) => ids.map(s => serverName(nodes, s)).join(', ');
|
||||
const text = late.length ? `${ready.length} из ${ofServers(k.servers.length)}`
|
||||
: k.servers.length === 1 ? serverName(nodes, k.servers[0]) : 'все серверы';
|
||||
const tip = late.length ? `Есть: ${names(ready) || 'нигде'}. Нет: ${names(late)} — добавятся сами, когда сервер будет на связи`
|
||||
: k.servers.length > 1 ? names(k.servers) : null;
|
||||
const chip = <span className={`chip ${late.length ? 'chip--warm' : 'chip--online'} mk-srv`}>{text}</span>; // всё на месте — светло-зелёный
|
||||
return tip ? <span className="tip-wrap tip-wrap--end" data-tip={tip}>{chip}</span> : chip;
|
||||
};
|
||||
|
||||
// Статус ключа по его устройствам: онлайн / когда были / «нет устройств», плюс фоновый приоритет и торренты
|
||||
const keyStatus = (list: Device[], empty: boolean) => {
|
||||
if (!list.length) return empty ? <span className="mk-flag">нет устройств</span> : null;
|
||||
const on = list.filter(d => d.online).length;
|
||||
const last = Math.max(...list.map(d => d.lastHandshake || 0));
|
||||
const torrent = list.some(d => d.torrent);
|
||||
const prio = list.some(d => d.priority === 'background') ? 'background' : list.find(d => d.priority)?.priority;
|
||||
const prio = bgOnly(list.some(d => d.priority === 'background') ? 'background' : undefined);
|
||||
return (
|
||||
<>
|
||||
<td>
|
||||
<span className={`chip chip--${on ? 'online' : 'offline'}`}>
|
||||
<span className="chip-dot" />
|
||||
{on ? `онлайн: ${on} из ${list.length}` : last ? timeAgo(last) + ' назад' : 'никогда'}
|
||||
</span>
|
||||
</td>
|
||||
<td><span className="user-chips"><PriorityChip priority={prio} torrent={torrent} /><TorrentChip torrent={torrent} /></span></td>
|
||||
<td colSpan={2}></td>
|
||||
<span className={`chip chip--${on ? 'online' : 'offline'}`}>
|
||||
<span className="chip-dot" />
|
||||
{on ? `онлайн: ${on} из ${list.length}` : last ? timeAgo(last) + ' назад' : 'никогда'}
|
||||
</span>
|
||||
<PriorityChip priority={prio} torrent={torrent} /><TorrentChip torrent={torrent} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Сводка по устройствам ключа в его строке — видна и у свёрнутого ключа.
|
||||
const summary = (k: MasterKey, list: Device[], empty: boolean) => {
|
||||
if (!list.length) return <><td>{keyStatus(list, empty)}</td><td colSpan={2}>{keyServers(k, list)}</td><td></td><td></td></>;
|
||||
return (
|
||||
<>
|
||||
<td><span className="user-chips">{keyStatus(list, empty)}</span></td>
|
||||
<td colSpan={2}>{keyServers(k, list)}</td>
|
||||
<td>{bytes(list.reduce((a, d) => a + d.rx, 0))}</td>
|
||||
<td>{bytes(list.reduce((a, d) => a + d.tx, 0))}</td>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Адрес с другого сервера подписан его именем; подсказка со всеми адресами — когда их больше одного.
|
||||
// Один адрес — выбранного в шапке сервера, остальные — «+N» и подсказка со всеми. Адрес с другого
|
||||
// сервера подписан его именем строкой ниже, иначе его примут за адрес выбранного.
|
||||
const ipCell = (d: Device) => {
|
||||
const all = d.ips ?? [];
|
||||
const { ip, serverId, other } = ipPick(d);
|
||||
const text = <code className="mk-ip">{ip}{other && serverId !== undefined ? ` · ${serverName(nodes, serverId)}` : ''}</code>;
|
||||
const body = (
|
||||
<span className="name-stack">
|
||||
<span className="mk-ip-line">
|
||||
<code className="mk-ip">{ip}</code>
|
||||
{all.length > 1 && <span className="mk-ip-more">+{all.length - 1}</span>}
|
||||
</span>
|
||||
{other && serverId !== undefined && <span className="mk-sub">{serverName(nodes, serverId)}</span>}
|
||||
</span>
|
||||
);
|
||||
return all.length > 1
|
||||
? <span className="tip-wrap" data-tip={all.map(x => `${serverName(nodes, x.server_id)}: ${x.ip}`).join(' · ')}>{text}</span>
|
||||
: text;
|
||||
? <span className="tip-wrap" data-tip={all.map(x => `${serverName(nodes, x.server_id)}: ${x.ip}`).join(' · ')}>{body}</span>
|
||||
: body;
|
||||
};
|
||||
|
||||
const caret = (k: MasterKey) => (
|
||||
// Самая новая версия SenAWG среди устройств панели: кто отстал — тёплой плашкой, как ноды в меню серверов
|
||||
const newest = useMemo(() => Object.values(devs).flat().map(d => d.version).filter(Boolean)
|
||||
.reduce<string | null>((a, v) => !a || cmpVersion(v, a) > 0 ? v : a, null), [devs]);
|
||||
const versionTag = (d: Device, tip: 'start' | 'end') => {
|
||||
if (!d.version) return null;
|
||||
const old = !!newest && cmpVersion(d.version, newest) < 0;
|
||||
return old
|
||||
? <span className={`tip-wrap tip-wrap--${tip}`} data-tip={`Есть новее: ${newest} — обнови SenAWG на устройстве`}><span className="chip chip--warm mk-ver">{d.version}</span></span>
|
||||
: <span className="mk-sub">{d.version}</span>;
|
||||
};
|
||||
const platformCell = (d: Device) => (
|
||||
<span className="name-stack">
|
||||
{d.platform || '—'}
|
||||
{versionTag(d, 'end')}
|
||||
</span>
|
||||
);
|
||||
|
||||
// Раскрывать нечего — вместо стрелки пустое место той же ширины, имена остаются в одну линию
|
||||
const caret = (k: MasterKey, n: number) => n === 0 ? <span className="mk-caret-gap" aria-hidden="true" /> : (
|
||||
<button className={`mk-caret${folded.has(k.id) ? ' mk-caret--folded' : ''}`}
|
||||
aria-label={folded.has(k.id) ? 'Развернуть' : 'Свернуть'} aria-expanded={!folded.has(k.id)}
|
||||
onClick={() => fold(k.id)}>▾</button>
|
||||
);
|
||||
|
||||
const deviceNode = (k: MasterKey, d: Device) => (
|
||||
<li className="mk-node mk-node--device" key={d.id}>
|
||||
<div className="mk-device">
|
||||
<div className="mk-device-main">
|
||||
<span className="mk-device-title">
|
||||
<span className="mk-device-name">{d.device_name || 'Устройство'}</span>
|
||||
<code className="mk-device-id" title={`ID устройства: ${d.device_id}`}>{d.device_id}</code>
|
||||
// Телефон: устройство — строка списка в карточке ключа, а не карточка в карточке. Имя, статус и «⋮»;
|
||||
// ниже мелко — платформа, версия, IP; трафик, приоритет и то, на скольких серверах оно есть.
|
||||
const deviceRow = (k: MasterKey, d: Device) => {
|
||||
const all = d.ips ?? [];
|
||||
const { ip, serverId, other } = ipPick(d);
|
||||
return (
|
||||
<li className="mk-dev" key={d.id}>
|
||||
<div className="mk-dev-head">
|
||||
<span className="name-stack mk-dev-title">
|
||||
<span className="mk-dev-name">{d.device_name || 'Устройство'}</span>
|
||||
{deviceId(d)}
|
||||
</span>
|
||||
<span className="mk-device-sub">{platformLabel(d)}
|
||||
{d.rekey_requested ? ' · ждёт смены ключа' : ''}{syncLabel(d)}</span>
|
||||
{statusChip(d)}
|
||||
{moreButton('device', d.id, `Ещё: ${d.device_name || 'устройство'}`)}
|
||||
</div>
|
||||
{statusChip(d)}
|
||||
{/* как строка IP в карточке пользователя: адрес и чипы приоритета/торрентов */}
|
||||
<div className="mk-device-ip">
|
||||
<IcoGlobe />
|
||||
{ipCell(d)}
|
||||
<PriorityChip priority={d.priority} torrent={d.torrent} />
|
||||
<div className="mk-dev-meta">
|
||||
<span>{d.platform || '—'}</span>
|
||||
{versionTag(d, 'start')}
|
||||
<span aria-hidden="true">·</span>
|
||||
<code className="mk-ip">{ip}</code>
|
||||
{all.length > 1 && <span className="mk-ip-more" aria-label={all.map(x => `${serverName(nodes, x.server_id)}: ${x.ip}`).join(', ')}>+{all.length - 1}</span>}
|
||||
{other && serverId !== undefined && <span>{serverName(nodes, serverId)}</span>}
|
||||
</div>
|
||||
<div className="mk-dev-meta">
|
||||
<span className="mk-dev-traffic">↓ {bytes(d.rx)} ↑ {bytes(d.tx)}</span>
|
||||
<PriorityChip priority={bgOnly(d.priority)} torrent={d.torrent} />
|
||||
<TorrentChip torrent={d.torrent} />
|
||||
{syncFlag(k, d) && <span>{syncFlag(k, d)}</span>}
|
||||
{d.rekey_requested && <span>ждёт смены ключа</span>}
|
||||
</div>
|
||||
<div className="mk-device-traffic">
|
||||
<span className="mk-metric"><i className="mk-metric-name" data-sfx=" rx">↓</i><b>{bytes(d.rx)}</b></span>
|
||||
<span className="mk-metric"><i className="mk-metric-name" data-sfx=" tx">↑</i><b>{bytes(d.tx)}</b></span>
|
||||
</div>
|
||||
{deviceActions(d)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -401,6 +539,19 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
<p className="mk-notice">Подписка работает без TLS: ответы подписаны, но secret ссылки и конфиг видны в сети.</p>
|
||||
)}
|
||||
|
||||
{masking && (
|
||||
<div className="mk-warn" role="note">
|
||||
<span className="mk-warn-text">
|
||||
<b>Маскировка первого пакета · {serverName(nodes, getServerId() ?? 0)}</b>
|
||||
Перед подключением клиент шлёт пакет, похожий на обычный трафик. Новый шаблон устройства sen://
|
||||
получат в течение минуты.
|
||||
</span>
|
||||
<button className="btn btn--tonal" onClick={regenMasking} disabled={masking === 'busy'}>
|
||||
<IcoRefresh /> Сменить
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="toolbar">
|
||||
<input className="field" placeholder="Метка (напр. Семья)" value={label}
|
||||
onChange={e => setLabel(e.target.value)} onKeyDown={e => e.key === 'Enter' && create()} />
|
||||
@@ -408,6 +559,7 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
aria-label="Лимит устройств" value={limit} onChange={e => setLimit(e.target.value)} />
|
||||
<div className="toolbar-btns">
|
||||
<button className="btn btn--primary" onClick={create} disabled={creating}><IcoPlus /> Создать ключ</button>
|
||||
<button className="btn btn--tonal" onClick={load}><IcoRefresh /> Обновить</button>
|
||||
<button className="btn btn--tonal" onClick={() => setBulk(true)} disabled={!live.length || !nodes.length}
|
||||
title="Добавить или убрать серверы у всех мастер-ключей сразу"><IcoSettings /> Серверы для всех</button>
|
||||
</div>
|
||||
@@ -418,65 +570,56 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
<table className="mk-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Имя</th><th>Статус</th><th>Приоритет</th><th>IP</th><th>Платформа</th>
|
||||
<th>Имя</th><th>Статус</th><th>IP</th><th>Платформа</th>
|
||||
<th>↓ rx</th><th>↑ tx</th><th>Устройства</th><th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{keys.length === 0 ? (
|
||||
<tr><td colSpan={9} className="empty">Нет мастер-ключей</td></tr>
|
||||
<tr><td colSpan={8} className="empty">Нет мастер-ключей</td></tr>
|
||||
) : keys.map(k => {
|
||||
if (k.deleting) return (
|
||||
<tr key={k.id} className="mk-tr-master mk-last">
|
||||
<td><span className="mk-name"><IcoKey />{nameCell(k)}</span></td>
|
||||
<td colSpan={8}>{deletingChip(k)}</td>
|
||||
<td colSpan={7}>{deletingChip(k)}</td>
|
||||
</tr>
|
||||
);
|
||||
const list = devs[k.id] ?? [];
|
||||
const count = devs[k.id]?.length ?? k.devices;
|
||||
const free = Math.max(0, k.device_limit - count);
|
||||
const open = !folded.has(k.id);
|
||||
return (
|
||||
<Fragment key={k.id}>
|
||||
<tr className="mk-tr-master">
|
||||
<td><span className="mk-name">{caret(k)}<IcoKey />{nameCell(k)}{dataFlag(k)}</span></td>
|
||||
{summary(list)}
|
||||
<td><span className="mk-name">{caret(k, count)}<IcoKey />{nameCell(k)}{dataFlag(k)}</span></td>
|
||||
{summary(k, list, count === 0)}
|
||||
<td>{meter(k, count)}</td>
|
||||
<td className="td-actions mk-td-actions">{actions(k)}</td>
|
||||
</tr>
|
||||
{tools === k.id && <tr className="mk-tr-tools"><td colSpan={9}>{toolbox(k)}</td></tr>}
|
||||
{tools === k.id && <tr className="mk-tr-tools"><td colSpan={8}>{toolbox(k)}</td></tr>}
|
||||
{open && list.map((d, i) => (
|
||||
<tr key={d.id} className={`mk-tr-device${i === list.length - 1 && free === 0 ? ' mk-last' : ''}`}>
|
||||
<tr key={d.id} className={`mk-tr-device${i === list.length - 1 ? ' mk-last' : ''}`}>
|
||||
<td>
|
||||
<span className="mk-indent">
|
||||
<span className="name-stack">
|
||||
{d.device_name || 'Устройство'}
|
||||
<span className="tip-wrap" data-tip={`ID устройства ${d.device_id} · нажми, чтобы скопировать`}>
|
||||
<button className="copy-id" aria-label={`Скопировать ID устройства ${d.device_id}`}
|
||||
onClick={() => copyText(d.device_id).then(() => showMsg('ID устройства скопирован'), () => showMsg('Не удалось скопировать'))}>
|
||||
{d.device_id.slice(0, 8)}…
|
||||
</button>
|
||||
{/* пометки — в строке ID, не рядом с именем: так колонка «Имя» уже и таблица влезает */}
|
||||
<span className="mk-id-line">
|
||||
{deviceId(d)}
|
||||
{syncFlag(k, d) && <span className="tip-wrap tip-wrap--start mk-flag" data-tip={syncTip(k, d)}>· {syncFlag(k, d)}</span>}
|
||||
{d.rekey_requested && <span className="mk-flag">· ждёт смены ключа</span>}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
{d.rekey_requested && <span className="mk-flag"> · ждёт смены ключа</span>}
|
||||
{syncLabel(d) && <span className="mk-flag">{syncLabel(d)}</span>}
|
||||
</td>
|
||||
<td>{statusChip(d)}</td>
|
||||
<td><span className="user-chips"><PriorityChip priority={d.priority} torrent={d.torrent} /><TorrentChip torrent={d.torrent} /></span></td>
|
||||
<td className="td-mono">{ipCell(d)}</td>
|
||||
<td>{platformLabel(d)}</td>
|
||||
<td><span className="user-chips">{statusChip(d)}<PriorityChip priority={bgOnly(d.priority)} torrent={d.torrent} /><TorrentChip torrent={d.torrent} /></span></td>
|
||||
<td>{ipCell(d)}</td>
|
||||
<td>{platformCell(d)}</td>
|
||||
<td>{bytes(d.rx)}</td>
|
||||
<td>{bytes(d.tx)}</td>
|
||||
<td></td>
|
||||
<td className="td-actions mk-td-actions">{deviceActions(d)}</td>
|
||||
</tr>
|
||||
))}
|
||||
{open && free > 0 && (
|
||||
<tr className="mk-tr-free mk-last">
|
||||
<td colSpan={9}><span className="mk-indent">Свободно: {free}</span></td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
@@ -484,7 +627,8 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Мобильный: таблица скрыта (.table-card), то же — деревом карточек */}
|
||||
{/* Телефон и планшет: таблица скрыта (.table-card) — карточка на ключ: шапка, сводка, действия,
|
||||
ниже списком его устройства */}
|
||||
{keys.length === 0 ? <p className="mk-empty mk-tree">Нет мастер-ключей</p> : (
|
||||
<ul className="mk-tree">
|
||||
{keys.map(k => {
|
||||
@@ -492,39 +636,65 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
<li className="mk-root" key={k.id}>
|
||||
<div className="mk-master">
|
||||
<IcoKey />
|
||||
<span className="mk-master-label">{k.label}<code className="mk-master-uuid">{k.uuid}</code></span>
|
||||
{deletingChip(k)}
|
||||
<span className="mk-master-label">{nameCell(k)}</span>
|
||||
</div>
|
||||
<div className="mk-master-sum">{deletingChip(k)}</div>
|
||||
</li>
|
||||
);
|
||||
const list = devs[k.id] ?? [];
|
||||
const count = devs[k.id]?.length ?? k.devices;
|
||||
const free = Math.max(0, k.device_limit - count);
|
||||
const isFolded = folded.has(k.id);
|
||||
return (
|
||||
<li className="mk-root" key={k.id}>
|
||||
<div className="mk-master">
|
||||
{caret(k)}
|
||||
{caret(k, count)}
|
||||
<IcoKey />
|
||||
<span className="mk-master-label">{k.label}{dataFlag(k)}<code className="mk-master-uuid">{k.uuid}</code></span>
|
||||
<span className="mk-master-label">{nameCell(k)}</span>
|
||||
{meter(k, count)}
|
||||
{actions(k)}
|
||||
</div>
|
||||
<div className="mk-master-sum">
|
||||
{keyStatus(list, count === 0)}
|
||||
{keyServers(k, list)}
|
||||
{dataFlag(k)}
|
||||
</div>
|
||||
<div className="mk-master-actions">
|
||||
<button className="btn btn--tonal" onClick={() => showQR(k)}><IcoQR /> QR</button>
|
||||
<button className="btn btn--outline" onClick={() => copyLink(k)}><IcoCopy /> Ссылка</button>
|
||||
{moreButton('key', k.id, `Ещё: ${k.label}`)}
|
||||
</div>
|
||||
{tools === k.id && toolbox(k)}
|
||||
{!isFolded && (
|
||||
<ul className="mk-children">
|
||||
{list.map(d => deviceNode(k, d))}
|
||||
{free > 0 && (
|
||||
<li className="mk-node mk-node--free"><div className="mk-free">Свободно: {free}</div></li>
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
{!isFolded && list.length > 0 && <ul className="mk-devs">{list.map(d => deviceRow(k, d))}</ul>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{menu && (() => {
|
||||
const run = (f: () => void) => () => { setMenu(null); f(); };
|
||||
const at = { top: menu.top, right: menu.right };
|
||||
const cls = `mk-menu${menu.up ? ' mk-menu--up' : ''}`;
|
||||
if (menu.kind === 'device') {
|
||||
const d = Object.values(devs).flat().find(x => x.id === menu.id);
|
||||
if (!d) return null;
|
||||
return (
|
||||
<div className={cls} role="menu" aria-label={`Устройство ${d.device_name}`} ref={menuRef} style={at}>
|
||||
<button role="menuitem" className="mk-menu-item" onClick={run(() => newPsk(d))}><IcoRefresh /> Новый PSK</button>
|
||||
<button role="menuitem" className="mk-menu-item mk-menu-item--danger" onClick={run(() => revoke(d))}><IcoTrash /> Отозвать</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const k = keys.find(x => x.id === menu.id);
|
||||
if (!k) return null;
|
||||
return (
|
||||
<div className={cls} role="menu" aria-label={`Мастер-ключ ${k.label}`} ref={menuRef} style={at}>
|
||||
{menu.full && <button role="menuitem" className="mk-menu-item" onClick={run(() => copyLink(k))}><IcoCopy /> Скопировать ссылку</button>}
|
||||
<button role="menuitem" className="mk-menu-item" onClick={run(() => openTools(k))}><IcoSettings /> Настройки ключа</button>
|
||||
<button role="menuitem" className="mk-menu-item mk-menu-item--danger" onClick={run(() => remove(k))}><IcoTrash /> Удалить</button>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{bulk && (
|
||||
<BulkServersModal token={token} nodes={nodes} keys={live} defaults={defaults} onClose={() => setBulk(false)}
|
||||
onDone={n => { setBulk(false); showMsg(n ? `Серверы обновлены у ${n} ключей` : 'Сохранено'); load(); }} />
|
||||
@@ -538,8 +708,8 @@ export default function MasterKeysPage({ token, showMsg }: PageProps) {
|
||||
onClick={async () => { await copyText(modal.link); showMsg('Ссылка скопирована'); }} />
|
||||
<p className="qr-hint">Отсканируй в SenAWG · нажми на QR чтобы скопировать{modal.tls ? '' : ' · без TLS'}</p>
|
||||
<div className="qr-actions">
|
||||
<button className="btn btn--text" onClick={() => setModal(null)}>Закрыть</button>
|
||||
<button className="btn btn--primary" onClick={async () => { await copyText(modal.link); showMsg('Ссылка скопирована'); }}><IcoCopy /> Скопировать</button>
|
||||
<button className="btn btn--tonal" onClick={() => setModal(null)}>Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -7,70 +7,84 @@ LICENSE file in the root directory of this source tree.
|
||||
Общая дизайн-система — в App.css. */
|
||||
|
||||
.mk-notice {
|
||||
font-size: 13px;
|
||||
color: var(--error-text);
|
||||
background: var(--error-bg);
|
||||
border-radius: 16px;
|
||||
font-size: var(--body-medium-size); line-height: var(--body-medium-line);
|
||||
color: var(--on-error-container);
|
||||
background: var(--error-container);
|
||||
border-radius: var(--shape-large);
|
||||
padding: 10px 16px;
|
||||
}
|
||||
.mk-empty { font-size: 14px; color: var(--neutral-text); text-align: center; padding: 48px 0; }
|
||||
/* Предупреждение о маскировке: тёплый tertiary, как чип «устарела» у версии сервера */
|
||||
.mk-warn {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
background: var(--tertiary-container); color: var(--on-tertiary-container);
|
||||
border-radius: var(--shape-large);
|
||||
padding: 10px 12px 10px 16px;
|
||||
}
|
||||
.mk-warn-text {
|
||||
flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px;
|
||||
font-size: var(--body-medium-size); line-height: var(--body-medium-line);
|
||||
}
|
||||
.mk-warn-text b { font-weight: var(--weight-medium); }
|
||||
.mk-warn .btn { flex-shrink: 0; }
|
||||
.mk-empty { font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--neutral-text); text-align: center; padding: 48px 0; }
|
||||
.mk-limit-input { width: 88px !important; }
|
||||
|
||||
/* ── таблица (десктоп) ── */
|
||||
.mk-table td, .mk-table th { white-space: nowrap; }
|
||||
.mk-table .td-actions { width: 150px; }
|
||||
.mk-table .mk-device-id { display: inline-block; max-width: 170px; vertical-align: middle; }
|
||||
.mk-table .td-actions { width: 80px; } /* QR и «⋮» */
|
||||
.mk-table th, .mk-table td { padding-left: 10px; padding-right: 10px; }
|
||||
.mk-table th:first-child, .mk-table td:first-child { padding-left: 20px; }
|
||||
.mk-table th:last-child, .mk-table td:last-child { padding-right: 16px; }
|
||||
.mk-tr-master td { background: var(--surface-container); font-weight: 500; padding-top: 6px; padding-bottom: 6px; }
|
||||
.mk-tr-master td { background: var(--surface-container); font-weight: var(--weight-medium); padding-top: 6px; padding-bottom: 6px; }
|
||||
.mk-tr-master:hover td { background: var(--surface-container); }
|
||||
.mk-name { display: inline-flex; align-items: center; gap: 8px; color: var(--primary); }
|
||||
.mk-master-uuid {
|
||||
display: block;
|
||||
font-family: var(--mono); font-size: 12px; font-weight: 400;
|
||||
color: var(--neutral-text);
|
||||
overflow: hidden; text-overflow: ellipsis;
|
||||
}
|
||||
.mk-name .mk-caret { margin-left: -8px; }
|
||||
.mk-tr-master .mk-name { color: var(--on-surface); }
|
||||
.mk-tr-master .mk-name svg { color: var(--primary); }
|
||||
.mk-tr-tools td { background: var(--surface-container); padding-top: 4px; padding-bottom: 12px; } /* слева/справа — общие отступы колонок таблицы: блок стоит под заголовком «Имя» */
|
||||
.mk-tr-tools:hover { background: transparent; }
|
||||
.mk-tr-device td, .mk-tr-free td { padding-top: 10px; padding-bottom: 10px; }
|
||||
.mk-flag { color: var(--neutral-text); font-size: 12px; }
|
||||
.mk-tr-device td { padding-top: 10px; padding-bottom: 10px; }
|
||||
.mk-flag { color: var(--neutral-text); font-size: var(--body-small-size); line-height: var(--body-small-line); }
|
||||
.mk-id-line { display: inline-flex; align-items: baseline; gap: 6px; }
|
||||
/* чипы приоритета и торрентов в одной ячейке — как во вкладке «Пользователи» */
|
||||
.mk-table .user-chips { display: inline-flex; flex-wrap: nowrap; gap: 6px; }
|
||||
.mk-ip { font-family: var(--mono); }
|
||||
.mk-ip { font-family: var(--mono); font-size: var(--body-small-size); line-height: var(--body-small-line); }
|
||||
/* вторая строка ячейки: сервер чужого адреса, версия клиента */
|
||||
.mk-sub { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.mk-ip-line { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.mk-ip-more {
|
||||
font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--on-surface-variant);
|
||||
background: var(--surface-container-high); border-radius: var(--shape-full); padding: 0 6px;
|
||||
}
|
||||
.mk-srv, .mk-ver { font-weight: var(--weight-regular); }
|
||||
.mk-ver { align-self: flex-start; padding-top: 0; padding-bottom: 0; font-family: var(--mono); }
|
||||
/* иерархия: линия слева от имени и «ножка» к каждой строке; у последней линия обрывается */
|
||||
.mk-tr-device td:first-child, .mk-tr-free td:first-child {
|
||||
.mk-tr-device td:first-child {
|
||||
background: linear-gradient(var(--outline), var(--outline)) 30px 0 / 2px 100% no-repeat;
|
||||
}
|
||||
.mk-tr-device.mk-last td:first-child, .mk-tr-free.mk-last td:first-child { background-size: 2px 50%; }
|
||||
.mk-tr-device.mk-last td:first-child { background-size: 2px 50%; }
|
||||
.mk-indent { position: relative; display: inline-block; padding-left: 36px; }
|
||||
.mk-indent::before {
|
||||
content: ''; position: absolute; left: 10px; top: 50%; width: 16px;
|
||||
border-top: 2px solid var(--outline);
|
||||
}
|
||||
.mk-tr-free td { color: var(--neutral-dot); font-size: 12px; }
|
||||
.mk-tr-free:hover { background: transparent; }
|
||||
|
||||
/* ── дерево (мобильный) ── */
|
||||
.mk-tree, .mk-children { list-style: none; margin: 0; padding: 0; }
|
||||
.mk-tree, .mk-devs { list-style: none; margin: 0; padding: 0; }
|
||||
.mk-tree { display: none; flex-direction: column; gap: 12px; } /* только мобильный */
|
||||
|
||||
.mk-root {
|
||||
background: var(--surface-bright);
|
||||
border: 1px solid var(--outline-variant);
|
||||
border-radius: var(--r-card);
|
||||
padding: 12px 18px 14px;
|
||||
border-radius: var(--shape-extra-large);
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
/* родитель */
|
||||
/* шапка ключа: стрелка, ключ, метка с коротким UUID, полоска устройств */
|
||||
.mk-master { display: flex; align-items: center; gap: 10px; color: var(--primary); min-height: 42px; }
|
||||
.mk-master-label {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
font-size: var(--title-medium-size); line-height: var(--title-medium-line);
|
||||
font-weight: var(--weight-medium);
|
||||
color: var(--on-surface);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
@@ -83,13 +97,38 @@ LICENSE file in the root directory of this source tree.
|
||||
border: 0; border-radius: 50%;
|
||||
background: transparent;
|
||||
color: var(--neutral-text);
|
||||
font-size: 16px;
|
||||
font-size: var(--body-large-size); line-height: var(--body-large-line);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition: transform 0.15s;
|
||||
transition: transform var(--duration-short3) var(--ease-standard);
|
||||
}
|
||||
.mk-caret:hover { background: var(--state-neutral); }
|
||||
.mk-caret--folded { transform: rotate(-90deg); }
|
||||
.mk-caret-gap { width: 28px; flex-shrink: 0; } /* ключ без устройств: место стрелки */
|
||||
.mk-name .mk-caret-gap { margin-left: -8px; }
|
||||
|
||||
/* Меню «⋮» ключа (MD3 menu): плавает над таблицей, у кнопки справа */
|
||||
.mk-menu {
|
||||
position: fixed; z-index: 30;
|
||||
min-width: 200px; padding: 6px;
|
||||
background: var(--surface-container);
|
||||
border-radius: var(--shape-large);
|
||||
box-shadow: var(--elevation-2);
|
||||
animation: mk-menu-in var(--duration-short4) var(--ease-emphasized-decelerate);
|
||||
transform-origin: top right;
|
||||
}
|
||||
.mk-menu--up { transform: translateY(-100%); transform-origin: bottom right; }
|
||||
@keyframes mk-menu-in { from { opacity: 0; scale: .92; } }
|
||||
.mk-menu-item {
|
||||
display: flex; align-items: center; gap: 12px; width: 100%;
|
||||
min-height: 40px; padding: 0 12px;
|
||||
border: 0; border-radius: var(--shape-medium); background: transparent;
|
||||
font-family: var(--font); font-size: var(--label-large-size); line-height: var(--label-large-line); font-weight: var(--weight-medium);
|
||||
color: var(--on-surface); text-align: left; cursor: pointer;
|
||||
}
|
||||
.mk-menu-item svg { color: var(--on-surface-variant); flex-shrink: 0; }
|
||||
.mk-menu-item--danger, .mk-menu-item--danger svg { color: var(--error); }
|
||||
@media (pointer: coarse) { .mk-menu-item { min-height: 48px; } }
|
||||
@media (prefers-reduced-motion: reduce) { .mk-menu { animation: none; } }
|
||||
|
||||
.mk-tools {
|
||||
display: grid;
|
||||
@@ -103,10 +142,10 @@ LICENSE file in the root directory of this source tree.
|
||||
display: flex; flex-direction: column; gap: 10px;
|
||||
background: var(--surface-bright);
|
||||
border: 1px solid var(--outline-variant);
|
||||
border-radius: 16px;
|
||||
border-radius: var(--shape-large);
|
||||
padding: 12px 16px 14px;
|
||||
}
|
||||
.mk-box-title { margin: 0; font-size: 13px; font-weight: 500; color: var(--label); }
|
||||
.mk-box-title { margin: 0; font-size: var(--title-small-size); line-height: var(--title-small-line); font-weight: var(--weight-medium); color: var(--on-surface-variant); }
|
||||
.mk-box .mk-box-title { margin-bottom: 2px; }
|
||||
/* строка настройки: слева название и пояснение, справа контрол */
|
||||
.mk-setting {
|
||||
@@ -117,25 +156,26 @@ LICENSE file in the root directory of this source tree.
|
||||
.mk-box-title + .mk-setting { border-top: 0; padding-top: 4px; }
|
||||
.mk-setting:last-child { padding-bottom: 0; }
|
||||
.mk-setting-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.mk-setting-name { font-size: 14px; font-weight: 500; color: var(--on-surface); }
|
||||
.mk-setting-hint { font-size: 12px; color: var(--neutral-text); }
|
||||
.mk-setting-name { font-size: var(--title-small-size); line-height: var(--title-small-line); font-weight: var(--weight-medium); color: var(--on-surface); }
|
||||
.mk-setting-hint { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.mk-setting-ctl { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
|
||||
.mk-uuid {
|
||||
font-family: var(--mono); font-size: 12px; color: var(--on-surface);
|
||||
font-family: var(--mono); font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--on-surface);
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%;
|
||||
}
|
||||
.mk-setting-ctl .btn { height: 36px; padding: 0 16px; font-size: 13px; }
|
||||
.mk-setting-ctl .btn { height: 36px; padding: 0 16px; font-size: var(--label-large-size); line-height: var(--label-large-line); }
|
||||
.mk-limit-input { height: 36px; width: 80px !important; text-align: center; }
|
||||
|
||||
/* прогресс занятых слотов с числом внутри; полный — цветом «ошибка».
|
||||
/* прогресс занятых слотов с числом внутри: обычная заливка primary, цветом — только когда мест
|
||||
не осталось (тёплый: это повод присмотреться, а не ошибка).
|
||||
Текст дублируется: тёмный на дорожке, светлый поверх заливки (обрезается ею). */
|
||||
.mk-meter {
|
||||
--mk-w: 136px;
|
||||
--meter-fill: var(--success-dot); /* < 2/3 — зелёный */
|
||||
--meter-on: #2a2118; /* цвет числа поверх заливки */
|
||||
--meter-fill: var(--primary);
|
||||
--meter-on: var(--on-primary); /* цвет числа поверх заливки */
|
||||
position: relative;
|
||||
width: var(--mk-w); height: 20px;
|
||||
border-radius: var(--r-pill);
|
||||
border-radius: var(--shape-full);
|
||||
background: var(--outline-variant);
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
@@ -144,7 +184,7 @@ LICENSE file in the root directory of this source tree.
|
||||
position: absolute; left: 0; top: 0; bottom: 0;
|
||||
background: var(--meter-fill);
|
||||
overflow: hidden;
|
||||
transition: width 0.25s, background 0.25s;
|
||||
transition: width var(--duration-medium1) var(--ease-standard), background var(--duration-medium1) var(--ease-standard);
|
||||
}
|
||||
/* числа по краям внутри полоски: текущее слева, лимит справа */
|
||||
.mk-meter-text {
|
||||
@@ -153,90 +193,62 @@ LICENSE file in the root directory of this source tree.
|
||||
box-sizing: border-box;
|
||||
padding: 0 11px;
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
font-size: 12px; font-weight: 500;
|
||||
font-size: var(--label-medium-size); line-height: var(--label-medium-line); font-weight: var(--weight-medium);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--on-surface);
|
||||
}
|
||||
.mk-meter-text--on { color: var(--meter-on); }
|
||||
.mk-meter--warn { --meter-fill: var(--warn-dot); } /* от 2/3 — оранжевый */
|
||||
.mk-meter--full { --meter-fill: var(--error-dot); --meter-on: #fff; } /* лимит — красный */
|
||||
:root[data-theme="dark"] .mk-meter--full { --meter-on: #2a2118; }
|
||||
.mk-meter--full { --meter-fill: var(--warn-dot); --meter-on: #2a2118; } /* все места заняты */
|
||||
|
||||
.mk-box .tip-wrap { width: 100%; }
|
||||
|
||||
/* дети: вертикальная линия слева и «ножка» к каждому узлу */
|
||||
.mk-children { margin: 8px 0 0 18px; padding-left: 28px; border-left: 2px solid var(--outline); }
|
||||
.mk-node { position: relative; padding: 4px 0; }
|
||||
.mk-node::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -28px; top: 50%;
|
||||
width: 28px;
|
||||
border-top: 2px solid var(--outline);
|
||||
}
|
||||
/* последний узел: линия родителя обрывается на его «ножке» */
|
||||
.mk-node:last-child::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -30px; top: calc(50% + 1px); bottom: 0;
|
||||
width: 2px;
|
||||
background: var(--surface-bright);
|
||||
}
|
||||
/* сводка (статус, серверы) и действия ключа */
|
||||
.mk-master-sum { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 6px; }
|
||||
.mk-master-sum:empty { display: none; }
|
||||
.mk-master-actions { display: flex; align-items: center; gap: 8px; margin-top: 12px; }
|
||||
.mk-master-actions .btn { flex: 1; }
|
||||
.mk-tree .mk-more { width: 40px; height: 40px; }
|
||||
/* на телефоне .tip-wrap по умолчанию во всю ширину — здесь чипы и ID идут в строку */
|
||||
.mk-tree .tip-wrap { width: auto; }
|
||||
|
||||
.mk-device {
|
||||
display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
|
||||
background: var(--surface-container);
|
||||
border-radius: 14px;
|
||||
padding: 8px 14px;
|
||||
/* устройства ключа — строками списка под ним, разделены линией */
|
||||
.mk-devs { margin: 12px -16px -12px; border-top: 1px solid var(--outline-variant); }
|
||||
.mk-dev { padding: 10px 16px; }
|
||||
.mk-dev + .mk-dev { border-top: 1px solid var(--outline-variant); }
|
||||
.mk-dev-head { display: flex; align-items: center; gap: 8px; }
|
||||
.mk-dev-title { flex: 1; min-width: 0; }
|
||||
.mk-dev-name {
|
||||
font-size: var(--title-small-size); line-height: var(--title-small-line); font-weight: var(--weight-medium); color: var(--on-surface);
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.mk-device-main { display: flex; flex-direction: column; min-width: 0; flex: 1 1 160px; }
|
||||
.mk-device-title { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
|
||||
.mk-device-id {
|
||||
font-family: var(--mono);
|
||||
font-size: 11px;
|
||||
color: var(--neutral-text);
|
||||
background: var(--surface-bright);
|
||||
border-radius: var(--r-pill);
|
||||
padding: 1px 8px;
|
||||
min-width: 0;
|
||||
max-width: 200px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
.mk-dev-head .mk-more { margin: -4px -8px -4px 0; }
|
||||
.mk-dev-meta {
|
||||
display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; margin-top: 4px;
|
||||
font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text);
|
||||
}
|
||||
.mk-device-name { font-size: 14px; font-weight: 500; color: var(--on-surface); }
|
||||
.mk-device-sub { font-size: 12px; color: var(--neutral-text); }
|
||||
.mk-device-ip {
|
||||
display: flex; flex-wrap: wrap; align-items: center; gap: 8px;
|
||||
width: 100%;
|
||||
color: var(--neutral-text);
|
||||
}
|
||||
.mk-device-ip .mk-ip { font-size: 13px; }
|
||||
.mk-device-ip .tip-wrap { width: auto; }
|
||||
.mk-device-traffic { display: flex; gap: 12px; font-family: var(--mono); font-size: 12px; color: var(--neutral-text); }
|
||||
.mk-metric { display: inline-flex; gap: 4px; }
|
||||
.mk-metric i, .mk-metric b { font-style: normal; font-weight: 400; }
|
||||
.mk-dev-meta .chip { font-size: var(--body-small-size); }
|
||||
.mk-dev-traffic { font-family: var(--mono); white-space: pre; }
|
||||
|
||||
.mk-free {
|
||||
border: 1px dashed var(--outline);
|
||||
border-radius: 14px;
|
||||
padding: 10px 14px;
|
||||
font-size: 13px;
|
||||
color: var(--neutral-dot);
|
||||
}
|
||||
|
||||
/* ── мобильный (design.md, часть IV): одна колонка, тач-цели ≥ 44px, rx/tx блоками
|
||||
50/50, действия рядом с большим пальцем ── */
|
||||
@media (max-width: 640px) {
|
||||
/* ── телефон и планшет (design.md, часть IV): карточка на ключ, устройства строками, тач-цели ≥ 44px ── */
|
||||
/* compact и medium (< 840px): карточки вместо таблицы */
|
||||
@media (max-width: 839px) {
|
||||
.mk-warn { flex-wrap: wrap; padding: 12px 12px 12px 16px; }
|
||||
.mk-warn-text { flex-basis: 100%; }
|
||||
.mk-warn .btn { margin-left: auto; }
|
||||
.mk-tree { display: flex; }
|
||||
}
|
||||
@media (pointer: coarse) {
|
||||
.mk-tree .mk-more { width: 44px; height: 44px; }
|
||||
}
|
||||
@media (max-width: 599px) {
|
||||
.mk-limit-input { width: 100% !important; }
|
||||
|
||||
.mk-root { padding: 12px; }
|
||||
.mk-devs { margin: 12px -12px -12px; }
|
||||
.mk-dev { padding: 10px 12px; }
|
||||
|
||||
/* родитель: шапка, затем ряд действий на всю ширину */
|
||||
.mk-master { flex-wrap: wrap; row-gap: 10px; }
|
||||
.mk-master .actions { width: 100%; gap: 8px; }
|
||||
.mk-caret { width: 44px; height: 44px; margin: -6px 0 -6px -8px; }
|
||||
.mk-caret-gap { width: 44px; margin-left: -8px; }
|
||||
.mk-meter { --mk-w: 112px; height: 24px; }
|
||||
|
||||
/* настройки узла: поля и кнопки на всю ширину */
|
||||
@@ -246,38 +258,6 @@ LICENSE file in the root directory of this source tree.
|
||||
.mk-setting-ctl .btn { flex: 1; height: 44px; }
|
||||
.mk-setting-ctl .mk-limit-input { width: 100% !important; flex: 1; height: 44px; }
|
||||
.mk-tools .btn { width: 100%; height: 44px; justify-content: center; }
|
||||
|
||||
/* дерево уже: отступы поменьше, «ножки» короче */
|
||||
.mk-children { margin-left: 8px; padding-left: 14px; }
|
||||
.mk-node { padding: 4px 0; }
|
||||
.mk-node::before { left: -14px; width: 14px; }
|
||||
.mk-node:last-child::after { left: -16px; }
|
||||
|
||||
/* устройство — карточка: заголовок + чип, метрики 50/50, ряд действий */
|
||||
.mk-device { border-radius: 16px; padding: 12px; gap: 10px; }
|
||||
.mk-device-main { flex: 1 1 0; }
|
||||
.mk-device-title { flex-wrap: wrap; row-gap: 2px; }
|
||||
.mk-device-id { max-width: 100%; }
|
||||
.mk-device-traffic { width: 100%; gap: 8px; }
|
||||
.mk-metric {
|
||||
flex: 1; flex-direction: column; gap: 2px;
|
||||
background: var(--surface-bright);
|
||||
border-radius: 16px; padding: 8px 12px;
|
||||
}
|
||||
.mk-metric i { font-family: var(--font, inherit); font-size: 12px; color: var(--neutral-text); }
|
||||
.mk-metric-name::after { content: attr(data-sfx); }
|
||||
.mk-metric b { font-size: 16px; font-weight: 500; color: var(--on-surface); }
|
||||
|
||||
/* кнопки действий: контурные, на всю ширину ряда, 44px */
|
||||
.mk-device .actions { width: 100%; gap: 8px; }
|
||||
.mk-master .btn-icon, .mk-device .btn-icon {
|
||||
flex: 1; width: auto; height: 44px;
|
||||
border: 1px solid var(--outline);
|
||||
border-radius: var(--r-pill);
|
||||
}
|
||||
.mk-master .btn-icon--danger, .mk-device .btn-icon--danger { border-color: var(--error-dot); }
|
||||
|
||||
.mk-free { padding: 12px; font-size: 13px; }
|
||||
}
|
||||
|
||||
/* «Серверы для всех» (BulkServersModal) */
|
||||
@@ -285,27 +265,25 @@ LICENSE file in the root directory of this source tree.
|
||||
.bs-list { display: flex; flex-direction: column; gap: 8px; }
|
||||
.bs-row {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
background: var(--surface-container); border-radius: 12px; padding: 8px 8px 8px 14px;
|
||||
font-size: 13px; color: var(--on-surface);
|
||||
background: var(--surface-container); border-radius: var(--shape-medium); padding: 8px 8px 8px 14px;
|
||||
font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--on-surface);
|
||||
}
|
||||
.bs-name { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; }
|
||||
.bs-sub { display: flex; flex-wrap: wrap; gap: 8px; font-size: 12px; color: var(--neutral-text); }
|
||||
.bs-sub { display: flex; flex-wrap: wrap; gap: 8px; font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.bs-sub .server-pick-ip { margin-left: 0; }
|
||||
.bs-opts { display: flex; gap: 4px; flex-shrink: 0; }
|
||||
.bs-opt {
|
||||
min-height: 36px; padding: 0 12px;
|
||||
font: inherit; font-size: 13px; color: var(--on-surface);
|
||||
font: inherit; font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--on-surface);
|
||||
background: var(--surface-bright);
|
||||
border: 1px solid var(--outline); border-radius: var(--r-pill);
|
||||
border: 1px solid var(--outline); border-radius: var(--shape-full);
|
||||
cursor: pointer; white-space: nowrap;
|
||||
}
|
||||
.bs-opt:hover { background: var(--state-primary); }
|
||||
.bs-opt--on { background: var(--primary-container); color: var(--on-primary-container); border-color: transparent; font-weight: 500; }
|
||||
.bs-check { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--on-surface); cursor: pointer; }
|
||||
.bs-opt--on { background: var(--primary-container); color: var(--on-primary-container); border-color: transparent; font-weight: var(--weight-medium); }
|
||||
.bs-check { display: flex; align-items: center; gap: 8px; font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--on-surface); cursor: pointer; }
|
||||
.bs-check input { accent-color: var(--primary); width: 18px; height: 18px; margin: 0; }
|
||||
@media (max-width: 640px) {
|
||||
@media (max-width: 599px) {
|
||||
.bs-row { flex-wrap: wrap; }
|
||||
.bs-opts { width: 100%; }
|
||||
.bs-opt { flex: 1; }
|
||||
}
|
||||
.bs-modal .btn:disabled { opacity: .5; cursor: default; }
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"id": "migrate",
|
||||
"label": "Перенос",
|
||||
"icon": "move",
|
||||
"group": "server",
|
||||
"order": 1.9,
|
||||
"chrome": {
|
||||
"serverBar": false,
|
||||
"restart": false
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2026 Ivan Vasilev
|
||||
This source code is licensed under the MIT license found in the
|
||||
LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
/* Стили вкладки «Перенос». Общая дизайн-система — в App.css. */
|
||||
|
||||
.mv-box { display: flex; flex-direction: column; gap: 10px; background: var(--surface-container); border-radius: 16px; padding: 12px 16px; }
|
||||
.mv-title { margin: 0; font-size: 14px; font-weight: 500; }
|
||||
.mv-text { margin: 0; font-size: 14px; line-height: 1.5; }
|
||||
.mv-muted { font-size: 13px; color: var(--neutral-text); }
|
||||
.mv-steps { margin: 0; padding-left: 20px; font-size: 14px; line-height: 1.6; }
|
||||
.mv-row { display: flex; gap: 8px; }
|
||||
.mv-row .field { flex: 1; min-width: 0; font-family: var(--mono); font-size: 12px; }
|
||||
.mv-row--end { justify-content: flex-end; flex-wrap: wrap; }
|
||||
.mv-self { align-self: flex-start; }
|
||||
.mv-notice {
|
||||
font-size: 13px; color: var(--error-text); background: var(--error-bg);
|
||||
border-radius: 16px; padding: 10px 16px; margin: 0;
|
||||
}
|
||||
.mv-box .node-modal-cmd { background: var(--surface-bright); }
|
||||
@media (max-width: 640px) { .mv-row:not(.mv-row--end) { flex-direction: column; } }
|
||||
.mv-box .btn:disabled { opacity: .5; cursor: default; }
|
||||
.mv-checks { display: flex; flex-direction: column; gap: 8px; }
|
||||
.mv-check { display: flex; align-items: baseline; gap: 10px; font-size: 14px; line-height: 1.5; }
|
||||
.mv-check .chip { flex-shrink: 0; }
|
||||
+106
-154
@@ -2,20 +2,16 @@
|
||||
// This source code is licensed under the MIT license found in the
|
||||
// LICENSE file in the root directory of this source tree.
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { apiFetch, copyText, getServerId, type NodeInfo, type PageProps } from '../../lib/shared';
|
||||
import { IcoCopy, IcoTrash } from '../../components/icons';
|
||||
import { apiFetch, getServerId, openTab, announcePrometheus, type NodeInfo, type PageProps } from '../../lib/shared';
|
||||
import { IcoGear } from '../../components/icons';
|
||||
import type { MonitorStatus as Status } from '../settings/prometheus';
|
||||
import LineChart from '../../components/LineChart';
|
||||
import ServerSelect, { ALL_SERVERS } from '../../components/ServerSelect';
|
||||
import './monitor.css';
|
||||
|
||||
// Вкладка «Монитор»: встроенный Prometheus и основные графики.
|
||||
// Кнопка «Подключить Prometheus» просит awg-ctrl сервера поставить его (`awg-ctrl monitor install`, root;
|
||||
// сама панель пакетов не ставит). У панели без VPN он ставится на ноду, и панель читает его через её агента.
|
||||
// Вкладка «Монитор»: основные графики со встроенного Prometheus. Ставится и удаляется он в «Настройках»,
|
||||
// раздел «Prometheus» (tabs/settings/prometheus); пока его нет, здесь — карточка со ссылкой туда.
|
||||
// Графики читают Prometheus через фиксированные запросы панели (internal/ui/monitor.go).
|
||||
interface Status {
|
||||
ready: boolean; can_install: boolean; command: string;
|
||||
host: { id: number; name: string } | null; // Prometheus на ноде (или будет поставлен туда); null — на этом сервере
|
||||
job: { action: 'install' | 'remove'; running: boolean; exit: number | null; log: string } | null; // последняя операция
|
||||
}
|
||||
type Pts = [number, number][];
|
||||
interface Overview {
|
||||
range: string; step: number; from: number; to: number;
|
||||
@@ -27,6 +23,24 @@ interface Overview {
|
||||
total: Series;
|
||||
}
|
||||
interface Series { down: Pts; up: Pts; online: Pts; heavy: Pts; drops: Pts; cpu: Pts; mem: Pts }
|
||||
type Row = Overview['servers'][number];
|
||||
type NumKey = 'down' | 'up' | 'online' | 'heavy' | 'cpu' | 'mem' | 'cores' | 'mem_total' | 'used_down' | 'used_up';
|
||||
|
||||
// «Все серверы» — сводка «сейчас» для плиток: скорости, устройства, ядра, память и объём складываем,
|
||||
// загрузку процессора и памяти — среднее по серверам (как и ряды total в monitor.go).
|
||||
function sumUp(rows: Row[]): Row | undefined {
|
||||
if (rows.length <= 1) return rows[0];
|
||||
const sum = (k: NumKey) => rows.some(r => r[k] != null) ? rows.reduce((n, r) => n + (r[k] ?? 0), 0) : null;
|
||||
const avg = (k: NumKey) => {
|
||||
const v = rows.map(r => r[k]).filter((x): x is number => x != null);
|
||||
return v.length ? v.reduce((a, b) => a + b, 0) / v.length : null;
|
||||
};
|
||||
return {
|
||||
id: ALL_SERVERS, name: 'Все серверы', ok: rows.every(r => r.ok), congested: rows.some(r => r.congested),
|
||||
down: sum('down'), up: sum('up'), online: sum('online'), heavy: sum('heavy'), cpu: avg('cpu'), mem: avg('mem'),
|
||||
cores: sum('cores'), mem_total: sum('mem_total'), used_down: sum('used_down'), used_up: sum('used_up'),
|
||||
};
|
||||
}
|
||||
|
||||
const RANGES: [string, string][] = [['1h', '1 час'], ['6h', '6 часов'], ['24h', '24 часа'], ['7d', '7 дней'], ['30d', '30 дней']];
|
||||
|
||||
@@ -51,28 +65,6 @@ function Bar({ v, label }: { v: number | null | undefined; label: string }) {
|
||||
</span>
|
||||
);
|
||||
}
|
||||
// Прогресс операции из строк «N/M шаг», которые печатает сам установщик (cli/src/monitor.ts). Шаг N считаем
|
||||
// выполненным наполовину: так полоска не стоит на нуле, пока идёт долгий apt, и не обещает больше, чем известно.
|
||||
const STEP = /^(\d+)\/(\d+)\s+(.+)$/;
|
||||
function JobProgress({ job, starting }: { job: Status['job']; starting: boolean }) {
|
||||
let step: [number, number, string] | null = null;
|
||||
for (const l of job?.log.split('\n') ?? []) { const m = STEP.exec(l.trim()); if (m) step = [Number(m[1]), Number(m[2]), m[3]]; }
|
||||
const failed = !!job && job.exit !== null && job.exit !== 0;
|
||||
const done = !!job && job.exit === 0;
|
||||
const pct = done ? 100 : step ? ((step[0] - 0.5) / step[1]) * 100 : 0;
|
||||
const label = failed ? `Не удалось (код ${job!.exit})`
|
||||
: done ? (job!.action === 'install' ? 'Готово' : 'Удалено')
|
||||
: step ? `Шаг ${step[0]} из ${step[1]}: ${step[2]}` : 'Запуск…';
|
||||
return (
|
||||
<div className="mon-progress" aria-live="polite">
|
||||
<span className={`mon-pbar${failed ? ' mon-pbar--bad' : done ? ' mon-pbar--ok' : !step && (starting || job?.running) ? ' mon-pbar--wait' : ''}`}
|
||||
role="progressbar" aria-label="Ход операции" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(pct)}>
|
||||
<i style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
<span className="mon-progress-label">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const gb = (b: number) => `${nf(b / 2 ** 30, 1)} ГБ`;
|
||||
// Объём трафика — десятичные единицы, как считают провайдеры: 1 ТБ = 10¹² байт
|
||||
function vol(b: number): string {
|
||||
@@ -81,39 +73,42 @@ function vol(b: number): string {
|
||||
return `${nf(b / 1e6, 0)} МБ`;
|
||||
}
|
||||
|
||||
export default function MonitorPage({ token, showMsg }: PageProps) {
|
||||
export default function MonitorPage({ token }: PageProps) {
|
||||
const [status, setStatus] = useState<Status | null>(null);
|
||||
const [range, setRange] = useState('1h');
|
||||
const [ov, setOv] = useState<Overview | null>(null);
|
||||
const [ovErr, setOvErr] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [pending, setPending] = useState<'install' | 'remove' | null>(null); // операция запущена из этой вкладки
|
||||
const [server, setServer] = useState<NodeInfo | null>(null); // показанный сервер: выбран в другой вкладке, здесь не меняется
|
||||
const [nodes, setNodes] = useState<NodeInfo[]>([]);
|
||||
// Чьи графики: сервер (по умолчанию — выбранный в шапке) или ALL_SERVERS. Выбор свой, шапку не меняет.
|
||||
const [view, setView] = useState(() => getServerId() ?? 0);
|
||||
const alive = useRef(true);
|
||||
// StrictMode монтирует эффект дважды: флаг надо вернуть в true, иначе все ответы отбрасываются
|
||||
useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
|
||||
|
||||
const loadStatus = useCallback(async () => {
|
||||
try { const s = await apiFetch('GET', `/ui/monitor?server=${getServerId() ?? 0}`, token) as Status; if (alive.current) setStatus(s); return s; }
|
||||
try { const s = await apiFetch('GET', `/ui/monitor?server=${getServerId() ?? 0}`, token) as Status; announcePrometheus(s.ready); if (alive.current) setStatus(s); return s; }
|
||||
catch { return null; }
|
||||
}, [token]);
|
||||
|
||||
const loadOverview = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const o = await apiFetch('GET', `/ui/monitor/overview?range=${range}&server=${getServerId() ?? 0}`, token) as Overview;
|
||||
// Без ?server= monitor.go отдаёт все серверы: total — сумма (процессор и память — среднее), servers — каждый
|
||||
const q = view === ALL_SERVERS ? '' : `&server=${view}`;
|
||||
const o = await apiFetch('GET', `/ui/monitor/overview?range=${range}${q}`, token) as Overview;
|
||||
if (alive.current) { setOv(o); setOvErr(''); }
|
||||
} catch (e: any) { if (alive.current) setOvErr(e?.response?.data?.error ?? 'Не удалось получить данные'); }
|
||||
finally { if (alive.current) setLoading(false); }
|
||||
}, [token, range]);
|
||||
}, [token, range, view]);
|
||||
|
||||
useEffect(() => { void loadStatus(); }, [loadStatus]);
|
||||
|
||||
// Название и состояние сервера для заголовка; список серверов на этой вкладке не показываем
|
||||
// Серверы для выбора (и их связь — точки на плашках)
|
||||
useEffect(() => {
|
||||
const load = () => apiFetch('GET', '/ui/nodes', token)
|
||||
.then(r => { if (alive.current) setServer((r.nodes as NodeInfo[]).find(n => n.id === (getServerId() ?? 0)) ?? null); })
|
||||
.catch(() => { /* заголовок необязателен */ });
|
||||
.then(r => { if (alive.current) setNodes(r.nodes ?? []); })
|
||||
.catch(() => { /* выбор необязателен — останется текущий сервер */ });
|
||||
void load();
|
||||
const t = setInterval(load, 15000);
|
||||
return () => clearInterval(t);
|
||||
@@ -127,116 +122,43 @@ export default function MonitorPage({ token, showMsg }: PageProps) {
|
||||
return () => clearInterval(t);
|
||||
}, [status?.ready, loadOverview]);
|
||||
|
||||
// Пока идёт установка или удаление — следим за ходом: раз в 2 с читаем статус и лог
|
||||
// Пока Prometheus нет — раз в 10 с проверяем: его могли поставить в «Настройках»
|
||||
useEffect(() => {
|
||||
if (!pending && !status?.job?.running) return;
|
||||
const t = setInterval(async () => {
|
||||
const s = await loadStatus();
|
||||
if (s && !s.job?.running) setPending(null);
|
||||
}, 2000);
|
||||
if (!status || status.ready) return;
|
||||
const t = setInterval(() => { void loadStatus(); }, 10000);
|
||||
return () => clearInterval(t);
|
||||
}, [pending, status?.job?.running, loadStatus]);
|
||||
}, [status, loadStatus]);
|
||||
|
||||
const run = async (action: 'install' | 'remove') => {
|
||||
if (action === 'remove' && !confirm('Удалить Prometheus? Он будет остановлен, а накопленные графики (до 31 дня) сотрутся. Панель продолжит отдавать /metrics.')) return;
|
||||
setPending(action);
|
||||
try { await apiFetch('POST', `/ui/monitor/${action}?server=${getServerId() ?? 0}`, token); await loadStatus(); }
|
||||
catch (e: any) { setPending(null); showMsg(e?.response?.data?.error ?? (action === 'install' ? 'Не удалось запустить установку' : 'Не удалось запустить удаление')); }
|
||||
};
|
||||
const working = !!pending || !!status?.job?.running;
|
||||
|
||||
// Прогресс рядом с кнопкой: для установки — пока Prometheus нет (там же виден итог удаления), для удаления — только удаление
|
||||
const progressFor = (action: 'install' | 'remove' | 'any') => {
|
||||
const j = status?.job;
|
||||
const mine = !!j && (action === 'any' || j.action === action) && (j.running || j.exit !== null);
|
||||
const starting = !!pending && (action === 'any' || action === pending);
|
||||
return mine || starting ? <JobProgress job={mine ? j! : null} starting={starting} /> : null;
|
||||
};
|
||||
|
||||
// Полный лог — только при ошибке: оператору нужна причина, а не поток строк apt
|
||||
const failureLog = () => {
|
||||
const j = status?.job;
|
||||
if (!j || j.exit === null || j.exit === 0) return null;
|
||||
return (
|
||||
<>
|
||||
<pre className="mon-log">{j.log.trim()}</pre>
|
||||
<p className="login-error">
|
||||
{j.action === 'install' ? 'Установка' : 'Удаление'} не удалась. Если дело в правах или пакетах, выполните вручную: <b>{`awg-ctrl monitor ${j.action}`}</b>
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// ───────── установка ─────────
|
||||
// Prometheus нет — графиков не будет: ведём в «Настройки», где он ставится
|
||||
const setup = status && !status.ready && (
|
||||
<section className="mon-card" aria-labelledby="mon-setup">
|
||||
<div className="mon-head">
|
||||
<h3 className="mon-title" id="mon-setup">Мониторинг</h3>
|
||||
<span className="chip chip--offline"><span className="chip-dot" />не подключён</span>
|
||||
<span className="chip chip--offline">
|
||||
<span className="chip-dot" />{status.job?.running && status.job.action === 'install' ? 'ставится' : 'не подключён'}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mon-hint">
|
||||
Панель поставит Prometheus {status.host ? <>на сервер <b>{status.host.name}</b></> : 'на этот сервер'} и сама подключит его к своим метрикам: основные графики —
|
||||
скорость, устройства онлайн, нагрузка на канал, — появятся здесь через минуту-две. Prometheus слушает
|
||||
только 127.0.0.1, наружу он не открывается.
|
||||
Графики — скорость, устройства онлайн, нагрузка на канал — строит встроенный Prometheus.
|
||||
Он ставится в «Настройках», на вкладке «Prometheus»; графики появятся здесь через минуту-две после установки.
|
||||
</p>
|
||||
|
||||
{status.can_install ? (
|
||||
<div className="mon-actions">
|
||||
<button className="btn btn--primary" onClick={() => run('install')} disabled={working}>
|
||||
{pending === 'install' || (status.job?.running && status.job.action === 'install') ? 'Устанавливаем…' : 'Подключить Prometheus'}
|
||||
</button>
|
||||
{progressFor('any')}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="mon-hint">
|
||||
У этой панели нет своего VPN-сервера: выберите ноду в сервер-баре, чтобы поставить Prometheus на неё
|
||||
кнопкой, или выполните на ней от root:
|
||||
</p>
|
||||
<code className="mon-code">{status.command}</code>
|
||||
<div className="mon-actions">
|
||||
<button className="btn btn--tonal" onClick={() => copyText(status.command).then(() => showMsg('Команда скопирована'))}>
|
||||
<IcoCopy /> Скопировать
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{failureLog()}
|
||||
</section>
|
||||
);
|
||||
|
||||
// Удаление: только пока Prometheus есть
|
||||
const manage = status?.ready && (
|
||||
<section className="mon-card" aria-labelledby="mon-manage">
|
||||
<div className="mon-head">
|
||||
<h3 className="mon-title" id="mon-manage">Prometheus</h3>
|
||||
<span className="chip chip--online"><span className="chip-dot" />работает</span>
|
||||
<div className="mon-actions">
|
||||
<button className="btn btn--primary" onClick={() => openTab('settings', 'prom')}>
|
||||
<IcoGear /> Открыть настройки
|
||||
</button>
|
||||
</div>
|
||||
<p className="mon-hint">
|
||||
Стоит {status.host ? <>на сервере <b>{status.host.name}</b> (панель читает его через агента ноды)</> : 'на этом сервере'} и
|
||||
слушает только 127.0.0.1:9090, графики хранит 31 день. Удаление остановит его, снимет пакет и сотрёт накопленные данные.
|
||||
</p>
|
||||
{status.can_install ? (
|
||||
<div className="mon-actions">
|
||||
<button className="btn btn--danger" onClick={() => run('remove')} disabled={working}>
|
||||
<IcoTrash /> {pending === 'remove' || (status.job?.running && status.job.action === 'remove') ? 'Удаляем…' : 'Удалить Prometheus'}
|
||||
</button>
|
||||
{progressFor('remove')}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="mon-hint">Выполните на сервере с Prometheus от root:</p>
|
||||
<code className="mon-code">awg-ctrl monitor remove</code>
|
||||
</>
|
||||
)}
|
||||
{status.job?.action === 'remove' && failureLog()}
|
||||
</section>
|
||||
);
|
||||
|
||||
// ───────── дашборд ─────────
|
||||
// Вкладка показывает один сервер — выбранный в сервер-баре; при смене сервера App монтирует её заново.
|
||||
const one = ov?.servers[0];
|
||||
// Один сервер или сводка по всем (sumUp) — плитки читают одно и то же
|
||||
const all = view === ALL_SERVERS;
|
||||
const one = all ? sumUp(ov?.servers ?? []) : ov?.servers[0];
|
||||
// Кого нет в сумме: сервер не отдал метрики (ok = false) или на связи, а рядов нет совсем (старый агент)
|
||||
const silent = !all || !ov ? [] : [
|
||||
...ov.servers.filter(r => !r.ok).map(r => r.name),
|
||||
...nodes.filter(n => n.online && !ov.servers.some(r => r.id === n.id)).map(n => n.health?.server || n.name),
|
||||
];
|
||||
const data = ov?.total ?? null;
|
||||
const cur = data && {
|
||||
// Скорость «сейчас» — от сервера: на неделе/месяце последняя точка ряда — среднее за шаг, а не текущее
|
||||
@@ -249,18 +171,30 @@ export default function MonitorPage({ token, showMsg }: PageProps) {
|
||||
const unit = peak >= 1e9 ? { name: 'Гбит/с', div: 1e9 } : peak >= 1e6 ? { name: 'Мбит/с', div: 1e6 } : peak >= 1e3 ? { name: 'Кбит/с', div: 1e3 } : { name: 'бит/с', div: 1 };
|
||||
const dashboard = status?.ready && (
|
||||
<>
|
||||
{/* Период — единственный фильтр: он задаёт окно для всего ниже */}
|
||||
<div className="mon-filters" role="group" aria-label="Период">
|
||||
{RANGES.map(([id, label]) => (
|
||||
<button key={id} type="button" className={`mon-range${range === id ? ' mon-range--on' : ''}`}
|
||||
aria-pressed={range === id} onClick={() => setRange(id)}>{label}</button>
|
||||
))}
|
||||
{/* Период слева задаёт окно для всего ниже; справа — чьи графики: кнопка и меню, как выбор
|
||||
сервера в шапке, «Все серверы» — сводка по всем */}
|
||||
<div className="mon-toolbar">
|
||||
<div className="mon-filters" role="group" aria-label="Период">
|
||||
{RANGES.map(([id, label]) => (
|
||||
<button key={id} type="button" className={`mon-range${range === id ? ' mon-range--on' : ''}`}
|
||||
aria-pressed={range === id} onClick={() => setRange(id)}>{label}</button>
|
||||
))}
|
||||
</div>
|
||||
{nodes.length > 0 && (
|
||||
<ServerSelect name="mon-server-menu" nodes={nodes} value={view} onChange={setView} all pickOffline />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{ovErr && <p className="login-error">{ovErr}</p>}
|
||||
{ov && !one?.ok && (
|
||||
{ov && !all && !one?.ok && (
|
||||
<p className="mon-hint mon-notice">Этот сервер сейчас не отдаёт метрики: графики могут быть неполными или пустыми.</p>
|
||||
)}
|
||||
{ov && all && (ov.servers.length === 0 || silent.length > 0) && (
|
||||
<p className="mon-hint mon-notice">
|
||||
{ov.servers.length === 0 ? 'Метрики сейчас не отдаёт ни один сервер.'
|
||||
: `Не отдают метрики: ${silent.join(', ')} — в сумме их нет.`}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mon-tiles">
|
||||
<div className="mon-tile">
|
||||
@@ -303,14 +237,14 @@ export default function MonitorPage({ token, showMsg }: PageProps) {
|
||||
<div className="mon-tile-meter">
|
||||
<span className="mon-tile-value mon-tile-rate">
|
||||
{one?.cpu != null ? `${nf(one.cpu, 0)} %` : '—'}
|
||||
<span className="mon-tile-sub">процессор{one?.cores ? ` · ${nf(one.cores, 0)} ядер` : ''}</span>
|
||||
<span className="mon-tile-sub">процессор{all ? ` · в среднем по ${ov?.servers.length ?? 0}` : one?.cores ? ` · ${nf(one.cores, 0)} ядер` : ''}</span>
|
||||
</span>
|
||||
<Bar v={one?.cpu} label="Загрузка процессора" />
|
||||
</div>
|
||||
<div className="mon-tile-meter">
|
||||
<span className="mon-tile-value mon-tile-rate">
|
||||
{one?.mem != null ? `${nf(one.mem, 0)} %` : '—'}
|
||||
<span className="mon-tile-sub">память{one?.mem_total ? ` · из ${gb(one.mem_total)}` : ''}</span>
|
||||
<span className="mon-tile-sub">память{all ? ` · в среднем по ${ov?.servers.length ?? 0}` : one?.mem_total ? ` · из ${gb(one.mem_total)}` : ''}</span>
|
||||
</span>
|
||||
<Bar v={one?.mem} label="Занято оперативной памяти" />
|
||||
</div>
|
||||
@@ -318,6 +252,33 @@ export default function MonitorPage({ token, showMsg }: PageProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Сводка по всем — и разбивка: кто сколько качает и насколько загружен */}
|
||||
{all && ov && ov.servers.length > 1 && (
|
||||
<section className="mon-chart mon-per-server" aria-labelledby="mon-per">
|
||||
<div className="mon-chart-head"><span className="mon-chart-title" id="mon-per">По серверам</span></div>
|
||||
<div className="mon-table-wrap">
|
||||
<table className="mon-table">
|
||||
<thead>
|
||||
<tr><th>Сервер</th><th>Загрузка</th><th>Отдача</th><th>Онлайн</th><th>Процессор</th><th>Память</th><th>Потрачено</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{ov.servers.map(r => (
|
||||
<tr key={r.id}>
|
||||
<td>{r.name}{!r.ok && <span className="mon-tile-sub"> · нет метрик</span>}</td>
|
||||
<td>{r.down != null ? rate(r.down) : '—'}</td>
|
||||
<td>{r.up != null ? rate(r.up) : '—'}</td>
|
||||
<td>{r.online != null ? nf(r.online, 0) : '—'}</td>
|
||||
<td>{r.cpu != null ? `${nf(r.cpu, 0)} %` : '—'}</td>
|
||||
<td>{r.mem != null ? `${nf(r.mem, 0)} %` : '—'}</td>
|
||||
<td>{r.used_down != null && r.used_up != null ? vol(r.used_down + r.used_up) : '—'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{ov && data && (
|
||||
<div className="mon-charts">
|
||||
<LineChart title={`Трафик, ${unit.name}`} from={ov.from} to={ov.to} step={ov.step} dim={loading}
|
||||
@@ -348,18 +309,9 @@ export default function MonitorPage({ token, showMsg }: PageProps) {
|
||||
|
||||
return (
|
||||
<>
|
||||
{server && (
|
||||
<p className="mon-server">
|
||||
<span className="mon-server-label">Сервер</span>
|
||||
<b>{server.health?.server || server.name}</b>
|
||||
<span className={`chip chip--${server.online ? 'online' : 'offline'}`}><span className="chip-dot" />{server.online ? 'на связи' : 'нет связи'}</span>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!status && <p className="mon-hint">Загрузка…</p>}
|
||||
{setup}
|
||||
{dashboard}
|
||||
{manage}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"icon": "pulse",
|
||||
"group": "server",
|
||||
"order": 1.7,
|
||||
"requires": "prometheus",
|
||||
"chrome": {
|
||||
"serverBar": false,
|
||||
"restart": false
|
||||
|
||||
@@ -8,25 +8,20 @@ LICENSE file in the root directory of this source tree.
|
||||
display: flex; flex-direction: column; gap: 12px;
|
||||
background: var(--surface-bright);
|
||||
border: 1px solid var(--outline-variant);
|
||||
border-radius: var(--r-card);
|
||||
border-radius: var(--shape-extra-large);
|
||||
padding: 20px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.mon-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
|
||||
.mon-title { margin: 0; font-size: 16px; font-weight: 500; color: var(--on-surface); }
|
||||
.mon-hint { margin: 0; font-size: 12px; color: var(--neutral-text); }
|
||||
.mon-title { margin: 0; font-size: var(--title-medium-size); line-height: var(--title-medium-line); font-weight: var(--weight-medium); color: var(--on-surface); }
|
||||
.mon-hint { margin: 0; font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.mon-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
|
||||
.mon-code {
|
||||
display: block; word-break: break-all; user-select: all;
|
||||
font-family: var(--mono); font-size: 12px; color: var(--on-surface);
|
||||
background: var(--surface-container);
|
||||
border-radius: var(--r-table);
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
@media (max-width: 599px) {
|
||||
.mon-actions .btn { flex: 1; }
|
||||
.mon-toolbar .server-select { flex: 1 1 100%; } /* своя строка под периодом */
|
||||
.mon-toolbar .server-current { width: 100%; }
|
||||
.mon-toolbar .server-menu { width: 100%; }
|
||||
}
|
||||
|
||||
/* ───── Графики ─────
|
||||
@@ -35,30 +30,31 @@ LICENSE file in the root directory of this source tree.
|
||||
:root { --series-1: #6a45b8; --series-2: #c4620a; }
|
||||
:root[data-theme="dark"] { --series-1: #8f6be0; --series-2: #d9772a; }
|
||||
|
||||
.mon-filters { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; }
|
||||
/* Строка над плитками: период слева, выбор сервера (components/ServerSelect) справа; на узком — друг под другом */
|
||||
.mon-toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px 16px; margin-bottom: 16px; }
|
||||
.mon-filters { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.mon-range {
|
||||
min-height: 44px; padding: 0 18px;
|
||||
font: inherit; font-size: 14px; color: var(--on-surface);
|
||||
font: inherit; font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--on-surface);
|
||||
background: var(--surface-bright);
|
||||
border: 1px solid var(--outline); border-radius: var(--r-pill);
|
||||
border: 1px solid var(--outline); border-radius: var(--shape-full);
|
||||
cursor: pointer;
|
||||
}
|
||||
.mon-range:hover { background: var(--state-primary); }
|
||||
.mon-range--on { background: var(--primary-container); color: var(--on-primary-container); border-color: transparent; font-weight: 500; }
|
||||
.mon-range--on { background: var(--primary-container); color: var(--on-primary-container); border-color: transparent; font-weight: var(--weight-medium); }
|
||||
|
||||
.mon-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(148px, 1fr)); gap: 12px; margin-bottom: 16px; }
|
||||
.mon-tile {
|
||||
display: flex; flex-direction: column; gap: 4px;
|
||||
background: var(--surface-bright);
|
||||
border: 1px solid var(--outline-variant); border-radius: var(--r-table);
|
||||
border: 1px solid var(--outline-variant); border-radius: var(--shape-large);
|
||||
padding: 14px 16px;
|
||||
}
|
||||
.mon-tile-label { font-size: 12px; color: var(--neutral-text); }
|
||||
.mon-tile-value { font-size: 20px; font-weight: 500; color: var(--on-surface); }
|
||||
.mon-tile-sub { font-size: 12px; color: var(--neutral-text); }
|
||||
.mon-tile-label { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.mon-tile-value { font-size: var(--title-large-size); line-height: var(--title-large-line); font-weight: var(--weight-medium); color: var(--on-surface); }
|
||||
.mon-tile-sub { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.mon-tile-rates { display: flex; flex-direction: column; gap: 10px; margin-top: 8px; }
|
||||
.mon-tile-rate { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 8px; white-space: nowrap; }
|
||||
.mon-tile-dir { font-size: 16px; }
|
||||
.mon-tile-dir { font-size: var(--body-large-size); line-height: var(--body-large-line); }
|
||||
.mon-tile-total { margin-top: 6px; padding-top: 10px; border-top: 1px solid var(--outline-variant); }
|
||||
.mon-tile-meter { display: flex; flex-direction: column; gap: 4px; }
|
||||
.mon-tile-dot { width: 8px; height: 8px; border-radius: 50%; flex: none; align-self: center; }
|
||||
@@ -71,78 +67,60 @@ LICENSE file in the root directory of this source tree.
|
||||
.mon-chart {
|
||||
margin: 0; min-width: 0;
|
||||
background: var(--surface-bright);
|
||||
border: 1px solid var(--outline-variant); border-radius: var(--r-card);
|
||||
border: 1px solid var(--outline-variant); border-radius: var(--shape-extra-large);
|
||||
padding: 16px;
|
||||
transition: opacity .15s;
|
||||
transition: opacity var(--duration-short3) var(--ease-standard);
|
||||
}
|
||||
.mon-chart--dim { opacity: .6; }
|
||||
.mon-chart-head { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 16px; margin-bottom: 4px; }
|
||||
.mon-chart-title { font-size: 15px; font-weight: 500; color: var(--on-surface); }
|
||||
.mon-legend { display: flex; flex-wrap: wrap; gap: 4px 14px; font-size: 12px; color: var(--neutral-text); }
|
||||
.mon-chart-title { font-size: var(--title-medium-size); line-height: var(--title-medium-line); font-weight: var(--weight-medium); color: var(--on-surface); }
|
||||
.mon-legend { display: flex; flex-wrap: wrap; gap: 4px 14px; font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.mon-legend-item { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.mon-key { display: inline-block; width: 14px; height: 3px; border-radius: 2px; flex: none; }
|
||||
.mon-key { display: inline-block; width: 14px; height: 3px; border-radius: var(--shape-extra-small); flex: none; }
|
||||
.mon-chart-toggle {
|
||||
margin-left: auto; min-height: 44px; padding: 0 12px;
|
||||
font: inherit; font-size: 13px; color: var(--on-primary-container);
|
||||
background: none; border: 0; border-radius: var(--r-pill); cursor: pointer;
|
||||
font: inherit; font-size: var(--label-large-size); line-height: var(--label-large-line); color: var(--on-primary-container);
|
||||
background: none; border: 0; border-radius: var(--shape-full); cursor: pointer;
|
||||
}
|
||||
.mon-chart-toggle:hover { background: var(--state-primary); }
|
||||
|
||||
.mon-plot { position: relative; }
|
||||
.mon-plot svg { display: block; max-width: 100%; }
|
||||
.mon-plot svg:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; border-radius: 8px; }
|
||||
.mon-plot svg:focus-visible { border-radius: var(--shape-small); }
|
||||
.mon-grid { stroke: var(--outline-variant); stroke-width: 1; }
|
||||
.mon-tick { fill: var(--neutral-text); font-size: 12px; font-family: var(--font); }
|
||||
.mon-tick { fill: var(--neutral-text); font-size: var(--body-small-size); font-family: var(--font); }
|
||||
.mon-cross { stroke: var(--outline); stroke-width: 1; }
|
||||
.mon-end { stroke: var(--surface-bright); stroke-width: 2px; }
|
||||
.mon-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; padding: 0 24px; text-align: center; font-size: 13px; color: var(--neutral-text); }
|
||||
.mon-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; padding: 0 24px; text-align: center; font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--neutral-text); }
|
||||
.mon-tip {
|
||||
position: absolute; pointer-events: none; z-index: 2;
|
||||
display: flex; flex-direction: column; gap: 4px;
|
||||
background: var(--surface-container);
|
||||
border: 1px solid var(--outline-variant); border-radius: 12px;
|
||||
padding: 8px 10px; font-size: 12px; color: var(--neutral-text);
|
||||
border: 1px solid var(--outline-variant); border-radius: var(--shape-medium);
|
||||
padding: 8px 10px; font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text);
|
||||
}
|
||||
.mon-tip-time { color: var(--neutral-text); }
|
||||
.mon-tip-row { display: flex; align-items: center; gap: 8px; }
|
||||
.mon-tip-row b { font-weight: 500; font-size: 13px; color: var(--on-surface); }
|
||||
.mon-tip-row b { font-weight: var(--weight-medium); font-size: var(--label-large-size); line-height: var(--label-large-line); color: var(--on-surface); }
|
||||
|
||||
.mon-table-wrap { overflow-x: auto; }
|
||||
.mon-table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||
.mon-table th { text-align: left; font-weight: 500; color: var(--label); padding: 8px 10px; white-space: nowrap; }
|
||||
.mon-table { width: 100%; border-collapse: collapse; font-size: var(--body-medium-size); line-height: var(--body-medium-line); }
|
||||
.mon-table th { text-align: left; font-weight: var(--weight-medium); color: var(--on-surface-variant); padding: 8px 10px; white-space: nowrap; }
|
||||
.mon-table td { padding: 8px 10px; color: var(--on-surface); border-top: .5px solid var(--outline-variant); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
|
||||
.mon-log {
|
||||
margin: 0; max-height: 240px; overflow: auto;
|
||||
font-family: var(--mono); font-size: 12px; color: var(--on-surface);
|
||||
background: var(--surface-container); border-radius: var(--r-table);
|
||||
padding: 12px; white-space: pre-wrap; word-break: break-word;
|
||||
}
|
||||
|
||||
.mon-notice { margin-bottom: 12px; }
|
||||
|
||||
/* Полоски процессора и памяти в плитках */
|
||||
.mon-bar { display: block; width: 100%; height: 8px; border-radius: 4px; overflow: hidden; background: var(--primary-container); margin: 2px 0; }
|
||||
.mon-bar i { display: block; height: 100%; border-radius: 4px; background: var(--series-1); transition: width .3s; }
|
||||
.mon-bar { display: block; width: 100%; height: 8px; border-radius: var(--shape-extra-small); overflow: hidden; background: var(--primary-container); margin: 2px 0; }
|
||||
.mon-bar i { display: block; height: 100%; border-radius: var(--shape-extra-small); background: var(--series-1); transition: width var(--duration-medium2) var(--ease-standard); }
|
||||
.mon-bar i.mon-bar--warn { background: var(--warn-dot); }
|
||||
.mon-bar i.mon-bar--bad { background: var(--error-dot); }
|
||||
|
||||
/* Какой сервер показан (выбирается в других вкладках) */
|
||||
.mon-server { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 12px; margin: 0 0 12px; font-size: 16px; color: var(--on-surface); }
|
||||
.mon-server b { font-weight: 500; }
|
||||
.mon-server-label { font-size: 12px; color: var(--neutral-text); }
|
||||
|
||||
|
||||
/* Прогресс операции рядом с кнопкой */
|
||||
|
||||
/* Разбивка «По серверам» в режиме «Все серверы» */
|
||||
.mon-per-server { margin-bottom: 16px; }
|
||||
|
||||
/* Кнопка рядом с подписью — по центру строки */
|
||||
.mon-actions { align-items: center; }
|
||||
.mon-progress { flex: 1; min-width: 200px; display: flex; flex-direction: column; gap: 6px; }
|
||||
.mon-progress-label { font-size: 12px; color: var(--neutral-text); }
|
||||
.mon-pbar { display: block; width: 100%; height: 8px; border-radius: 4px; overflow: hidden; background: var(--primary-container); }
|
||||
.mon-pbar i { display: block; height: 100%; border-radius: 4px; background: var(--series-1); transition: width .4s ease; }
|
||||
.mon-pbar--ok i { background: var(--success-dot); }
|
||||
.mon-pbar--bad i { background: var(--error-dot); }
|
||||
/* Шага ещё нет — ход неизвестен: бегущий отрезок вместо ложных процентов */
|
||||
.mon-pbar--wait i { width: 35% !important; animation: mon-wait 1.2s ease-in-out infinite; }
|
||||
@keyframes mon-wait { 0% { transform: translateX(-100%); } 100% { transform: translateX(290%); } }
|
||||
@media (prefers-reduced-motion: reduce) { .mon-pbar--wait i { animation: none; } .mon-pbar i { transition: none; } }
|
||||
|
||||
|
||||
+19
-16
@@ -8,11 +8,11 @@ LICENSE file in the root directory of this source tree.
|
||||
/* Открытый API-ключ (показывается один раз при создании) */
|
||||
.apikey-value {
|
||||
font-family: var(--mono);
|
||||
font-size: 13px;
|
||||
font-size: var(--body-medium-size); line-height: var(--body-medium-line);
|
||||
color: var(--on-surface);
|
||||
background: var(--surface-container);
|
||||
border: 1px solid var(--outline-variant);
|
||||
border-radius: 12px;
|
||||
border-radius: var(--shape-medium);
|
||||
padding: 12px 14px;
|
||||
width: 100%;
|
||||
word-break: break-all;
|
||||
@@ -21,9 +21,9 @@ LICENSE file in the root directory of this source tree.
|
||||
|
||||
.apikey-cards-list { display: none; flex-direction: column; gap: 12px; }
|
||||
|
||||
.apikey-count { font-size: 12px; color: var(--neutral-text); }
|
||||
.apikey-count { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.apikey-empty {
|
||||
font-size: 14px;
|
||||
font-size: var(--body-medium-size); line-height: var(--body-medium-line);
|
||||
color: var(--neutral-text);
|
||||
text-align: center;
|
||||
padding: 48px 0;
|
||||
@@ -31,7 +31,7 @@ LICENSE file in the root directory of this source tree.
|
||||
.apikey-card {
|
||||
background: var(--surface-bright);
|
||||
border: 1px solid var(--outline-variant);
|
||||
border-radius: var(--r-card);
|
||||
border-radius: var(--shape-extra-large);
|
||||
padding: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -49,10 +49,10 @@ LICENSE file in the root directory of this source tree.
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.apikey-card-num { font-size: 12px; color: var(--neutral-dot); flex-shrink: 0; }
|
||||
.apikey-card-num { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-dot); flex-shrink: 0; }
|
||||
.apikey-card-label {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
font-size: var(--title-medium-size); line-height: var(--title-medium-line);
|
||||
font-weight: var(--weight-medium);
|
||||
color: var(--on-surface);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -60,7 +60,7 @@ LICENSE file in the root directory of this source tree.
|
||||
}
|
||||
.apikey-card-prefix {
|
||||
font-family: var(--mono);
|
||||
font-size: 13px;
|
||||
font-size: var(--body-medium-size); line-height: var(--body-medium-line);
|
||||
color: var(--neutral-text);
|
||||
word-break: break-all;
|
||||
}
|
||||
@@ -68,12 +68,15 @@ LICENSE file in the root directory of this source tree.
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
font-size: var(--body-small-size); line-height: var(--body-small-line);
|
||||
color: var(--neutral-text);
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.apikey-cards-list { display: flex; }
|
||||
/* compact и medium (< 840px): карточки вместо таблицы, на планшете — сеткой */
|
||||
@media (max-width: 839px) {
|
||||
.apikey-cards-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); }
|
||||
/* счётчик и «пусто» — на всю строку сетки */
|
||||
:is(.apikey-count, .apikey-empty) { grid-column: 1 / -1; }
|
||||
}
|
||||
|
||||
/* Настройки ключа: какие серверы он видит */
|
||||
@@ -82,13 +85,13 @@ LICENSE file in the root directory of this source tree.
|
||||
display: flex; flex-direction: column; gap: 10px;
|
||||
background: var(--surface-bright);
|
||||
border: 1px solid var(--outline-variant);
|
||||
border-radius: 16px;
|
||||
border-radius: var(--shape-large);
|
||||
padding: 12px 16px 14px;
|
||||
margin: 6px 0 8px;
|
||||
}
|
||||
.apikey-tools-title { margin: 0; font-size: 13px; font-weight: 500; color: var(--label); }
|
||||
.apikey-tools-hint { margin: 0; font-size: 12px; color: var(--neutral-text); }
|
||||
.apikey-tools-title { margin: 0; font-size: var(--title-small-size); line-height: var(--title-small-line); font-weight: var(--weight-medium); color: var(--on-surface-variant); }
|
||||
.apikey-tools-hint { margin: 0; font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.apikey-card-btns { display: flex; gap: 8px; flex-shrink: 0; }
|
||||
.apikey-card-servers { font-size: 12px; color: var(--neutral-text); }
|
||||
.apikey-card-servers { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
|
||||
.apikey-new-servers { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; margin: 0 0 16px; }
|
||||
@@ -2,15 +2,15 @@
|
||||
// This source code is licensed under the MIT license found in the
|
||||
// LICENSE file in the root directory of this source tree.
|
||||
import { Fragment, useState, useEffect, useCallback } from 'react';
|
||||
import { apiFetch, copyText, timeAgo, getServerId, type ApiKey, type NodeInfo, type PageProps } from '../../lib/shared';
|
||||
import { IcoPlus, IcoTrash, IcoCopy, IcoSettings } from '../../components/icons';
|
||||
import ServerPicker, { serverName } from '../../components/ServerPicker';
|
||||
import { apiFetch, copyText, timeAgo, getServerId, type ApiKey, type NodeInfo, type PageProps } from '../../../lib/shared';
|
||||
import { IcoPlus, IcoTrash, IcoCopy, IcoSettings } from '../../../components/icons';
|
||||
import ServerPicker, { serverName } from '../../../components/ServerPicker';
|
||||
import './apikeys.css';
|
||||
|
||||
// Вкладка «API-ключи»: ключи внешнего API (/api/v1). Открытый ключ показывается
|
||||
// один раз при создании (в БД хранится только хэш). Сервер-бар сверху рендерит App.
|
||||
// один раз при создании (в БД хранится только хэш). Раздел вкладки «Настройки».
|
||||
// Ключ видит набор серверов: на них он заводит vpn://-пользователей и в их пределах
|
||||
// управляет мастер-ключами. Создаётся на выбранном в сервер-баре сервере, набор
|
||||
// управляет мастер-ключами. По умолчанию новый ключ видит выбранный в панели сервер, набор
|
||||
// правится в настройках ключа.
|
||||
export default function ApiKeysPage({ token, showMsg }: PageProps) {
|
||||
const [keys, setKeys] = useState<ApiKey[]>([]);
|
||||
@@ -18,7 +18,7 @@ export default function ApiKeysPage({ token, showMsg }: PageProps) {
|
||||
const [label, setLabel] = useState('');
|
||||
const [created, setCreated] = useState<{ label: string; key: string } | null>(null);
|
||||
const [tools, setTools] = useState<number | null>(null); // ключ с открытыми настройками
|
||||
const [picked, setPicked] = useState<number[] | null>(null); // серверы нового ключа; null — только выбранный в сервер-баре
|
||||
const [picked, setPicked] = useState<number[] | null>(null); // серверы нового ключа; null — только выбранный в панели
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
@@ -77,7 +77,6 @@ export default function ApiKeysPage({ token, showMsg }: PageProps) {
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Сервер-бар сверху рендерит App; новый ключ получает выбранный в нём сервер. */}
|
||||
<div className="toolbar">
|
||||
<input
|
||||
className="field"
|
||||
@@ -194,11 +193,11 @@ export default function ApiKeysPage({ token, showMsg }: PageProps) {
|
||||
</p>
|
||||
<code className="apikey-value">{created.key}</code>
|
||||
<div className="qr-actions">
|
||||
<button className="btn btn--text" onClick={() => setCreated(null)}>Закрыть</button>
|
||||
<button className="btn btn--primary" onClick={async () => {
|
||||
await copyText(created.key);
|
||||
showMsg('Ключ скопирован');
|
||||
}}><IcoCopy /> Скопировать</button>
|
||||
<button className="btn btn--tonal" onClick={() => setCreated(null)}>Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -7,33 +7,33 @@ LICENSE file in the root directory of this source tree.
|
||||
|
||||
.au-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
|
||||
.au-run { margin-left: auto; }
|
||||
.au-hint { font-size: 13px; color: var(--neutral-text); }
|
||||
.au-hint { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.au-notice {
|
||||
font-size: 13px; color: var(--error-text); background: var(--error-bg);
|
||||
border-radius: 16px; padding: 10px 16px; margin: 0;
|
||||
font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--on-error-container); background: var(--error-container);
|
||||
border-radius: var(--shape-large); padding: 10px 16px; margin: 0;
|
||||
}
|
||||
.au-empty { font-size: 14px; color: var(--neutral-text); text-align: center; padding: 48px 0; }
|
||||
.au-pub { display: inline-block; max-width: 340px; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; font-family: var(--mono); font-size: 12px; }
|
||||
.au-empty { font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--neutral-text); text-align: center; padding: 48px 0; }
|
||||
.au-pub { display: inline-block; max-width: 340px; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; font-family: var(--mono); font-size: var(--body-small-size); line-height: var(--body-small-line); }
|
||||
.au-table td, .au-table th { white-space: nowrap; }
|
||||
|
||||
/* мобильный: таблица скрыта (.table-card), то же — карточками */
|
||||
.au-cards { list-style: none; margin: 0; padding: 0; display: none; flex-direction: column; gap: 8px; }
|
||||
.au-card { display: flex; flex-direction: column; gap: 4px; background: var(--surface-container); border-radius: 16px; padding: 12px 16px; }
|
||||
.au-card { display: flex; flex-direction: column; gap: 4px; background: var(--surface-container); border-radius: var(--shape-large); padding: 12px 16px; }
|
||||
.au-card-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.au-card .au-pub { max-width: 100%; }
|
||||
@media (max-width: 640px) { .au-cards { display: flex; } }
|
||||
@media (max-width: 839px) { .au-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); } }
|
||||
|
||||
.au-btns { display: flex; flex-wrap: wrap; gap: 8px; margin-left: auto; }
|
||||
.au-run { margin-left: 0; }
|
||||
|
||||
.au-box { display: flex; flex-direction: column; gap: 10px; background: var(--surface-container); border-radius: 16px; padding: 12px 16px; }
|
||||
.au-box-title { margin: 0; font-size: 14px; font-weight: 500; }
|
||||
.au-box { display: flex; flex-direction: column; gap: 10px; background: var(--surface-container); border-radius: var(--shape-large); padding: 12px 16px; }
|
||||
.au-box-title { margin: 0; font-size: var(--title-small-size); line-height: var(--title-small-line); font-weight: var(--weight-medium); }
|
||||
.au-setting { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.au-setting-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.au-setting-name { font-size: 14px; }
|
||||
.au-setting-name { font-size: var(--body-medium-size); line-height: var(--body-medium-line); }
|
||||
.au-setting-ctl { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.au-max { width: 88px !important; }
|
||||
.au-select { width: auto !important; }
|
||||
.au-log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||
.au-log li { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; font-size: 13px; }
|
||||
.au-log li { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; font-size: var(--body-medium-size); line-height: var(--body-medium-line); }
|
||||
.au-log .au-pub { max-width: 240px; }
|
||||
@@ -2,12 +2,12 @@
|
||||
// This source code is licensed under the MIT license found in the
|
||||
// LICENSE file in the root directory of this source tree.
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { apiFetch, timeAgo, type NodeInfo, type PageProps } from '../../lib/shared';
|
||||
import { IcoRefresh, IcoTrash } from '../../components/icons';
|
||||
import { serverName } from '../../components/ServerPicker';
|
||||
import { apiFetch, timeAgo, type NodeInfo, type PageProps } from '../../../lib/shared';
|
||||
import { IcoRefresh, IcoTrash } from '../../../components/icons';
|
||||
import { serverName } from '../../../components/ServerPicker';
|
||||
import './audit.css';
|
||||
|
||||
// Вкладка «Аудит»: core периодически обходит все серверы и ищет «мёртвых» пиров — живых на сервере,
|
||||
// Раздел «Аудит» вкладки «Настройки»: core периодически обходит все серверы и ищет «мёртвых» пиров — живых на сервере,
|
||||
// хотя панель про них не знает (мастер-ключ удалён, а пир остался). Снимает только подтверждённых
|
||||
// (мёртвых два прохода подряд): автоматически, если включено в настройках, или кнопкой.
|
||||
// Отчёт и очистку считает awg-ui/sub.ts (/ui/masterkeys/audit*).
|
||||
@@ -96,7 +96,7 @@ export default function AuditPage({ token, showMsg }: PageProps) {
|
||||
</section>
|
||||
|
||||
<section className="au-box">
|
||||
<h4 className="au-box-title">Настройки</h4>
|
||||
<h4 className="au-box-title">Параметры аудита</h4>
|
||||
<label className="au-setting">
|
||||
<span className="au-setting-text">
|
||||
<span className="au-setting-name">Снимать мёртвых автоматически</span>
|
||||
@@ -0,0 +1,285 @@
|
||||
// Copyright (c) 2026 Ivan Vasilev
|
||||
// This source code is licensed under the MIT license found in the
|
||||
// LICENSE file in the root directory of this source tree.
|
||||
import { useState, useEffect, useLayoutEffect, useCallback, useRef } from 'react';
|
||||
import axios from 'axios';
|
||||
import { apiFetch, copyText, timeAgo, BRAND_FALLBACK, SETTINGS_SECTION_KEY, type Brand, type NodeInfo, type PageProps } from '../../lib/shared';
|
||||
import { useTheme, setThemeMode, type ThemeMode } from '../../lib/theme';
|
||||
import { IcoCheck, IcoCopy, IcoRefresh, IcoTrash, IcoPlus } from '../../components/icons';
|
||||
import ApiKeysPage from './apikeys';
|
||||
import AuditPage from './audit';
|
||||
import MigratePage from './migrate';
|
||||
import PrometheusInstall from './prometheus';
|
||||
import ServerSettings from './server';
|
||||
import './settings.css';
|
||||
|
||||
// Вкладка «Настройки»: настройки самой панели, не конкретного сервера (те — в меню серверов).
|
||||
// Разделы — по вкладкам MD3 (primary tabs) сверху, виден один:
|
||||
// Оформление — тема (хранится в браузере, lib/theme).
|
||||
// Сервер — деление канала и блокировка торрентов сервера из шапки (./server; туда ведёт и шестерёнка
|
||||
// в меню серверов).
|
||||
// API-ключи, Аудит, Перенос — бывшие отдельные вкладки меню; живут в подпапках и
|
||||
// рендерятся здесь целиком (реестр tabs/index.ts их не видит — он ищет на уровень выше).
|
||||
// Prometheus — установка встроенного Prometheus (./prometheus) и токен «только метрики» для GET /metrics (/ui/metrics-token): выпуск,
|
||||
// перевыпуск, отзыв. Значение показывается один раз, в БД — только хэш.
|
||||
// О панели — имя, канал, версия и серверы.
|
||||
interface MetricsToken {
|
||||
exists: boolean;
|
||||
prefix?: string;
|
||||
created_at?: number;
|
||||
last_used?: number | null;
|
||||
per_peer: boolean; // пер-пировые серии (METRICS_PEERS=on в .env)
|
||||
}
|
||||
|
||||
const SECTIONS = [
|
||||
{ id: 'look', label: 'Оформление' },
|
||||
{ id: 'server', label: 'Сервер' },
|
||||
{ id: 'apikeys', label: 'API-ключи' },
|
||||
{ id: 'prom', label: 'Prometheus' },
|
||||
{ id: 'audit', label: 'Аудит' },
|
||||
{ id: 'migrate', label: 'Перенос' },
|
||||
{ id: 'about', label: 'О панели' },
|
||||
] as const;
|
||||
type SectionId = (typeof SECTIONS)[number]['id'];
|
||||
|
||||
// Открытый раздел помнится в браузере — чтобы «Аудит» или «Перенос» не искать заново
|
||||
// (туда же пишет openTab из lib/shared, когда другая вкладка ведёт в нужный раздел)
|
||||
const indexOf = (id: SectionId) => SECTIONS.findIndex(t => t.id === id);
|
||||
function savedSection(): SectionId {
|
||||
try {
|
||||
const v = localStorage.getItem(SETTINGS_SECTION_KEY);
|
||||
if (SECTIONS.some(t => t.id === v)) return v as SectionId;
|
||||
} catch { /* не критично */ }
|
||||
return 'look';
|
||||
}
|
||||
|
||||
const THEMES: { id: ThemeMode; label: string }[] = [
|
||||
{ id: 'light', label: 'Светлая' },
|
||||
{ id: 'dark', label: 'Тёмная' },
|
||||
{ id: 'system', label: 'Как в системе' },
|
||||
];
|
||||
|
||||
export default function SettingsPage({ token, showMsg }: PageProps) {
|
||||
const { mode } = useTheme();
|
||||
const [metrics, setMetrics] = useState<MetricsToken | null>(null);
|
||||
const [created, setCreated] = useState<string | null>(null); // открытый токен — один раз после выпуска
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [brand, setBrand] = useState<Brand>({ brand: BRAND_FALLBACK, channel: '', version: '' });
|
||||
const [nodes, setNodes] = useState<NodeInfo[]>([]);
|
||||
// dir — откуда въезжает раздел: 1 — справа (вкладка правее прежней), -1 — слева, 0 — первый показ
|
||||
const [view, setView] = useState<{ section: SectionId; dir: number }>(() => ({ section: savedSection(), dir: 0 }));
|
||||
const section = view.section;
|
||||
const go = (id: SectionId) => setView(v => v.section === id ? v : { section: id, dir: Math.sign(indexOf(id) - indexOf(v.section)) });
|
||||
const tabRefs = useRef<Partial<Record<SectionId, HTMLButtonElement | null>>>({});
|
||||
const indicator = useRef<HTMLSpanElement>(null);
|
||||
const centered = useRef(false); // первый показ — без анимации прокрутки вкладок
|
||||
|
||||
// Индикатор — одна полоса под активной вкладкой: переезжает к ней, а не появляется заново
|
||||
useLayoutEffect(() => {
|
||||
const place = () => {
|
||||
const b = tabRefs.current[section], el = indicator.current;
|
||||
if (b && el) { el.style.left = `${b.offsetLeft}px`; el.style.width = `${b.offsetWidth}px`; }
|
||||
};
|
||||
place();
|
||||
// На узком экране вкладки прокручиваются — выбранную ставим по центру полосы (у краёв — насколько
|
||||
// позволяет прокрутка). Двигаем саму полосу, а не scrollIntoView: тот прокрутил бы и страницу.
|
||||
const b = tabRefs.current[section], bar = b?.parentElement;
|
||||
if (b && bar && bar.scrollWidth > bar.clientWidth) {
|
||||
const still = !centered.current || matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
bar.scrollTo({ left: b.offsetLeft - (bar.clientWidth - b.offsetWidth) / 2, behavior: still ? 'auto' : 'smooth' });
|
||||
}
|
||||
centered.current = true;
|
||||
try { localStorage.setItem(SETTINGS_SECTION_KEY, section); } catch { /* не критично */ }
|
||||
window.addEventListener('resize', place);
|
||||
return () => window.removeEventListener('resize', place);
|
||||
}, [section]);
|
||||
|
||||
// openTab('settings', раздел) при уже открытых настройках: раздел записан в localStorage — переключаемся на него
|
||||
useEffect(() => {
|
||||
const h = (e: Event) => { if ((e as CustomEvent).detail === 'settings') go(savedSection()); };
|
||||
window.addEventListener('awg:open-tab', h);
|
||||
return () => window.removeEventListener('awg:open-tab', h);
|
||||
}, []);
|
||||
|
||||
// Стрелки, Home/End — по вкладкам (MD3 / WAI-ARIA tabs)
|
||||
const onTabKey = (e: React.KeyboardEvent) => {
|
||||
const i = indexOf(section);
|
||||
const j = e.key === 'ArrowRight' ? (i + 1) % SECTIONS.length
|
||||
: e.key === 'ArrowLeft' ? (i + SECTIONS.length - 1) % SECTIONS.length
|
||||
: e.key === 'Home' ? 0 : e.key === 'End' ? SECTIONS.length - 1 : -1;
|
||||
if (j < 0) return;
|
||||
e.preventDefault();
|
||||
go(SECTIONS[j].id);
|
||||
tabRefs.current[SECTIONS[j].id]?.focus();
|
||||
};
|
||||
|
||||
// Адрес /metrics рядом с панелью — с учётом префикса, под которым она открыта
|
||||
const metricsUrl = new URL('metrics', location.href.split(/[?#]/)[0]).href;
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setMetrics(await apiFetch('GET', '/ui/metrics-token', token));
|
||||
} catch {
|
||||
showMsg('Ошибка загрузки настроек');
|
||||
}
|
||||
axios.get('/ui/brand').then(({ data }) => setBrand({
|
||||
brand: data.brand || BRAND_FALLBACK, channel: data.channel || '', version: data.version || '',
|
||||
})).catch(() => {});
|
||||
apiFetch('GET', '/ui/nodes', token).then(r => setNodes(r.nodes ?? [])).catch(() => {});
|
||||
}, [token, showMsg]);
|
||||
|
||||
useEffect(() => { if (token) load(); }, [token, load]);
|
||||
|
||||
const issue = useCallback(async () => {
|
||||
if (metrics?.exists && !confirm('Перевыпустить токен? Старый сразу перестанет работать — Prometheus нужно будет перенастроить.')) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await apiFetch('POST', '/ui/metrics-token', token);
|
||||
setCreated(r.token);
|
||||
setMetrics(r);
|
||||
} catch (e: any) {
|
||||
showMsg(e?.response?.data?.error ?? 'Ошибка запроса');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [metrics, token, showMsg]);
|
||||
|
||||
const revoke = useCallback(async () => {
|
||||
if (!confirm('Отозвать токен? Prometheus перестанет получать метрики панели.')) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
setMetrics(await apiFetch('DELETE', '/ui/metrics-token', token));
|
||||
showMsg('Токен отозван');
|
||||
} catch (e: any) {
|
||||
showMsg(e?.response?.data?.error ?? 'Ошибка запроса');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [token, showMsg]);
|
||||
|
||||
const online = nodes.filter(n => n.online).length;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="st-tabs" role="tablist" aria-label="Разделы настроек" onKeyDown={onTabKey}>
|
||||
{SECTIONS.map(t => (
|
||||
<button key={t.id} type="button" role="tab" id={`st-tab-${t.id}`} className="st-tab"
|
||||
aria-selected={section === t.id} aria-controls={`st-panel-${t.id}`}
|
||||
tabIndex={section === t.id ? 0 : -1}
|
||||
ref={el => { tabRefs.current[t.id] = el; }} onClick={() => go(t.id)}>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
<span className="st-tabs-indicator" ref={indicator} aria-hidden="true" />
|
||||
</div>
|
||||
|
||||
{/* Раздел пересоздаётся при смене (key) и въезжает со стороны выбранной вкладки */}
|
||||
<div key={section} className="st-view" role="tabpanel" id={`st-panel-${section}`} aria-labelledby={`st-tab-${section}`}
|
||||
style={{ '--st-dir': view.dir } as React.CSSProperties}>
|
||||
{section === 'look' && (
|
||||
<section className="st-section">
|
||||
<div className="st-row">
|
||||
<span className="st-row-text">
|
||||
<span className="st-row-name">Тема</span>
|
||||
<span className="st-hint">Запоминается в этом браузере</span>
|
||||
</span>
|
||||
<div className="segmented" role="radiogroup" aria-label="Тема">
|
||||
{THEMES.map(t => (
|
||||
<button key={t.id} type="button" role="radio" aria-checked={mode === t.id}
|
||||
className="segmented-item" onClick={() => setThemeMode(t.id)}>
|
||||
{mode === t.id && <IcoCheck />}{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{section === 'prom' && <PrometheusInstall token={token} showMsg={showMsg} />}
|
||||
|
||||
{section === 'prom' && (
|
||||
<section className="st-section">
|
||||
<p className="st-hint st-lead">
|
||||
Метрики панели и всех серверов отдаются по адресу <code className="st-code">{metricsUrl}</code> только
|
||||
с токеном: Prometheus передаёт его заголовком <code className="st-code">Authorization: Bearer</code>.
|
||||
Токен открывает только метрики — ни панель, ни API.
|
||||
</p>
|
||||
<div className="st-row">
|
||||
<span className="st-row-text">
|
||||
<span className="st-row-name">Токен метрик</span>
|
||||
{metrics?.exists ? (
|
||||
<span className="st-hint">
|
||||
<code className="st-code">{metrics.prefix}</code> · выпущен {new Date((metrics.created_at ?? 0) * 1000).toLocaleDateString()}
|
||||
{' · '}{metrics.last_used ? `скрейп ${timeAgo(metrics.last_used)} назад` : 'ещё не использовался'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="st-hint">{metrics ? 'Не выпущен — /metrics закрыт' : 'Загрузка…'}</span>
|
||||
)}
|
||||
</span>
|
||||
{metrics && (
|
||||
<span className="st-row-ctl">
|
||||
{metrics.exists && (
|
||||
<button className="btn btn--danger" disabled={busy} onClick={revoke}><IcoTrash /> Отозвать</button>
|
||||
)}
|
||||
<button className={`btn ${metrics.exists ? 'btn--tonal' : 'btn--primary'}`} disabled={busy} onClick={issue}>
|
||||
{metrics.exists ? <><IcoRefresh /> Перевыпустить</> : <><IcoPlus /> Выпустить</>}
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{metrics && (
|
||||
<div className="st-row">
|
||||
<span className="st-row-text">
|
||||
<span className="st-row-name">Метрики по пользователям</span>
|
||||
<span className="st-hint">
|
||||
{metrics.per_peer
|
||||
? 'Включены: серии по каждому пиру с внутренним IP и именем'
|
||||
: 'Выключены. Включаются строкой METRICS_PEERS=on в .env панели'}
|
||||
</span>
|
||||
</span>
|
||||
<span className={`chip chip--${metrics.per_peer ? 'online' : 'offline'}`}>
|
||||
<span className="chip-dot" />{metrics.per_peer ? 'Вкл' : 'Выкл'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{section === 'server' && <ServerSettings token={token} showMsg={showMsg} />}
|
||||
{section === 'apikeys' && <ApiKeysPage token={token} showMsg={showMsg} />}
|
||||
{section === 'audit' && <AuditPage token={token} showMsg={showMsg} />}
|
||||
{section === 'migrate' && <MigratePage token={token} showMsg={showMsg} />}
|
||||
|
||||
{section === 'about' && (
|
||||
<section className="st-section">
|
||||
<dl className="st-facts">
|
||||
<div><dt>Панель</dt><dd>{brand.brand}</dd></div>
|
||||
<div><dt>Версия</dt><dd>{[brand.channel, brand.version].filter(Boolean).join(' ') || '—'}</dd></div>
|
||||
<div><dt>Серверы</dt><dd>{nodes.length ? `${nodes.length}, на связи ${online}` : '—'}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{created && (
|
||||
<div className="qr-backdrop" onClick={() => setCreated(null)}>
|
||||
<div className="qr-card" role="dialog" aria-modal="true" aria-labelledby="st-new-title" onClick={e => e.stopPropagation()}>
|
||||
<p className="qr-name" id="st-new-title">Токен метрик выпущен</p>
|
||||
<p className="qr-hint">
|
||||
Скопируй его сейчас — он показывается один раз. В prometheus.yml он идёт
|
||||
в <code className="st-code">authorization.credentials</code>.
|
||||
</p>
|
||||
<code className="st-secret">{created}</code>
|
||||
<div className="qr-actions">
|
||||
<button className="btn btn--text" onClick={() => setCreated(null)}>Закрыть</button>
|
||||
<button className="btn btn--primary" onClick={async () => {
|
||||
await copyText(created);
|
||||
showMsg('Токен скопирован');
|
||||
}}><IcoCopy /> Скопировать</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"id": "settings",
|
||||
"label": "Настройки",
|
||||
"icon": "settings",
|
||||
"group": "server",
|
||||
"order": 9,
|
||||
"chrome": {
|
||||
"restart": false
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,11 @@
|
||||
// This source code is licensed under the MIT license found in the
|
||||
// LICENSE file in the root directory of this source tree.
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { apiFetch, copyText, type PageProps } from '../../lib/shared';
|
||||
import { IcoCopy } from '../../components/icons';
|
||||
import { apiFetch, copyText, type PageProps } from '../../../lib/shared';
|
||||
import { IcoCopy } from '../../../components/icons';
|
||||
import './migrate.css';
|
||||
|
||||
// Вкладка «Перенос»: панель уезжает с сервера «панель + VPN» на отдельную панель без VPN, а
|
||||
// Раздел «Перенос» вкладки «Настройки»: панель уезжает с сервера «панель + VPN» на отдельную панель без VPN, а
|
||||
// старый сервер остаётся её нодой #0. Новая панель выдаёт одноразовый код, старая по нему сама
|
||||
// отправляет туда базу и ключи подписки — у пользователей не меняется ничего. Логика — в
|
||||
// internal/ui/migrate.go (/ui/migrate*), порядок — docs/node-protocol.md, «Перенос панели».
|
||||
@@ -160,7 +160,7 @@ export default function MigratePage({ token, showMsg }: PageProps) {
|
||||
</p>
|
||||
<ol className="mv-steps">
|
||||
<li>На новом сервере установите Forgetting с ролью «только панель».</li>
|
||||
<li>Там на вкладке «Перенос» нажмите «Получить код».</li>
|
||||
<li>Там в «Настройках», на вкладке «Перенос», нажмите «Получить код».</li>
|
||||
<li>Вставьте код сюда и нажмите «Перенести».</li>
|
||||
</ol>
|
||||
{info.state === 'uncertain' ? (
|
||||
@@ -190,7 +190,7 @@ export default function MigratePage({ token, showMsg }: PageProps) {
|
||||
info.code ? (
|
||||
<>
|
||||
<p className="mv-text">
|
||||
Вставьте код на вкладке «Перенос» старой панели. Он одноразовый и действует
|
||||
Вставьте код в «Настройках» старой панели, на вкладке «Перенос». Он одноразовый и действует
|
||||
ещё {Math.max(1, Math.round(info.code.expires_in / 60))} мин. Архив придёт зашифрованным ключом из кода.
|
||||
</p>
|
||||
<code className="node-modal-cmd">{info.code.code}</code>
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
Copyright (c) 2026 Ivan Vasilev
|
||||
This source code is licensed under the MIT license found in the
|
||||
LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
/* Стили вкладки «Перенос». Общая дизайн-система — в App.css. */
|
||||
|
||||
.mv-box { display: flex; flex-direction: column; gap: 10px; background: var(--surface-container); border-radius: var(--shape-large); padding: 12px 16px; }
|
||||
.mv-title { margin: 0; font-size: var(--title-small-size); line-height: var(--title-small-line); font-weight: var(--weight-medium); }
|
||||
.mv-text { margin: 0; font-size: var(--body-medium-size); line-height: 1.5; }
|
||||
.mv-muted { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.mv-steps { margin: 0; padding-left: 20px; font-size: var(--body-medium-size); line-height: 1.6; }
|
||||
.mv-row { display: flex; gap: 8px; }
|
||||
.mv-row .field { flex: 1; min-width: 0; font-family: var(--mono); font-size: var(--body-small-size); line-height: var(--body-small-line); }
|
||||
.mv-row--end { justify-content: flex-end; flex-wrap: wrap; }
|
||||
.mv-self { align-self: flex-start; }
|
||||
.mv-notice {
|
||||
font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--on-error-container); background: var(--error-container);
|
||||
border-radius: var(--shape-large); padding: 10px 16px; margin: 0;
|
||||
}
|
||||
.mv-box .node-modal-cmd { background: var(--surface-bright); }
|
||||
@media (max-width: 599px) { .mv-row:not(.mv-row--end) { flex-direction: column; } }
|
||||
.mv-checks { display: flex; flex-direction: column; gap: 8px; }
|
||||
.mv-check { display: flex; align-items: baseline; gap: 10px; font-size: var(--body-medium-size); line-height: 1.5; }
|
||||
.mv-check .chip { flex-shrink: 0; }
|
||||
@@ -0,0 +1,141 @@
|
||||
// Copyright (c) 2026 Ivan Vasilev
|
||||
// This source code is licensed under the MIT license found in the
|
||||
// LICENSE file in the root directory of this source tree.
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { apiFetch, copyText, getServerId, announcePrometheus, type PageProps } from '../../../lib/shared';
|
||||
import { IcoCopy, IcoPlus, IcoTrash } from '../../../components/icons';
|
||||
import './prometheus.css';
|
||||
|
||||
// Установка встроенного Prometheus (раздел «Prometheus» вкладки «Настройки»; графики — во вкладке «Монитор»).
|
||||
// Кнопка просит awg-ctrl сервера поставить его (`awg-ctrl monitor install`, root; сама панель пакетов
|
||||
// не ставит). У панели без VPN он ставится на ноду, и панель читает его через её агента — на сервер,
|
||||
// выбранный в шапке (при смене сервера вкладка перемонтируется). У панели со своим VPN цель всегда
|
||||
// «этот сервер».
|
||||
export interface MonitorStatus {
|
||||
ready: boolean; can_install: boolean; command: string;
|
||||
host: { id: number; name: string } | null; // Prometheus на ноде (или будет поставлен туда); null — на этом сервере
|
||||
job: { action: 'install' | 'remove'; running: boolean; exit: number | null; log: string } | null; // последняя операция
|
||||
}
|
||||
|
||||
// Прогресс операции из строк «N/M шаг», которые печатает сам установщик (cli/src/monitor.ts). Шаг N считаем
|
||||
// выполненным наполовину: так полоска не стоит на нуле, пока идёт долгий apt, и не обещает больше, чем известно.
|
||||
const STEP = /^(\d+)\/(\d+)\s+(.+)$/;
|
||||
function JobProgress({ job, starting }: { job: MonitorStatus['job']; starting: boolean }) {
|
||||
let step: [number, number, string] | null = null;
|
||||
for (const l of job?.log.split('\n') ?? []) { const m = STEP.exec(l.trim()); if (m) step = [Number(m[1]), Number(m[2]), m[3]]; }
|
||||
const failed = !!job && job.exit !== null && job.exit !== 0;
|
||||
const done = !!job && job.exit === 0;
|
||||
const pct = done ? 100 : step ? ((step[0] - 0.5) / step[1]) * 100 : 0;
|
||||
const label = failed ? `Не удалось (код ${job!.exit})`
|
||||
: done ? (job!.action === 'install' ? 'Готово' : 'Удалено')
|
||||
: step ? `Шаг ${step[0]} из ${step[1]}: ${step[2]}` : 'Запуск…';
|
||||
return (
|
||||
<div className="prom-progress" aria-live="polite">
|
||||
<span className={`prom-pbar${failed ? ' prom-pbar--bad' : done ? ' prom-pbar--ok' : !step && (starting || job?.running) ? ' prom-pbar--wait' : ''}`}
|
||||
role="progressbar" aria-label="Ход операции" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(pct)}>
|
||||
<i style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
<span className="st-hint">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PrometheusInstall({ token, showMsg }: PageProps) {
|
||||
const target = getServerId() ?? 0; // куда ставить (панель без VPN) — сервер из шапки
|
||||
const [status, setStatus] = useState<MonitorStatus | null>(null);
|
||||
const [pending, setPending] = useState<'install' | 'remove' | null>(null); // операция запущена отсюда
|
||||
const alive = useRef(true);
|
||||
// StrictMode монтирует эффект дважды: флаг надо вернуть в true, иначе все ответы отбрасываются
|
||||
useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
|
||||
|
||||
const loadStatus = useCallback(async () => {
|
||||
try { const s = await apiFetch('GET', `/ui/monitor?server=${target}`, token) as MonitorStatus; announcePrometheus(s.ready); if (alive.current) setStatus(s); return s; }
|
||||
catch { return null; }
|
||||
}, [token, target]);
|
||||
|
||||
useEffect(() => { void loadStatus(); }, [loadStatus]);
|
||||
|
||||
// Пока идёт установка или удаление — следим за ходом: раз в 2 с читаем статус и лог
|
||||
useEffect(() => {
|
||||
if (!pending && !status?.job?.running) return;
|
||||
const t = setInterval(async () => {
|
||||
const s = await loadStatus();
|
||||
if (s && !s.job?.running) setPending(null);
|
||||
}, 2000);
|
||||
return () => clearInterval(t);
|
||||
}, [pending, status?.job?.running, loadStatus]);
|
||||
|
||||
const run = async (action: 'install' | 'remove') => {
|
||||
if (action === 'remove' && !confirm('Удалить Prometheus? Он будет остановлен, а накопленные графики (до 31 дня) сотрутся. Панель продолжит отдавать /metrics.')) return;
|
||||
setPending(action);
|
||||
try { await apiFetch('POST', `/ui/monitor/${action}?server=${target}`, token); await loadStatus(); }
|
||||
catch (e: any) { setPending(null); showMsg(e?.response?.data?.error ?? (action === 'install' ? 'Не удалось запустить установку' : 'Не удалось запустить удаление')); }
|
||||
};
|
||||
|
||||
if (!status) return <section className="st-section"><p className="st-hint">Загрузка…</p></section>;
|
||||
|
||||
const job = status.job;
|
||||
const working = !!pending || !!job?.running;
|
||||
const doing = pending ?? (job?.running ? job.action : null);
|
||||
const showJob = !!pending || (!!job && (job.running || job.exit !== null));
|
||||
const failed = !!job && job.exit !== null && job.exit !== 0;
|
||||
// «Этот сервер» путал: в шапке может быть выбрана нода, а Prometheus у панели один и стоит не там
|
||||
const where = status.host ? <>на сервере <b>{status.host.name}</b></> : 'на сервере панели';
|
||||
const command = status.ready ? 'awg-ctrl monitor remove' : status.command;
|
||||
|
||||
return (
|
||||
<section className="st-section">
|
||||
<div className="st-row">
|
||||
<span className="st-row-text">
|
||||
<span className="st-row-name">Встроенный Prometheus</span>
|
||||
<span className="st-hint">
|
||||
{status.ready
|
||||
? <>Один на всю панель, собирает метрики всех серверов. Стоит {where}{status.host && ' (панель читает его через агента ноды)'}, слушает только 127.0.0.1:9090, графики хранит 31 день.</>
|
||||
: <>Один на всю панель, соберёт метрики всех серверов. Панель поставит его {where} и сама подключит к своим метрикам: графики «Монитора» появятся через минуту-две. Наружу он не открывается.</>}
|
||||
</span>
|
||||
</span>
|
||||
<span className="st-row-ctl">
|
||||
<span className={`chip chip--${status.ready ? 'online' : 'offline'}`}>
|
||||
<span className="chip-dot" />{doing === 'install' ? 'ставится' : doing === 'remove' ? 'удаляется' : status.ready ? 'работает' : 'не подключён'}
|
||||
</span>
|
||||
{status.can_install && (status.ready ? (
|
||||
<button className="btn btn--danger" onClick={() => run('remove')} disabled={working}>
|
||||
<IcoTrash /> {doing === 'remove' ? 'Удаляем…' : 'Удалить'}
|
||||
</button>
|
||||
) : (
|
||||
<button className="btn btn--primary" onClick={() => run('install')} disabled={working}>
|
||||
<IcoPlus /> {doing === 'install' ? 'Устанавливаем…' : 'Установить'}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{showJob && <JobProgress job={job} starting={!!pending} />}
|
||||
|
||||
{!status.can_install && (
|
||||
<div className="st-row">
|
||||
<span className="st-row-text">
|
||||
<span className="st-hint">
|
||||
{status.ready ? 'Удаляется на сервере с Prometheus от root:'
|
||||
: 'На выбранном сервере установка кнопкой недоступна (нет связи или старый awg-ctrl): выберите другой сервер в шапке или выполните на этом от root:'}
|
||||
</span>
|
||||
<code className="prom-code">{command}</code>
|
||||
</span>
|
||||
<button className="btn btn--tonal" onClick={() => copyText(command).then(() => showMsg('Команда скопирована'))}>
|
||||
<IcoCopy /> Скопировать
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Полный лог — только при ошибке: оператору нужна причина, а не поток строк apt */}
|
||||
{failed && (
|
||||
<>
|
||||
<pre className="prom-log">{job!.log.trim()}</pre>
|
||||
<p className="login-error">
|
||||
{job!.action === 'install' ? 'Установка' : 'Удаление'} не удалась. Если дело в правах или пакетах, выполните вручную: <b>{`awg-ctrl monitor ${job!.action}`}</b>
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
Copyright (c) 2026 Ivan Vasilev
|
||||
This source code is licensed under the MIT license found in the
|
||||
LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
/* Установка Prometheus (раздел «Prometheus» вкладки «Настройки»). Строки — из settings.css. */
|
||||
|
||||
/* Ход установки или удаления: полоска + подпись шага */
|
||||
.prom-progress { display: flex; flex-direction: column; gap: 6px; padding: 4px 0 12px; }
|
||||
.prom-pbar { display: block; width: 100%; height: 8px; border-radius: var(--shape-extra-small); overflow: hidden; background: var(--primary-container); }
|
||||
.prom-pbar i { display: block; height: 100%; border-radius: var(--shape-extra-small); background: var(--primary); transition: width var(--duration-medium4) var(--ease-standard); }
|
||||
.prom-pbar--ok i { background: var(--success-dot); }
|
||||
.prom-pbar--bad i { background: var(--error-dot); }
|
||||
/* Шага ещё нет — ход неизвестен: бегущий отрезок вместо ложных процентов */
|
||||
.prom-pbar--wait i { width: 35% !important; animation: prom-wait 1.2s ease-in-out infinite; }
|
||||
@keyframes prom-wait { 0% { transform: translateX(-100%); } 100% { transform: translateX(290%); } }
|
||||
@media (prefers-reduced-motion: reduce) { .prom-pbar--wait i { animation: none; } .prom-pbar i { transition: none; } }
|
||||
|
||||
.prom-code {
|
||||
display: block; margin-top: 6px; word-break: break-all; user-select: all;
|
||||
font-family: var(--mono); font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--on-surface);
|
||||
background: var(--surface-container-lowest);
|
||||
border-radius: var(--shape-medium);
|
||||
padding: 10px 12px;
|
||||
}
|
||||
.prom-log {
|
||||
margin: 0 0 8px; max-height: 240px; overflow: auto;
|
||||
font-family: var(--mono); font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--on-surface);
|
||||
background: var(--surface-container-lowest); border-radius: var(--shape-medium);
|
||||
padding: 12px; white-space: pre-wrap; word-break: break-word;
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// Copyright (c) 2026 Ivan Vasilev
|
||||
// This source code is licensed under the MIT license found in the
|
||||
// LICENSE file in the root directory of this source tree.
|
||||
import { useEffect, useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import { apiFetch, type PageProps, type ShapingStatus, type TorrentStatus } from '../../../lib/shared';
|
||||
import './server.css';
|
||||
|
||||
// Раздел «Сервер» вкладки «Настройки»: деление канала между устройствами (CAKE) и блокировка BitTorrent
|
||||
// для сервера из шапки (при его смене вкладка перемонтируется). Сами настройки живут в awg-ctrl этого
|
||||
// сервера — запрос идёт обычным прокси с X-Server-Id, так что ядро и ноды настраиваются одинаково.
|
||||
export default function ServerSettings({ token, showMsg }: PageProps) {
|
||||
const [st, setSt] = useState<ShapingStatus | null>(null);
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [auto, setAuto] = useState(true);
|
||||
const [down, setDown] = useState('');
|
||||
const [up, setUp] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [unsupported, setUnsupported] = useState(false);
|
||||
const [tst, setTst] = useState<TorrentStatus | null>(null);
|
||||
const [tEnabled, setTEnabled] = useState(false);
|
||||
const [tUnsupported, setTUnsupported] = useState(false);
|
||||
|
||||
const fill = (s: ShapingStatus) => {
|
||||
setSt(s);
|
||||
setEnabled(s.settings.enabled); setAuto(s.settings.auto);
|
||||
setDown(s.settings.downMbit ? String(s.settings.downMbit) : '');
|
||||
setUp(s.settings.upMbit ? String(s.settings.upMbit) : '');
|
||||
};
|
||||
|
||||
const errText = (e: unknown, fallback: string) =>
|
||||
axios.isAxiosError(e) ? e.response?.data?.error ?? fallback : fallback;
|
||||
|
||||
const fillTorrent = (s: TorrentStatus) => { setTst(s); setTEnabled(s.settings.enabled); };
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
apiFetch('GET', '/api/torrent', token)
|
||||
.then(s => { if (alive) fillTorrent(s as TorrentStatus); })
|
||||
.catch(e => {
|
||||
if (!alive) return;
|
||||
if (axios.isAxiosError(e) && e.response?.status === 404) setTUnsupported(true);
|
||||
else setError(errText(e, 'Не удалось загрузить настройки'));
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [token]);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
apiFetch('GET', '/api/shaping', token)
|
||||
.then(s => { if (alive) fill(s as ShapingStatus); })
|
||||
.catch(e => {
|
||||
if (!alive) return;
|
||||
// Старый awg-ctrl не знает этот маршрут — его надо обновить, а не «починить» здесь.
|
||||
if (axios.isAxiosError(e) && e.response?.status === 404) setUnsupported(true);
|
||||
else setError(errText(e, 'Не удалось загрузить настройки'));
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [token]);
|
||||
|
||||
const downN = Number(down), upN = Number(up);
|
||||
const valid = !enabled || (Number.isInteger(downN) && downN >= 1 && Number.isInteger(upN) && upN >= 1);
|
||||
|
||||
// Отправляем только изменённое: лишний PUT /api/shaping заново ставил бы tc на интерфейс.
|
||||
const shapingDirty = !!st && (enabled !== st.settings.enabled || auto !== st.settings.auto
|
||||
|| (Number(down) || 0) !== st.settings.downMbit || (Number(up) || 0) !== st.settings.upMbit);
|
||||
const torrentDirty = !!tst && tEnabled !== tst.settings.enabled;
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true); setError('');
|
||||
const done: string[] = [];
|
||||
try {
|
||||
if (shapingDirty) {
|
||||
const s = await apiFetch('PUT', '/api/shaping', token, {
|
||||
enabled, auto, downMbit: Number(down) || 0, upMbit: Number(up) || 0,
|
||||
});
|
||||
fill(s as ShapingStatus);
|
||||
done.push(enabled ? 'деление канала включено' : 'деление канала выключено');
|
||||
}
|
||||
if (torrentDirty) {
|
||||
const s = await apiFetch('PUT', '/api/torrent', token, { enabled: tEnabled });
|
||||
fillTorrent(s as TorrentStatus);
|
||||
done.push(tEnabled ? 'торренты блокируются' : 'блокировка торрентов выключена');
|
||||
}
|
||||
if (done.length) showMsg(done.join(', ').replace(/^./, c => c.toUpperCase()));
|
||||
} catch (e) { setError(errText(e, 'Не удалось сохранить')); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="st-section ss-card">
|
||||
<h3 className="ss-section">Деление канала</h3>
|
||||
|
||||
{unsupported ? (
|
||||
<p className="st-hint">
|
||||
Этот сервер не поддерживает деление канала: обновите его (install.sh → «Обновить»).
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="st-hint">
|
||||
Канал делится поровну между устройствами, но не простаивает: кто берёт мало, получает всё
|
||||
нужное, остальное достаётся тем, кто качает много. Звонки и игры не ждут за чужими закачками.
|
||||
</p>
|
||||
|
||||
<label className="ss-setting">
|
||||
<span className="ss-setting-text">
|
||||
<span className="ss-setting-name">Честное деление между устройствами</span>
|
||||
</span>
|
||||
<input type="checkbox" checked={enabled} disabled={!st || busy} onChange={e => setEnabled(e.target.checked)} />
|
||||
</label>
|
||||
|
||||
<div className="ss-grid">
|
||||
<label className="ss-field">
|
||||
<span className="ss-setting-name">Загрузка, Мбит/с</span>
|
||||
<input className="field" type="number" inputMode="numeric" min={1} max={100000}
|
||||
value={down} disabled={!st || busy} onChange={e => setDown(e.target.value)} />
|
||||
</label>
|
||||
<label className="ss-field">
|
||||
<span className="ss-setting-name">Отдача, Мбит/с</span>
|
||||
<input className="field" type="number" inputMode="numeric" min={1} max={100000}
|
||||
value={up} disabled={!st || busy} onChange={e => setUp(e.target.value)} />
|
||||
</label>
|
||||
</div>
|
||||
<p className="st-hint">
|
||||
Укажите около 90–95% реального канала сервера. Если задать больше, очередь копится у провайдера
|
||||
и деление перестаёт работать.
|
||||
</p>
|
||||
|
||||
<label className="ss-setting">
|
||||
<span className="ss-setting-text">
|
||||
<span className="ss-setting-name">Снижать приоритет тяжёлых</span>
|
||||
<span className="st-hint">
|
||||
Когда канал занят, устройства, которые долго качают заметно больше своей доли, временно
|
||||
уходят в фоновый класс. Работает на загрузку; свободный канал они по-прежнему занимают.
|
||||
</span>
|
||||
</span>
|
||||
<input type="checkbox" checked={auto} disabled={!st || busy || !enabled} onChange={e => setAuto(e.target.checked)} />
|
||||
</label>
|
||||
|
||||
{st?.settings.enabled && (
|
||||
<div className="ss-status">
|
||||
<span className={`chip ${st.active ? (st.congested ? 'chip--warm' : 'chip--online') : 'chip--offline'}`}>
|
||||
<span className="chip-dot" />
|
||||
{!st.active ? 'не применено' : st.congested ? 'канал занят' : 'канал свободен'}
|
||||
</span>
|
||||
<span className="ss-mono">
|
||||
↓ {st.rateDown} · ↑ {st.rateUp} Мбит/с · устройств {st.devices}
|
||||
</span>
|
||||
{st.heavy.length > 0 && (
|
||||
<span className="ss-mono">в фоне: {st.heavy.join(', ')}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
</section>
|
||||
|
||||
<section className="st-section ss-card">
|
||||
<h3 className="ss-section">Торренты</h3>
|
||||
{tUnsupported ? (
|
||||
<p className="st-hint">
|
||||
Этот сервер не умеет блокировать торренты: обновите его (install.sh → «Обновить»).
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<label className="ss-setting">
|
||||
<span className="ss-setting-text">
|
||||
<span className="ss-setting-name">Блокировать BitTorrent</span>
|
||||
<span className="st-hint">
|
||||
Режет поиск пиров (DHT), трекеры и начало торрент-соединений — как блокировка в 3x-ui.
|
||||
Клиент с шифрованием и HTTPS-трекерами может частично её обойти, но без DHT и открытых
|
||||
трекеров большинство торрентов не стартуют. Остальной трафик не режется.
|
||||
</span>
|
||||
<span className="st-hint">
|
||||
{enabled
|
||||
? 'Кто пытается качать, на 10 минут после последней попытки уходит в фоновый приоритет: уступает остальным, когда канал занят.'
|
||||
: 'Включите деление канала — тогда кто пытается качать, на 10 минут уйдёт ещё и в фоновый приоритет.'}
|
||||
</span>
|
||||
</span>
|
||||
<input type="checkbox" checked={tEnabled} disabled={!tst || busy} onChange={e => setTEnabled(e.target.checked)} />
|
||||
</label>
|
||||
|
||||
{tst?.settings.enabled && (
|
||||
<div className="ss-status">
|
||||
<span className={`chip ${tst.active ? 'chip--online' : 'chip--offline'}`}>
|
||||
<span className="chip-dot" />{tst.active ? 'работает' : 'не применено'}
|
||||
</span>
|
||||
<span className="ss-mono">заблокировано попыток: {tst.hits.toLocaleString('ru-RU')}</span>
|
||||
{tst.active && !tst.tcp && (
|
||||
<span className="st-hint">
|
||||
TCP не проверяется: на сервере старый nftables. DHT, трекеры и uTP блокируются.
|
||||
</span>
|
||||
)}
|
||||
{tst.error && <span className="st-hint">{tst.error}</span>}
|
||||
{tst.seen.length > 0 && (
|
||||
<>
|
||||
<span className="st-hint">Пытались качать за последние 10 минут:</span>
|
||||
<span className="ss-seen">
|
||||
{tst.seen.map(p => (
|
||||
<span key={p.ip} className="chip chip--error">
|
||||
<span className="chip-dot" />{p.name ? `${p.name} · ${p.ip}` : p.ip}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
</section>
|
||||
|
||||
{error && <p className="login-error">{error}</p>}
|
||||
|
||||
{!(unsupported && tUnsupported) && (
|
||||
<div className="ss-actions">
|
||||
<button className="btn btn--primary" onClick={save} disabled={busy || !valid || !(shapingDirty || torrentDirty)}>
|
||||
Сохранить
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
Copyright (c) 2026 Ivan Vasilev
|
||||
This source code is licensed under the MIT license found in the
|
||||
LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
/* Раздел «Сервер» вкладки «Настройки»: бывший диалог «Настройки сервера», строки .ss-* — из App.css */
|
||||
.ss-card { gap: 12px; padding: 16px; }
|
||||
.ss-card .ss-section { margin: 0; }
|
||||
.ss-card .ss-status { background: var(--surface-container-lowest); }
|
||||
.ss-actions { display: flex; justify-content: flex-end; }
|
||||
.ss-card .ss-grid { max-width: 480px; }
|
||||
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
Copyright (c) 2026 Ivan Vasilev
|
||||
This source code is licensed under the MIT license found in the
|
||||
LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
/* Стили вкладки «Настройки». Общая дизайн-система — в App.css (там же .segmented). */
|
||||
|
||||
/* Вкладки разделов (MD3 primary tabs, прокручиваемые): 48px, подпись title-small, прижаты влево;
|
||||
активная — цветом primary и полосой 3px снизу, которая переезжает между вкладками (left/width
|
||||
ставит компонент). Под вкладками — линия outline-variant во всю ширину. */
|
||||
.st-tabs {
|
||||
position: relative;
|
||||
display: flex;
|
||||
box-shadow: inset 0 -1px var(--outline-variant); /* линия — тенью: рамка ушла бы в прокрутку */
|
||||
/* MD3 scrollable tabs: не влезли — прокручиваются вбок, без полосы прокрутки */
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.st-tabs::-webkit-scrollbar { display: none; }
|
||||
.st-tab {
|
||||
flex: 0 0 auto;
|
||||
height: 48px;
|
||||
padding: 0 20px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--on-surface-variant);
|
||||
font-family: var(--font);
|
||||
font-size: var(--title-small-size); line-height: var(--title-small-line);
|
||||
font-weight: var(--weight-medium);
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition: color var(--duration-short3) var(--ease-standard);
|
||||
}
|
||||
.st-tab[aria-selected="true"] { color: var(--primary); }
|
||||
.st-tab:focus-visible { outline-offset: -3px; }
|
||||
.st-tabs-indicator {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
height: 3px;
|
||||
border-radius: 3px 3px 0 0;
|
||||
background: var(--primary);
|
||||
transition: left var(--duration-medium2) var(--ease-standard), width var(--duration-medium2) var(--ease-standard);
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .st-tabs-indicator { transition: none; } }
|
||||
|
||||
/* Содержимое раздела — с тем же шагом, что у страницы. При смене вкладки въезжает на 32px со стороны
|
||||
выбранной (--st-dir: 1 — справа, -1 — слева, 0 — только проявляется), как MD3 shared axis X.
|
||||
Только backwards: после анимации transform не остаётся — иначе fixed-диалоги внутри (QR, ключи)
|
||||
отсчитывались бы от раздела, а не от окна. */
|
||||
.st-view {
|
||||
display: flex; flex-direction: column; gap: 20px; min-width: 0;
|
||||
animation: st-view-in var(--duration-medium2) var(--ease-emphasized-decelerate) backwards;
|
||||
}
|
||||
@keyframes st-view-in {
|
||||
from { opacity: 0; transform: translateX(calc(var(--st-dir, 0) * 32px)); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .st-view { animation: none; } }
|
||||
/* въезжающий раздел на миг шире страницы — без горизонтальной прокрутки */
|
||||
.main:has(.st-view) { overflow-x: hidden; }
|
||||
|
||||
/* Раздел — блок на surface-container; строки внутри разделены линией outline-variant */
|
||||
.st-section {
|
||||
display: flex; flex-direction: column;
|
||||
background: var(--surface-container);
|
||||
border-radius: var(--shape-large);
|
||||
padding: 12px 16px;
|
||||
}
|
||||
.st-lead { margin: 4px 0; }
|
||||
.st-row {
|
||||
display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
padding: 12px 0;
|
||||
}
|
||||
.st-row + .st-row, .st-lead + .st-row { border-top: 1px solid var(--outline-variant); }
|
||||
.st-row:first-child { padding-top: 4px; }
|
||||
.st-row:last-child { padding-bottom: 4px; }
|
||||
.st-row-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1 1 240px; }
|
||||
.st-row-name { font-size: var(--body-large-size); line-height: var(--body-large-line); color: var(--on-surface); }
|
||||
.st-row-ctl { display: inline-flex; flex-wrap: wrap; gap: 8px; }
|
||||
.st-hint { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); overflow-wrap: anywhere; }
|
||||
.st-code {
|
||||
font-family: var(--mono);
|
||||
font-size: 0.95em;
|
||||
background: var(--surface-container-highest);
|
||||
border-radius: var(--shape-extra-small);
|
||||
padding: 0 4px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
|
||||
/* О панели: пары «название — значение» */
|
||||
.st-facts { display: flex; flex-direction: column; margin: 0; }
|
||||
.st-facts > div { display: flex; justify-content: space-between; gap: 16px; padding: 10px 0; }
|
||||
.st-facts > div + div { border-top: 1px solid var(--outline-variant); }
|
||||
.st-facts > div:first-child { padding-top: 4px; }
|
||||
.st-facts > div:last-child { padding-bottom: 4px; }
|
||||
.st-facts dt { font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--neutral-text); }
|
||||
.st-facts dd { margin: 0; font-size: var(--body-medium-size); line-height: var(--body-medium-line); color: var(--on-surface); text-align: right; }
|
||||
|
||||
/* Открытый токен (один раз после выпуска) — как ключ API */
|
||||
.st-secret {
|
||||
font-family: var(--mono);
|
||||
font-size: var(--body-medium-size); line-height: var(--body-medium-line);
|
||||
color: var(--on-surface);
|
||||
background: var(--surface-container-lowest);
|
||||
border-radius: var(--shape-medium);
|
||||
padding: 12px 14px;
|
||||
width: 100%;
|
||||
word-break: break-all;
|
||||
user-select: all;
|
||||
}
|
||||
|
||||
/* compact: переключатель темы и кнопки — на всю ширину строки */
|
||||
@media (max-width: 599px) {
|
||||
.st-row > .segmented { width: 100%; }
|
||||
.st-row > .segmented .segmented-item { flex: 1; padding: 0 8px; }
|
||||
.st-row-ctl { width: 100%; }
|
||||
.st-row-ctl .btn { flex: 1; }
|
||||
}
|
||||
@@ -2,11 +2,11 @@
|
||||
// This source code is licensed under the MIT license found in the
|
||||
// LICENSE file in the root directory of this source tree.
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import QRCode from 'qrcode';
|
||||
import {
|
||||
apiFetch, vpnKeyToConf, downloadFile, copyText, bytes, timeAgo, genLabel,
|
||||
type User, type PageProps, type AwgGen,
|
||||
} from '../../lib/shared';
|
||||
import { qrDataUrl } from '../../lib/qr';
|
||||
import { IcoPlus, IcoRefresh, IcoQR, IcoTrash, IcoGlobe } from '../../components/icons';
|
||||
import PriorityChip from '../../components/PriorityChip';
|
||||
import TorrentChip from '../../components/TorrentChip';
|
||||
@@ -109,12 +109,7 @@ export default function UsersPage({ token, showMsg }: PageProps) {
|
||||
const vpnKey = u.vpn_key ?? '';
|
||||
// errorCorrectionLevel 'L' (а не 'H'): ключ vpn:// длинный (~1.3 КБ),
|
||||
// при 'H' ёмкость QR падает до ~1273 байт и кодирование падает.
|
||||
const dataUrl = await QRCode.toDataURL(vpnKey, {
|
||||
width: 560,
|
||||
margin: 2,
|
||||
errorCorrectionLevel: 'L',
|
||||
});
|
||||
setQrModal({ name, dataUrl, vpnKey });
|
||||
setQrModal({ name, dataUrl: qrDataUrl(vpnKey, 'L'), vpnKey });
|
||||
} catch {
|
||||
showMsg('Не удалось сгенерировать QR-код');
|
||||
}
|
||||
@@ -297,6 +292,7 @@ export default function UsersPage({ token, showMsg }: PageProps) {
|
||||
/>
|
||||
<p className="qr-hint">Отсканируй в AmneziaVPN · нажми на QR чтобы скопировать</p>
|
||||
<div className="qr-actions">
|
||||
<button className="btn btn--text" onClick={() => setQrModal(null)}>Закрыть</button>
|
||||
<button className="btn btn--tonal" onClick={async () => {
|
||||
try {
|
||||
const conf = await vpnKeyToConf(qrModal.vpnKey);
|
||||
@@ -305,7 +301,6 @@ export default function UsersPage({ token, showMsg }: PageProps) {
|
||||
showMsg('Конфиг скачан');
|
||||
} catch { showMsg('Не удалось декодировать ключ'); }
|
||||
}}>Скачать .conf</button>
|
||||
<button className="btn btn--tonal" onClick={() => setQrModal(null)}>Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -8,9 +8,9 @@ LICENSE file in the root directory of this source tree.
|
||||
|
||||
.user-cards-list { display: none; flex-direction: column; gap: 12px; }
|
||||
|
||||
.users-count { font-size: 12px; color: var(--neutral-text); }
|
||||
.users-count { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.empty-cards {
|
||||
font-size: 14px;
|
||||
font-size: var(--body-medium-size); line-height: var(--body-medium-line);
|
||||
color: var(--neutral-text);
|
||||
text-align: center;
|
||||
padding: 48px 0;
|
||||
@@ -18,7 +18,7 @@ LICENSE file in the root directory of this source tree.
|
||||
.user-card {
|
||||
background: var(--surface-bright);
|
||||
border: 1px solid var(--outline-variant);
|
||||
border-radius: var(--r-card);
|
||||
border-radius: var(--shape-extra-large);
|
||||
padding: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -36,10 +36,10 @@ LICENSE file in the root directory of this source tree.
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.user-card-num { font-size: 12px; color: var(--neutral-dot); flex-shrink: 0; }
|
||||
.user-card-num { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-dot); flex-shrink: 0; }
|
||||
.user-card-name {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
font-size: var(--title-medium-size); line-height: var(--title-medium-line);
|
||||
font-weight: var(--weight-medium);
|
||||
color: var(--on-surface);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -52,20 +52,23 @@ LICENSE file in the root directory of this source tree.
|
||||
gap: 8px;
|
||||
color: var(--neutral-text);
|
||||
}
|
||||
.user-card-ip-text { font-family: var(--mono); font-size: 13px; }
|
||||
.user-card-ip-text { font-family: var(--mono); font-size: var(--body-medium-size); line-height: var(--body-medium-line); }
|
||||
/* чипы приоритета и торрентов — рядом с IP, как в карточке устройства мастер-ключа (на телефоне
|
||||
.tip-wrap по умолчанию во всю ширину и уводил чип на отдельную строку) */
|
||||
.user-card-ip .tip-wrap { width: auto; }
|
||||
|
||||
.user-card-metrics { display: flex; gap: 8px; }
|
||||
.metric-block {
|
||||
flex: 1;
|
||||
background: var(--surface-container);
|
||||
border-radius: var(--r-table);
|
||||
border-radius: var(--shape-large);
|
||||
padding: 10px 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.metric-label { font-size: 12px; color: var(--neutral-text); }
|
||||
.metric-value { font-family: var(--mono); font-size: 18px; font-weight: 500; color: var(--on-surface); }
|
||||
.metric-label { font-size: var(--body-small-size); line-height: var(--body-small-line); color: var(--neutral-text); }
|
||||
.metric-value { font-family: var(--mono); font-size: var(--title-medium-size); line-height: var(--title-medium-line); font-weight: var(--weight-medium); color: var(--on-surface); }
|
||||
|
||||
.user-card-actions { display: flex; gap: 8px; }
|
||||
.user-card-actions .btn--outline { flex: 1; }
|
||||
@@ -73,9 +76,14 @@ LICENSE file in the root directory of this source tree.
|
||||
/* Метка устаревшего ключа рядом с именем: ключ выдан на другом поколении AWG. */
|
||||
.user-gen { margin-left: 8px; vertical-align: middle; }
|
||||
|
||||
/* На мобильной таблица скрывается (.table-card в App.css), карточки показываются. */
|
||||
@media (max-width: 640px) {
|
||||
.user-cards-list { display: flex; }
|
||||
/* compact и medium (< 840px): таблица скрывается (.table-card в App.css), показываются карточки —
|
||||
в одну колонку на телефоне, сеткой на планшете. */
|
||||
@media (max-width: 839px) {
|
||||
.user-cards-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); }
|
||||
/* счётчик и «пусто» — на всю строку сетки */
|
||||
:is(.users-count, .empty-cards) { grid-column: 1 / -1; }
|
||||
}
|
||||
@media (max-width: 599px) {
|
||||
/* .tip-wrap на мобильной растягивается на всю ширину — метке это не нужно. */
|
||||
.user-gen { width: auto; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user