Restructure ARNavi contour UX and expose project-scoped VPS inventory
Device Core qualification / qualify (push) Successful in 7m42s
Device Core qualification / qualify (push) Successful in 7m42s
This commit is contained in:
@@ -1,24 +1,26 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge,
|
||||
TextField, TextAreaField, WindowFooterActions, ConfirmationModal } from '@nodedc/ui-react';
|
||||
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, WindowFooterActions, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react';
|
||||
import { loadProjects } from '../api';
|
||||
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
|
||||
import { b2Request, type B2Status } from './api';
|
||||
import './b2.css';
|
||||
|
||||
type Section = 'connection' | 'contours' | 'applications';
|
||||
type Section = 'connection' | 'contours';
|
||||
type Form = 'contour' | 'application' | 'project' | null;
|
||||
export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: {
|
||||
host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void;
|
||||
onChanged: () => Promise<void>; onError: (error: unknown) => void;
|
||||
}) {
|
||||
const project = workspace.project;
|
||||
const [section, setSection] = useState<Section>('connection');
|
||||
const [section, setSection] = useState<Section>('contours');
|
||||
const [status, setStatus] = useState<B2Status | null>(null);
|
||||
const [pending, setPending] = useState('');
|
||||
const [pending, setPending] = useState('load');
|
||||
const [connection, setConnection] = useState('');
|
||||
const connectionFile = useRef<HTMLInputElement>(null);
|
||||
const [key, setKey] = useState(''); const [name, setName] = useState('');
|
||||
const [contour, setContour] = useState('');
|
||||
const [key, setKey] = useState(''), [name, setName] = useState('');
|
||||
const [contourId, setContourId] = useState(''), [applicationId, setApplicationId] = useState('');
|
||||
const [form, setForm] = useState<Form>(null);
|
||||
const [showHistory, setShowHistory] = useState(false), [showInactive, setShowInactive] = useState(false);
|
||||
const [targetProject, setTargetProject] = useState(project.projectRef);
|
||||
const [projects, setProjects] = useState<ProjectSummary[]>([]);
|
||||
const [issued, setIssued] = useState('');
|
||||
@@ -27,10 +29,9 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
const refresh = () => request<B2Status>('status').then(setStatus);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setPending('load');
|
||||
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
|
||||
if (!active) return;
|
||||
setStatus(value);
|
||||
setStatus(value); if (!value.connected) setSection('connection');
|
||||
setProjects(available.filter((item) => item.ownerScope.ownerScopeRef === project.ownerScope.ownerScopeRef));
|
||||
}).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); });
|
||||
return () => { active = false; };
|
||||
@@ -38,111 +39,95 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
async function run(action: string, data: Record<string, unknown> = {}) {
|
||||
setPending(action);
|
||||
try {
|
||||
const result = await request<{ connection?: unknown }>(action, data);
|
||||
const result = await request<{ connection?: unknown; id?: string }>(action, data);
|
||||
if (result.connection) setIssued(JSON.stringify(result.connection, null, 2));
|
||||
if (action === 'connect') setConnection('');
|
||||
await refresh(); await onChanged();
|
||||
} catch (error) { onError(error); } finally { setPending(''); }
|
||||
if (action === 'connect') { setConnection(''); setSection('contours'); }
|
||||
if (action === 'contour-create' && result.id) { setContourId(result.id); setApplicationId(''); }
|
||||
if (action === 'application-create' && result.id) setApplicationId(result.id);
|
||||
setForm(null); setName(''); setKey('');
|
||||
// A successful mutation must not be presented as failed if a subsequent read fails.
|
||||
try { await refresh(); await onChanged(); } catch (error) { onError(error); }
|
||||
return true;
|
||||
} catch (error) { onError(error); return false; } finally { setPending(''); }
|
||||
}
|
||||
const contours = status?.contours || [];
|
||||
const canManage = status?.authority === 'host';
|
||||
const busy = Boolean(pending);
|
||||
const contours = status?.contours || [], selected = contours.find((item) => item.id === contourId);
|
||||
const linkedProject = status?.links?.find((item) => item.contourId === contourId)?.projectRef;
|
||||
const applications = (status?.applications || []).filter((app) => app.authority !== 'host' && app.key !== 'legacy-mission-core' && app.grants[contourId]);
|
||||
const application = applications.find((app) => app.id === applicationId);
|
||||
const inactive = (app: typeof applications[number]) => app.credentials.length > 0 && !app.credentials.some((item) => item.enabled);
|
||||
const busy = Boolean(pending), canManage = status?.authority === 'host';
|
||||
const begin = (value: Form) => { setForm(value); setName(''); setKey(''); setTargetProject(project.projectRef); };
|
||||
const back = () => {
|
||||
setIssued(''); setShowHistory(false);
|
||||
if (form) setForm(null); else if (applicationId) setApplicationId(''); else { setContourId(''); setShowInactive(false); }
|
||||
};
|
||||
function downloadIssuedKey() {
|
||||
const url = URL.createObjectURL(new Blob([issued + '\n'], { type: 'application/json' }));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = 'arnavi-application-key.json';
|
||||
link.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
const link = document.createElement('a'); link.href = url; link.download = 'arnavi-application-key.json';
|
||||
document.body.append(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
return <>
|
||||
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
|
||||
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
|
||||
sections={[{ id: 'connection', label: 'Подключение', icon: 'network' },
|
||||
{ id: 'contours', label: 'Контуры и проекты', icon: 'layers', disabled: !status?.connected },
|
||||
{ id: 'applications', label: 'Приложения и ключи', icon: 'key', disabled: !status?.connected }]}
|
||||
activeSection={section} onSectionChange={(value) => { setSection(value); setKey(''); setName(''); }} onClose={onClose}
|
||||
footer={<WindowFooterActions><Button onClick={onClose}>Закрыть</Button>
|
||||
sections={[{ id: 'connection', label: 'Подключение', icon: 'network' }, { id: 'contours', label: 'Контуры', icon: 'layers', disabled: !status?.connected }]}
|
||||
activeSection={section} onSectionChange={(value) => { setSection(value); setForm(null); setIssued(''); }} onClose={onClose}
|
||||
footer={<WindowFooterActions>
|
||||
{section === 'contours' && (selected || form) ? <IconButton label={form ? 'Отменить создание' : application ? 'К приложениям контура' : 'К списку контуров'} disabled={busy} onClick={back}><Icon name="chevron-left" /></IconButton> : null}
|
||||
<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
|
||||
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
|
||||
}}><Icon name="refresh" /></IconButton></WindowFooterActions>}>
|
||||
<div className="b2-settings">
|
||||
}}><Icon name="refresh" /></IconButton>
|
||||
</WindowFooterActions>}>
|
||||
<div className="b2-settings" aria-busy={busy}>
|
||||
{section === 'connection' ? <>
|
||||
<SettingsCard title="ARNavi VPS" description="Одно подключение сервера для проектов компании. Устройства разделяются контурами.">
|
||||
<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Подключён' : pending === 'load' ? 'Проверяем подключение' : status ? 'Не подключён' : 'Состояние не получено'}</StatusBadge>
|
||||
{status?.endpoint ? <p>{status.endpoint}</p> : null}
|
||||
</SettingsCard>
|
||||
<SettingsCard title={status?.connected ? 'Заменить ключ подключения' : 'Подключить сервер'} description="Загрузите файл ключа или вставьте ключ, выданный на VPS. После подключения он хранится только на сервере Device Core.">
|
||||
<ResourceRow title={host.displayName} description={status?.endpoint} status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Подключён' : pending === 'load' ? 'Подключение…' : 'Не подключён'}</StatusBadge>} />
|
||||
<SettingsCard title={status?.connected ? 'Заменить ключ сервера' : 'Подключить сервер'}>
|
||||
<div className="b2-settings">
|
||||
<Button disabled={busy} onClick={() => connectionFile.current?.click()}><Icon name="upload" />Загрузить файл ключа</Button>
|
||||
<input ref={connectionFile} type="file" accept=".json,application/json" hidden aria-label="Файл ключа подключения VPS" disabled={busy}
|
||||
onChange={async (event) => {
|
||||
const file = event.currentTarget.files?.[0]; event.currentTarget.value = '';
|
||||
if (!file) return;
|
||||
setPending('file');
|
||||
try {
|
||||
if (file.size > 16384) throw new Error('Файл ключа слишком большой. Выберите JSON-файл, выданный на VPS.');
|
||||
const text = await file.text();
|
||||
try { JSON.parse(text); } catch { throw new Error('Не удалось прочитать файл ключа. Выберите JSON-файл, выданный на VPS.'); }
|
||||
setConnection(text);
|
||||
} catch (error) { onError(error); } finally { setPending(''); }
|
||||
}} />
|
||||
<TextAreaField label="Ключ подключения" value={connection} autoComplete="off" spellCheck={false}
|
||||
onChange={(event) => setConnection(event.target.value)} rows={5} />
|
||||
<input ref={connectionFile} type="file" accept=".json,application/json" hidden aria-label="Файл ключа подключения VPS" disabled={busy} onChange={async (event) => {
|
||||
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return; setPending('file');
|
||||
try { if (file.size > 16384) throw new Error(); const text = await file.text(); JSON.parse(text); setConnection(text); }
|
||||
catch { onError(new Error('Не удалось прочитать файл ключа VPS.')); } finally { setPending(''); }
|
||||
}} />
|
||||
<TextAreaField label="Ключ сервера" value={connection} autoComplete="off" spellCheck={false} onChange={(event) => setConnection(event.target.value)} rows={4} />
|
||||
<Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>Подключить</Button>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
</> : null}
|
||||
{section === 'contours' ? <>
|
||||
<SettingsCard title="Контуры на VPS" description="Связь с проектом определяет, где появятся устройства. Один контур можно подключить к нескольким приложениям.">
|
||||
<div className="b2-path" aria-label="Текущий раздел">{[host.displayName, selected?.name, application?.name].filter(Boolean).join(' / ')}</div>
|
||||
{form === 'contour' || form === 'application' ? <SettingsCard title={form === 'contour' ? 'Новый контур' : 'Новое приложение'}>
|
||||
<div className="b2-settings">
|
||||
{contours.map((item) => {
|
||||
const link = status?.links?.find((value) => value.contourId === item.id);
|
||||
return <div className="b2-resource" key={item.id}><div><strong>{item.name}</strong><small>{item.key}</small></div>
|
||||
<StatusBadge tone={link ? 'success' : 'neutral'}>{link ? projects.find((p) => p.projectRef === link.projectRef)?.name || 'Связан с проектом' : 'Не связан'}</StatusBadge></div>;
|
||||
})}
|
||||
{!contours.length ? <p>На VPS пока нет контуров.</p> : null}
|
||||
<Select label="Контур" value={contour} onChange={setContour} options={contours.map((item) => ({ value: item.id, label: item.name }))} />
|
||||
<Select label="Проект" value={targetProject} onChange={setTargetProject} options={projects.map((item) => ({ value: item.projectRef, label: item.name }))} />
|
||||
<Button loading={pending === 'link'} disabled={busy || !contour || !targetProject} onClick={() => void run('link', { contourId: contour, targetProjectRef: targetProject })}>Связать с проектом</Button>
|
||||
{form === 'application' ? <ResourceRow title={selected?.name} metadata="Контур" /> : null}
|
||||
<TextField label="Название" value={name} maxLength={160} onChange={(e) => setName(e.target.value)} />
|
||||
<TextField label="Код" value={key} placeholder={form === 'contour' ? 'robot2b' : 'delivery-app'} onChange={(e) => setKey(e.target.value.toLowerCase())} />
|
||||
<div className="b2-actions"><Button onClick={() => setForm(null)} disabled={busy}>Отмена</Button><Button loading={busy} disabled={busy || !name.trim() || !/^[a-z][a-z0-9-]{0,63}$/.test(key)} onClick={() => void run(form === 'contour' ? 'contour-create' : 'application-create', { key, name, ...(form === 'application' ? { contourId } : {}) })}>Создать</Button></div>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
{canManage ? <SettingsCard title="Новый контур" description="Контур создаётся на VPS и получает собственный реестр устройств.">
|
||||
<div className="b2-settings"><TextField label="Название" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
<TextField label="Код контура" value={key} placeholder="robot2b" onChange={(e) => setKey(e.target.value)} />
|
||||
<Button loading={pending === 'contour-create'} disabled={busy || !/^[a-z][a-z0-9-]{0,63}$/.test(key) || !name.trim()}
|
||||
onClick={() => void run('contour-create', { key, name })}>Создать контур</Button></div>
|
||||
</SettingsCard> : null}
|
||||
</> : null}
|
||||
{section === 'applications' ? <>
|
||||
{issued ? <SettingsCard title="Новый ключ приложения" description="Сохраните файл ключа для подключаемого приложения. Позже ключ можно перевыпустить без потери устройств.">
|
||||
<div className="b2-settings"><TextAreaField label="Ключ" value={issued} readOnly rows={6} />
|
||||
<Button onClick={downloadIssuedKey}><Icon name="download" />Скачать файл ключа</Button>
|
||||
<Button onClick={() => navigator.clipboard.writeText(issued).catch(onError)}>Скопировать ключ</Button>
|
||||
<Button onClick={() => setIssued('')}>Скрыть</Button></div>
|
||||
</SettingsCard> : null}
|
||||
{(status?.applications || []).filter((app) => app.authority !== 'host' && app.key !== 'legacy-mission-core').map((app) => <SettingsCard key={app.id} title={app.name}
|
||||
description={Object.keys(app.grants).map((id) => contours.find((item) => item.id === id)?.name || id).join(', ')}>
|
||||
<div className="b2-settings">
|
||||
{app.credentials.map((credential) => <div className="b2-resource" key={credential.client_id}>
|
||||
<div><small>{credential.client_id}</small><StatusBadge tone={credential.enabled ? 'success' : 'neutral'}>{credential.enabled ? 'Действует' : 'Отозван'}</StatusBadge></div>
|
||||
{credential.enabled ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: credential.client_id }, text: `Отозвать ключ приложения «${app.name}»? Подключённый клиент потеряет доступ.` })}>Отозвать</Button> : null}
|
||||
</div>)}
|
||||
<Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: true }, text: `Выдать новый ключ для «${app.name}»? Предыдущие ключи этого приложения перестанут работать. Устройства и история сохранятся.` })}>{app.credentials.some((c) => c.enabled) ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button>
|
||||
</div>
|
||||
</SettingsCard>)}
|
||||
{canManage ? <SettingsCard title="Подключить новое приложение" description="Для каждого приложения создайте отдельный ключ. Несколько приложений могут работать с одним контуром независимо.">
|
||||
<div className="b2-settings"><TextField label="Название приложения" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
<TextField label="Код приложения" value={key} placeholder="robot2b-client" onChange={(e) => setKey(e.target.value)} />
|
||||
<Select label="Контур" value={contour} onChange={setContour} options={contours.map((item) => ({ value: item.id, label: item.name }))} />
|
||||
<Button loading={pending === 'application-create'} disabled={busy || !contour || !name.trim() || !/^[a-z][a-z0-9-]{0,63}$/.test(key)}
|
||||
onClick={() => void run('application-create', { key, name, contourId: contour })}>Создать приложение</Button></div>
|
||||
</SettingsCard> : <SettingsCard title="Доступ к контуру" description="Управление ключами доступно через управляющее подключение VPS." />}
|
||||
</SettingsCard> : form === 'project' ? <SettingsCard title="Проект Device Core"><div className="b2-settings">
|
||||
<ResourceRow title={selected?.name} metadata="Контур VPS" /><Select label="Проект" value={targetProject} onChange={setTargetProject} options={projects.map((p) => ({ value: p.projectRef, label: p.name }))} />
|
||||
<div className="b2-actions"><Button disabled={busy} onClick={() => setForm(null)}>Отмена</Button><Button disabled={busy || !targetProject} loading={pending === 'link'} onClick={() => void run('link', { contourId, targetProjectRef: targetProject })}>Связать</Button></div>
|
||||
</div></SettingsCard> : !selected ? <SettingsCard title="Контуры" actions={canManage ? <IconButton label="Создать контур" disabled={busy} onClick={() => begin('contour')}><Icon name="plus" /></IconButton> : undefined}>
|
||||
<ResourceList>{contours.map((item) => {
|
||||
const link = status?.links?.find((value) => value.contourId === item.id), projectName = projects.find((p) => p.projectRef === link?.projectRef)?.name;
|
||||
return <li key={item.id}><ResourceRow title={item.name} metadata={projectName ? `Проект: ${projectName}` : 'Проект не связан'} actions={<IconButton label={`Открыть контур ${item.name}`} disabled={busy} onClick={() => { setContourId(item.id); setApplicationId(''); }}><Icon name="chevron-right" /></IconButton>} /></li>;
|
||||
})}</ResourceList>{!contours.length ? <p>Контуров пока нет</p> : null}
|
||||
</SettingsCard> : !application ? <>
|
||||
<SettingsCard title={selected.name} actions={<StatusBadge>Контур</StatusBadge>}><ResourceRow title={projects.find((p) => p.projectRef === linkedProject)?.name || 'Не выбран'} metadata="Проект Device Core" actions={!linkedProject ? <Button disabled={busy} onClick={() => begin('project')}>Выбрать проект</Button> : undefined} /></SettingsCard>
|
||||
<SettingsCard title="Приложения" actions={canManage ? <IconButton label={`Добавить приложение в ${selected.name}`} disabled={busy} onClick={() => begin('application')}><Icon name="plus" /></IconButton> : undefined}>
|
||||
<ResourceList>{applications.filter((app) => showInactive || !inactive(app)).map((app) => <li key={app.id}><ResourceRow title={app.name} status={<StatusBadge tone={app.credentials.some((c) => c.enabled) ? 'success' : 'neutral'}>{app.credentials.some((c) => c.enabled) ? 'Ключ действует' : 'Нет активного ключа'}</StatusBadge>} actions={<IconButton label={`Ключи ${app.name}`} disabled={busy} onClick={() => { setApplicationId(app.id); setShowHistory(false); }}><Icon name="key" /></IconButton>} /></li>)}</ResourceList>
|
||||
{!applications.filter((app) => showInactive || !inactive(app)).length ? <p>Нет подключённых приложений</p> : null}
|
||||
{applications.some(inactive) ? <Button variant="ghost" onClick={() => setShowInactive(!showInactive)}>{showInactive ? 'Скрыть отключённые' : `Отключённые приложения · ${applications.filter(inactive).length}`}</Button> : null}
|
||||
</SettingsCard>
|
||||
</> : <>
|
||||
{issued ? <SettingsCard title="Новый ключ" description="Сохраните ключ — повторный просмотр недоступен."><div className="b2-settings"><TextAreaField label="Ключ подключения" value={issued} readOnly rows={4} /><div className="b2-actions"><Button onClick={downloadIssuedKey}>Скачать файл</Button><Button onClick={() => navigator.clipboard.writeText(issued).catch(onError)}>Скопировать</Button><Button onClick={() => setIssued('')}>Скрыть</Button></div></div></SettingsCard> : null}
|
||||
<SettingsCard title="Ключи приложения" actions={<Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: application.id, replace: true }, text: `Выдать новый ключ для «${application.name}»? Прежний ключ перестанет работать. Устройства сохранятся.` })}>{application.credentials.some((c) => c.enabled) ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button>}>
|
||||
<ResourceList>{application.credentials.filter((c) => c.enabled || showHistory).map((credential) => <li key={credential.client_id}><ResourceRow metadata="ID ключа" title={<code className="b2-key-id" title={credential.client_id}>{credential.client_id}</code>} status={<StatusBadge tone={credential.enabled ? 'success' : 'neutral'}>{credential.enabled ? 'Действует' : 'Отозван'}</StatusBadge>} actions={credential.enabled ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: credential.client_id }, text: `Отозвать ключ приложения «${application.name}»?` })}>Отозвать</Button> : undefined} /></li>)}</ResourceList>
|
||||
{!application.credentials.some((c) => c.enabled) ? <p>Нет активного ключа</p> : null}
|
||||
{application.credentials.some((c) => !c.enabled) ? <Button variant="ghost" onClick={() => setShowHistory(!showHistory)}>{showHistory ? 'Скрыть историю' : `История ключей · ${application.credentials.filter((c) => !c.enabled).length}`}</Button> : null}
|
||||
</SettingsCard>
|
||||
</>}
|
||||
</> : null}
|
||||
</div>
|
||||
</FeatureSettingsWindow>
|
||||
<ConfirmationModal open={Boolean(confirm)} title="Изменить доступ приложения" description={confirm?.text}
|
||||
confirmLabel="Продолжить" cancelLabel="Отмена" onClose={() => setConfirm(null)}
|
||||
onConfirm={async () => { if (confirm) await run(confirm.action, confirm.fields); setConfirm(null); }} />
|
||||
<ConfirmationModal open={Boolean(confirm)} title="Ключ приложения" description={confirm?.text} confirmLabel="Подтвердить" cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && await run(confirm.action, confirm.fields)) setConfirm(null); }} />
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
.b2-settings { display: grid; gap: var(--nodedc-space-md, 16px); }
|
||||
.b2-settings p { margin: 0; font-size: var(--nodedc-font-size-sm); color: var(--nodedc-text-secondary); }
|
||||
.b2-resource { display: flex; align-items: center; justify-content: space-between; gap: var(--nodedc-space-sm, 8px); flex-wrap: wrap; }
|
||||
.b2-resource > div { display: grid; gap: 4px; min-width: 0; }
|
||||
.b2-resource strong { font-size: var(--nodedc-font-size-sm); }
|
||||
.b2-resource small { font-size: var(--nodedc-font-size-xs); overflow-wrap: anywhere; color: var(--nodedc-text-secondary); }
|
||||
.b2-settings { display: grid; gap: var(--nodedc-space-md); }
|
||||
.b2-settings p, .b2-path { margin: 0; font-size: var(--nodedc-font-size-sm); color: var(--nodedc-text-secondary); }
|
||||
.b2-path { overflow-wrap: anywhere; }
|
||||
.b2-actions { display: flex; gap: var(--nodedc-space-sm); flex-wrap: wrap; justify-content: flex-end; }
|
||||
.b2-key-id { font-family: inherit; font-size: var(--nodedc-font-size-sm); overflow-wrap: anywhere; font-weight: 400; }
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { b2Request, type B2Device } from './api';
|
||||
export type B2HostState = { hostRef: string; name: string; endpoint: string; contours: number; reachable: boolean; checkedAt: string; devices: number | null };
|
||||
export type B2Inventory = { items: Array<B2Device & { hostRef: string; hostName: string }>; hosts: B2HostState[] };
|
||||
export function useB2Inventory(projectRef: string, refreshSignal: unknown) {
|
||||
const [data, setData] = useState<B2Inventory | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
let active = true, timer: ReturnType<typeof setTimeout>;
|
||||
async function load() {
|
||||
try {
|
||||
const next = await b2Request<B2Inventory>(projectRef, '', 'inventory');
|
||||
if (active) { setData(next); setError(''); }
|
||||
} catch (reason) {
|
||||
if (active) { setData(null); setError(reason instanceof Error ? reason.message : 'VPS недоступен'); }
|
||||
} finally { if (active) timer = setTimeout(load, 30_000); }
|
||||
}
|
||||
void load();
|
||||
return () => { active = false; clearTimeout(timer); };
|
||||
}, [projectRef, refreshSignal]);
|
||||
return { data, error };
|
||||
}
|
||||
Reference in New Issue
Block a user