refactor(client): view unmount lifecycle, WS unsubscribe, lazy-split core views, Toast bus, Command Palette & diff hunks
This commit is contained in:
parent
67137056f8
commit
3a28a2332f
11 changed files with 831 additions and 132 deletions
|
|
@ -8,17 +8,52 @@ const LAZY_CHUNK_BUDGET_BYTES = 20 * 1024;
|
||||||
const clientDir = path.resolve('src/client');
|
const clientDir = path.resolve('src/client');
|
||||||
const outDir = path.resolve('dist/public');
|
const outDir = path.resolve('dist/public');
|
||||||
|
|
||||||
|
function normalizeOutKey(rawPath: string): string {
|
||||||
|
const rel = path.relative(outDir, path.resolve(rawPath));
|
||||||
|
return rel.replace(/\\/g, '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectSyncImports(
|
||||||
|
metaOutputs: Record<string, esbuild.Metafile['outputs'][string]>,
|
||||||
|
entryKey: string,
|
||||||
|
): string[] {
|
||||||
|
const visited = new Set<string>();
|
||||||
|
const queue: string[] = [entryKey];
|
||||||
|
|
||||||
|
while (queue.length > 0) {
|
||||||
|
const cur = queue.shift()!;
|
||||||
|
if (visited.has(cur)) continue;
|
||||||
|
visited.add(cur);
|
||||||
|
|
||||||
|
const matchEntry = Object.entries(metaOutputs).find(
|
||||||
|
([outPath]) => normalizeOutKey(outPath) === cur,
|
||||||
|
);
|
||||||
|
if (!matchEntry) continue;
|
||||||
|
|
||||||
|
for (const imp of matchEntry[1].imports) {
|
||||||
|
if (imp.kind !== 'import-statement') continue;
|
||||||
|
const targetKey = normalizeOutKey(imp.path);
|
||||||
|
if (!visited.has(targetKey)) {
|
||||||
|
queue.push(targetKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...visited];
|
||||||
|
}
|
||||||
|
|
||||||
async function buildClient(): Promise<void> {
|
async function buildClient(): Promise<void> {
|
||||||
fs.rmSync(outDir, { recursive: true, force: true });
|
fs.rmSync(outDir, { recursive: true, force: true });
|
||||||
fs.mkdirSync(outDir, { recursive: true });
|
fs.mkdirSync(outDir, { recursive: true });
|
||||||
|
|
||||||
await esbuild.build({
|
const jsResult = await esbuild.build({
|
||||||
entryPoints: [path.join(clientDir, 'ts', 'main.ts')],
|
entryPoints: [path.join(clientDir, 'ts', 'main.ts')],
|
||||||
bundle: true,
|
bundle: true,
|
||||||
format: 'esm',
|
format: 'esm',
|
||||||
splitting: true,
|
splitting: true,
|
||||||
minify: true,
|
minify: true,
|
||||||
sourcemap: false,
|
sourcemap: false,
|
||||||
|
metafile: true,
|
||||||
target: 'es2020',
|
target: 'es2020',
|
||||||
outdir: outDir,
|
outdir: outDir,
|
||||||
entryNames: '[name]',
|
entryNames: '[name]',
|
||||||
|
|
@ -46,18 +81,22 @@ async function buildClient(): Promise<void> {
|
||||||
fs.copyFileSync(path.join(clientDir, asset), path.join(outDir, asset));
|
fs.copyFileSync(path.join(clientDir, asset), path.join(outDir, asset));
|
||||||
}
|
}
|
||||||
|
|
||||||
const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js'];
|
const syncJsChunks = jsResult.metafile
|
||||||
|
? collectSyncImports(jsResult.metafile.outputs, 'main.js').filter((k) => k !== 'main.js')
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js', ...syncJsChunks];
|
||||||
let totalRaw = 0;
|
let totalRaw = 0;
|
||||||
let totalGzip = 0;
|
let totalGzip = 0;
|
||||||
|
|
||||||
for (const file of coreAssets) {
|
for (const file of coreAssets) {
|
||||||
const buf = fs.readFileSync(path.join(outDir, file));
|
const fullPath = path.join(outDir, file);
|
||||||
|
if (!fs.existsSync(fullPath)) continue;
|
||||||
|
const buf = fs.readFileSync(fullPath);
|
||||||
const gz = zlib.gzipSync(buf, { level: 9 });
|
const gz = zlib.gzipSync(buf, { level: 9 });
|
||||||
totalRaw += buf.length;
|
totalRaw += buf.length;
|
||||||
totalGzip += gz.length;
|
totalGzip += gz.length;
|
||||||
console.log(
|
console.log(` ${file.padEnd(24)} raw=${buf.length}B gzip=${gz.length}B`);
|
||||||
` ${file.padEnd(14)} raw=${buf.length}B gzip=${gz.length}B`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const chunksDir = path.join(outDir, 'chunks');
|
const chunksDir = path.join(outDir, 'chunks');
|
||||||
|
|
@ -65,7 +104,8 @@ async function buildClient(): Promise<void> {
|
||||||
for (const chunk of fs.readdirSync(chunksDir).sort()) {
|
for (const chunk of fs.readdirSync(chunksDir).sort()) {
|
||||||
const cBuf = fs.readFileSync(path.join(chunksDir, chunk));
|
const cBuf = fs.readFileSync(path.join(chunksDir, chunk));
|
||||||
const cGz = zlib.gzipSync(cBuf, { level: 9 });
|
const cGz = zlib.gzipSync(cBuf, { level: 9 });
|
||||||
console.log(` chunks/${chunk.padEnd(28)} raw=${cBuf.length}B gzip=${cGz.length}B`);
|
const syncTag = syncJsChunks.includes(`chunks/${chunk}`) ? ' [sync-core]' : '';
|
||||||
|
console.log(` chunks/${chunk.padEnd(28)} raw=${cBuf.length}B gzip=${cGz.length}B${syncTag}`);
|
||||||
if (!chunk.startsWith('terminal-view-') && cGz.length >= LAZY_CHUNK_BUDGET_BYTES) {
|
if (!chunk.startsWith('terminal-view-') && cGz.length >= LAZY_CHUNK_BUDGET_BYTES) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Lazy chunk ${chunk} (${cGz.length}B gzipped) exceeded 20KB budget (${LAZY_CHUNK_BUDGET_BYTES}B)`,
|
`Lazy chunk ${chunk} (${cGz.length}B gzipped) exceeded 20KB budget (${LAZY_CHUNK_BUDGET_BYTES}B)`,
|
||||||
|
|
|
||||||
|
|
@ -699,3 +699,87 @@ dialog.ai-drawer[open] {
|
||||||
padding: 6px 10px;
|
padding: 6px 10px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.sr-only-focusable:focus {
|
||||||
|
position: static;
|
||||||
|
width: auto;
|
||||||
|
height: auto;
|
||||||
|
overflow: visible;
|
||||||
|
clip: auto;
|
||||||
|
white-space: normal;
|
||||||
|
display: inline-block;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
padding: 6px 10px;
|
||||||
|
border: 1px solid var(--accent);
|
||||||
|
background: var(--bg-panel);
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-region {
|
||||||
|
position: fixed;
|
||||||
|
right: 12px;
|
||||||
|
bottom: 12px;
|
||||||
|
z-index: 40;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
max-width: min(380px, calc(100vw - 24px));
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-item {
|
||||||
|
pointer-events: auto;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: var(--bg-panel);
|
||||||
|
color: var(--fg);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-ok {
|
||||||
|
border-color: var(--ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-warn {
|
||||||
|
border-color: var(--warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-err {
|
||||||
|
border-color: var(--err);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmd-palette-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
max-height: 55vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmd-palette-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmd-palette-item.active {
|
||||||
|
border-color: var(--accent);
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.diff-hunk-sep {
|
||||||
|
padding: 2px 6px;
|
||||||
|
margin: 4px 0;
|
||||||
|
border-top: 1px dashed var(--border);
|
||||||
|
border-bottom: 1px dashed var(--border);
|
||||||
|
color: var(--fg-muted);
|
||||||
|
font-size: 0.78rem;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app" class="app-shell">
|
<div id="app" class="app-shell">
|
||||||
|
<a href="#view-root" class="sr-only sr-only-focusable">Skip to main content</a>
|
||||||
<header id="topbar" class="topbar" hidden>
|
<header id="topbar" class="topbar" hidden>
|
||||||
<div class="topbar-brand">
|
<div class="topbar-brand">
|
||||||
<span class="brand-mark">>_ GCOORD</span>
|
<span class="brand-mark">>_ GCOORD</span>
|
||||||
|
|
@ -33,6 +34,7 @@
|
||||||
<option value="tokyo-night">tokyo-night</option>
|
<option value="tokyo-night">tokyo-night</option>
|
||||||
<option value="high-contrast">high-contrast</option>
|
<option value="high-contrast">high-contrast</option>
|
||||||
</select>
|
</select>
|
||||||
|
<button id="cmd-palette-btn" type="button" class="btn btn-sm" title="Command Palette (Ctrl+K / Alt+K)">[CMD]</button>
|
||||||
<button id="safe-toggle-btn" type="button" class="btn btn-sm" aria-pressed="false">[SAFE: OFF]</button>
|
<button id="safe-toggle-btn" type="button" class="btn btn-sm" aria-pressed="false">[SAFE: OFF]</button>
|
||||||
<button id="panic-btn" type="button" class="btn btn-sm btn-danger">[PANIC LOCK]</button>
|
<button id="panic-btn" type="button" class="btn btn-sm btn-danger">[PANIC LOCK]</button>
|
||||||
<button id="logout-btn" type="button" class="btn btn-sm">[LOGOUT]</button>
|
<button id="logout-btn" type="button" class="btn btn-sm">[LOGOUT]</button>
|
||||||
|
|
@ -169,6 +171,19 @@
|
||||||
</form>
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
|
<!-- Toast Region -->
|
||||||
|
<div id="toast-region" class="toast-region" aria-live="polite" aria-atomic="false"></div>
|
||||||
|
|
||||||
|
<!-- Command Palette Dialog -->
|
||||||
|
<dialog id="dialog-cmd" class="dialog-wide" aria-labelledby="dialog-cmd-title">
|
||||||
|
<div class="row-between">
|
||||||
|
<h1 id="dialog-cmd-title">Command Palette</h1>
|
||||||
|
<button id="cmd-palette-close" type="button" class="btn btn-sm">Esc</button>
|
||||||
|
</div>
|
||||||
|
<input id="cmd-palette-input" type="search" class="input-full" placeholder="Jump to route, server, terminal, SFTP, or security action..." autocomplete="off">
|
||||||
|
<div id="cmd-palette-list" class="cmd-palette-list" role="listbox" aria-label="Commands"></div>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
<script type="module" src="/main.js"></script>
|
<script type="module" src="/main.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
161
src/client/ts/command-palette.ts
Normal file
161
src/client/ts/command-palette.ts
Normal file
|
|
@ -0,0 +1,161 @@
|
||||||
|
import { el, type ClientState } from './state.js';
|
||||||
|
|
||||||
|
interface PaletteAction {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
hint: string;
|
||||||
|
run: () => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CommandPaletteContext {
|
||||||
|
state: ClientState;
|
||||||
|
navigate: (hash: string) => void;
|
||||||
|
toggleSafeMode: () => Promise<void>;
|
||||||
|
lockVault: () => Promise<void>;
|
||||||
|
triggerPanic: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function openCommandPalette(ctx: CommandPaletteContext): void {
|
||||||
|
const dialog = document.getElementById('dialog-cmd') as HTMLDialogElement | null;
|
||||||
|
const input = document.getElementById('cmd-palette-input') as HTMLInputElement | null;
|
||||||
|
const listEl = document.getElementById('cmd-palette-list') as HTMLElement | null;
|
||||||
|
const closeBtn = document.getElementById('cmd-palette-close') as HTMLButtonElement | null;
|
||||||
|
if (!dialog || !input || !listEl || !closeBtn) return;
|
||||||
|
|
||||||
|
const actions: PaletteAction[] = [
|
||||||
|
{ id: 'nav-dashboard', label: 'Go to Dashboard', hint: '#dashboard', run: () => ctx.navigate('#dashboard') },
|
||||||
|
{ id: 'nav-systems', label: 'Go to Systems', hint: '#systems', run: () => ctx.navigate('#systems') },
|
||||||
|
{ id: 'nav-terminal', label: 'Go to Terminal', hint: '#terminal', run: () => ctx.navigate('#terminal') },
|
||||||
|
{ id: 'nav-sftp', label: 'Go to SFTP Files', hint: '#sftp', run: () => ctx.navigate('#sftp') },
|
||||||
|
{ id: 'nav-workflows', label: 'Go to Workflows & Broadcast', hint: '#workflows', run: () => ctx.navigate('#workflows') },
|
||||||
|
{ id: 'nav-alerts', label: 'Go to Alerts & Incidents', hint: '#alerts', run: () => ctx.navigate('#alerts') },
|
||||||
|
{ id: 'nav-config', label: 'Go to Config & Diffs', hint: '#config', run: () => ctx.navigate('#config') },
|
||||||
|
{ id: 'nav-vault', label: 'Go to Vault & Keys', hint: '#vault', run: () => ctx.navigate('#vault') },
|
||||||
|
{ id: 'nav-settings', label: 'Go to Settings & Audit', hint: '#settings', run: () => ctx.navigate('#settings') },
|
||||||
|
{
|
||||||
|
id: 'act-safemode',
|
||||||
|
label: ctx.state.safeMode ? 'Disable Safe Mode' : 'Enable Safe Mode',
|
||||||
|
hint: 'security',
|
||||||
|
run: () => ctx.toggleSafeMode(),
|
||||||
|
},
|
||||||
|
{ id: 'act-lockvault', label: 'Lock Vault (Write-Only)', hint: 'vault', run: () => ctx.lockVault() },
|
||||||
|
{ id: 'act-panic', label: 'Engage Panic Lock', hint: 'danger', run: () => ctx.triggerPanic() },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const srv of ctx.state.overview?.servers ?? []) {
|
||||||
|
const srvId = typeof srv.id === 'string' ? srv.id : String(srv.id ?? '');
|
||||||
|
if (!srvId) continue;
|
||||||
|
const srvName = typeof srv.name === 'string' ? srv.name : srvId;
|
||||||
|
const srvHost = typeof srv.host === 'string' ? srv.host : '';
|
||||||
|
actions.push(
|
||||||
|
{
|
||||||
|
id: `srv-${srvId}`,
|
||||||
|
label: `Server: ${srvName}${srvHost ? ` (${srvHost})` : ''}`,
|
||||||
|
hint: `#server/${srvId}`,
|
||||||
|
run: () => ctx.navigate(`#server/${encodeURIComponent(srvId)}`),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: `term-${srvId}`,
|
||||||
|
label: `Open Terminal on ${srvName}`,
|
||||||
|
hint: 'ssh pty',
|
||||||
|
run: () => ctx.navigate(`#terminal?server=${encodeURIComponent(srvId)}`),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: `sftp-${srvId}`,
|
||||||
|
label: `Browse SFTP on ${srvName}`,
|
||||||
|
hint: 'files',
|
||||||
|
run: () => ctx.navigate(`#sftp?server=${encodeURIComponent(srvId)}`),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let selectedIdx = 0;
|
||||||
|
let filtered: PaletteAction[] = actions;
|
||||||
|
|
||||||
|
const close = () => {
|
||||||
|
cleanup();
|
||||||
|
if (dialog.open) dialog.close();
|
||||||
|
};
|
||||||
|
|
||||||
|
const runAction = (act: PaletteAction | undefined) => {
|
||||||
|
if (!act) return;
|
||||||
|
close();
|
||||||
|
void act.run();
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderList = () => {
|
||||||
|
const q = input.value.trim().toLowerCase();
|
||||||
|
filtered = q
|
||||||
|
? actions.filter(
|
||||||
|
(a) =>
|
||||||
|
a.label.toLowerCase().includes(q) ||
|
||||||
|
a.hint.toLowerCase().includes(q),
|
||||||
|
)
|
||||||
|
: actions;
|
||||||
|
if (selectedIdx >= filtered.length) selectedIdx = Math.max(0, filtered.length - 1);
|
||||||
|
|
||||||
|
listEl.replaceChildren();
|
||||||
|
if (filtered.length === 0) {
|
||||||
|
listEl.append(el('div', { class: 'muted' }, 'No matching commands.'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
filtered.slice(0, 14).forEach((act, idx) => {
|
||||||
|
const btn = el(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
class: `btn cmd-palette-item ${idx === selectedIdx ? 'active' : ''}`,
|
||||||
|
role: 'option',
|
||||||
|
'aria-selected': idx === selectedIdx ? 'true' : 'false',
|
||||||
|
},
|
||||||
|
el('span', {}, act.label),
|
||||||
|
el('span', { class: 'muted mono' }, act.hint),
|
||||||
|
);
|
||||||
|
btn.addEventListener('click', () => runAction(act));
|
||||||
|
listEl.append(btn);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const onInput = () => {
|
||||||
|
selectedIdx = 0;
|
||||||
|
renderList();
|
||||||
|
};
|
||||||
|
|
||||||
|
const onKeyDown = (ev: KeyboardEvent) => {
|
||||||
|
if (ev.key === 'ArrowDown') {
|
||||||
|
ev.preventDefault();
|
||||||
|
if (filtered.length > 0) {
|
||||||
|
selectedIdx = (selectedIdx + 1) % Math.min(filtered.length, 14);
|
||||||
|
renderList();
|
||||||
|
}
|
||||||
|
} else if (ev.key === 'ArrowUp') {
|
||||||
|
ev.preventDefault();
|
||||||
|
const len = Math.min(filtered.length, 14);
|
||||||
|
if (len > 0) {
|
||||||
|
selectedIdx = (selectedIdx - 1 + len) % len;
|
||||||
|
renderList();
|
||||||
|
}
|
||||||
|
} else if (ev.key === 'Enter') {
|
||||||
|
ev.preventDefault();
|
||||||
|
runAction(filtered[selectedIdx]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
input.removeEventListener('input', onInput);
|
||||||
|
input.removeEventListener('keydown', onKeyDown);
|
||||||
|
closeBtn.removeEventListener('click', close);
|
||||||
|
dialog.removeEventListener('close', cleanup);
|
||||||
|
};
|
||||||
|
|
||||||
|
input.value = '';
|
||||||
|
renderList();
|
||||||
|
input.addEventListener('input', onInput);
|
||||||
|
input.addEventListener('keydown', onKeyDown);
|
||||||
|
closeBtn.addEventListener('click', close);
|
||||||
|
dialog.addEventListener('close', cleanup);
|
||||||
|
|
||||||
|
if (!dialog.open) dialog.showModal();
|
||||||
|
input.focus();
|
||||||
|
}
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
import { collapseDiffHunks, type CollapsedDiffEntry } from '../../shared/diff.js';
|
||||||
import { apiFetch } from './api.js';
|
import { apiFetch } from './api.js';
|
||||||
import {
|
import {
|
||||||
el,
|
el,
|
||||||
|
|
@ -12,6 +13,7 @@ export interface DiffModalData {
|
||||||
source: string;
|
source: string;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>;
|
lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>;
|
||||||
|
collapsedLines?: CollapsedDiffEntry[];
|
||||||
onRollback: () => Promise<void>;
|
onRollback: () => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -232,16 +234,56 @@ export function openDiffModal(data: DiffModalData): void {
|
||||||
const closeBtn = document.getElementById('dialog-diff-close') as HTMLButtonElement;
|
const closeBtn = document.getElementById('dialog-diff-close') as HTMLButtonElement;
|
||||||
const rollbackBtn = document.getElementById('dialog-diff-rollback') as HTMLButtonElement;
|
const rollbackBtn = document.getElementById('dialog-diff-rollback') as HTMLButtonElement;
|
||||||
|
|
||||||
metaEl.textContent = `${data.filePath} — Revision #${data.revisionId} (${data.source})`;
|
const hunks = data.collapsedLines ?? collapseDiffHunks(data.lines);
|
||||||
bodyEl.replaceChildren();
|
const hasHunk = hunks.some((entry) => entry.type === 'hunk');
|
||||||
for (const line of data.lines) {
|
let expanded = hunks.length === 0 || !hasHunk;
|
||||||
const prefix = line.type === 'add' ? '+ ' : line.type === 'del' ? '- ' : ' ';
|
|
||||||
const cls =
|
const toggleBtn = el(
|
||||||
line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : '';
|
'button',
|
||||||
bodyEl.append(el('div', { class: cls }, `${prefix}${line.text}`));
|
{ type: 'button', class: 'btn btn-sm', style: 'margin-left:8px' },
|
||||||
|
expanded ? 'Full Diff' : 'Expand Full Diff',
|
||||||
|
);
|
||||||
|
if (!hasHunk) {
|
||||||
|
toggleBtn.hidden = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const renderLines = () => {
|
||||||
|
bodyEl.replaceChildren();
|
||||||
|
if (expanded) {
|
||||||
|
for (const line of data.lines) {
|
||||||
|
const prefix = line.type === 'add' ? '+ ' : line.type === 'del' ? '- ' : ' ';
|
||||||
|
const cls = line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : '';
|
||||||
|
bodyEl.append(el('div', { class: cls }, `${prefix}${line.text}`));
|
||||||
|
}
|
||||||
|
toggleBtn.textContent = 'Collapse Context';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const entry of hunks) {
|
||||||
|
if (entry.type === 'hunk') {
|
||||||
|
bodyEl.append(el('div', { class: 'diff-hunk-sep' }, entry.text));
|
||||||
|
} else {
|
||||||
|
const prefix = entry.type === 'add' ? '+ ' : entry.type === 'del' ? '- ' : ' ';
|
||||||
|
const cls = entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : '';
|
||||||
|
bodyEl.append(el('div', { class: cls }, `${prefix}${entry.text}`));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
toggleBtn.textContent = 'Expand Full Diff';
|
||||||
|
};
|
||||||
|
|
||||||
|
metaEl.replaceChildren(
|
||||||
|
document.createTextNode(`${data.filePath} — Revision #${data.revisionId} (${data.source})`),
|
||||||
|
toggleBtn,
|
||||||
|
);
|
||||||
|
renderLines();
|
||||||
|
|
||||||
|
const onToggle = () => {
|
||||||
|
expanded = !expanded;
|
||||||
|
renderLines();
|
||||||
|
};
|
||||||
|
|
||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
|
toggleBtn.removeEventListener('click', onToggle);
|
||||||
closeBtn.removeEventListener('click', onClose);
|
closeBtn.removeEventListener('click', onClose);
|
||||||
rollbackBtn.removeEventListener('click', onRollbackClick);
|
rollbackBtn.removeEventListener('click', onRollbackClick);
|
||||||
dialog.removeEventListener('close', cleanup);
|
dialog.removeEventListener('close', cleanup);
|
||||||
|
|
@ -262,6 +304,7 @@ export function openDiffModal(data: DiffModalData): void {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
toggleBtn.addEventListener('click', onToggle);
|
||||||
closeBtn.addEventListener('click', onClose);
|
closeBtn.addEventListener('click', onClose);
|
||||||
rollbackBtn.addEventListener('click', onRollbackClick);
|
rollbackBtn.addEventListener('click', onRollbackClick);
|
||||||
dialog.addEventListener('close', cleanup);
|
dialog.addEventListener('close', cleanup);
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,10 @@ import {
|
||||||
SAFE_MODE_STORAGE_KEY,
|
SAFE_MODE_STORAGE_KEY,
|
||||||
THEME_STORAGE_KEY,
|
THEME_STORAGE_KEY,
|
||||||
applyTheme,
|
applyTheme,
|
||||||
|
el,
|
||||||
|
extractErrorMessage,
|
||||||
|
flushViewCleanups,
|
||||||
|
getDashboardLivePatchers,
|
||||||
initialDeviceSafeMode,
|
initialDeviceSafeMode,
|
||||||
type ClientAuthRequirements,
|
type ClientAuthRequirements,
|
||||||
type ClientSecuritySettings,
|
type ClientSecuritySettings,
|
||||||
|
|
@ -19,16 +23,7 @@ import {
|
||||||
type ConfigOverview,
|
type ConfigOverview,
|
||||||
type RouteId,
|
type RouteId,
|
||||||
} from './state.js';
|
} from './state.js';
|
||||||
import { renderAuthView } from './views/auth-view.js';
|
import { showToast } from './toast.js';
|
||||||
import { renderConfigView } from './views/config-view.js';
|
|
||||||
import {
|
|
||||||
patchDashboardServerStates,
|
|
||||||
patchDashboardServerTick,
|
|
||||||
renderDashboardView,
|
|
||||||
} from './views/dashboard-view.js';
|
|
||||||
import { renderServerDetailView } from './views/server-detail-view.js';
|
|
||||||
import { renderSettingsView } from './views/settings-view.js';
|
|
||||||
import { renderVaultView } from './views/vault-view.js';
|
|
||||||
import { MultiplexWsClient } from './ws-client.js';
|
import { MultiplexWsClient } from './ws-client.js';
|
||||||
|
|
||||||
const VALID_ROUTES = new Set<RouteId>([
|
const VALID_ROUTES = new Set<RouteId>([
|
||||||
|
|
@ -167,12 +162,47 @@ async function refreshOverview(): Promise<void> {
|
||||||
updateTopBarUi();
|
updateTopBarUi();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let activeViewCleanup: (() => void) | null = null;
|
||||||
|
let renderSeq = 0;
|
||||||
|
|
||||||
|
function runActiveCleanup(): void {
|
||||||
|
if (activeViewCleanup) {
|
||||||
|
try {
|
||||||
|
activeViewCleanup();
|
||||||
|
} catch {
|
||||||
|
// Ignore view unmount errors
|
||||||
|
}
|
||||||
|
activeViewCleanup = null;
|
||||||
|
}
|
||||||
|
flushViewCleanups();
|
||||||
|
}
|
||||||
|
|
||||||
|
function captureCleanup(seq: number, result: unknown): void {
|
||||||
|
if (typeof result !== 'function') return;
|
||||||
|
const fn = result as () => void;
|
||||||
|
if (seq !== renderSeq) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch {
|
||||||
|
// Ignore stale cleanup error
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
activeViewCleanup = fn;
|
||||||
|
}
|
||||||
|
|
||||||
async function renderCurrentView(): Promise<void> {
|
async function renderCurrentView(): Promise<void> {
|
||||||
|
const mySeq = ++renderSeq;
|
||||||
|
runActiveCleanup();
|
||||||
|
|
||||||
const root = document.getElementById('view-root')!;
|
const root = document.getElementById('view-root')!;
|
||||||
updateTopBarUi();
|
updateTopBarUi();
|
||||||
|
|
||||||
|
try {
|
||||||
if (!state.authenticated) {
|
if (!state.authenticated) {
|
||||||
await renderAuthView(
|
const { renderAuthView } = await import('./views/auth-view.js');
|
||||||
|
if (mySeq !== renderSeq) return;
|
||||||
|
const cleanup = await renderAuthView(
|
||||||
root,
|
root,
|
||||||
state.bootstrapped,
|
state.bootstrapped,
|
||||||
state.safeMode,
|
state.safeMode,
|
||||||
|
|
@ -181,32 +211,50 @@ async function renderCurrentView(): Promise<void> {
|
||||||
await bootstrapApp();
|
await bootstrapApp();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
captureCleanup(mySeq, cleanup);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!state.overview) {
|
if (!state.overview) {
|
||||||
await refreshOverview();
|
await refreshOverview();
|
||||||
|
if (mySeq !== renderSeq) return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const route = state.route;
|
const route = state.route;
|
||||||
if (route === 'dashboard') {
|
if (route === 'dashboard') {
|
||||||
await renderDashboardView(root, state);
|
const { renderDashboardView } = await import('./views/dashboard-view.js');
|
||||||
|
if (mySeq !== renderSeq) return;
|
||||||
|
captureCleanup(mySeq, await renderDashboardView(root, state));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (route === 'server-detail' && state.selectedServerId) {
|
if (route === 'server-detail' && state.selectedServerId) {
|
||||||
|
const { renderServerDetailView } = await import('./views/server-detail-view.js');
|
||||||
|
if (mySeq !== renderSeq) return;
|
||||||
|
captureCleanup(
|
||||||
|
mySeq,
|
||||||
await renderServerDetailView(root, state.selectedServerId, () => {
|
await renderServerDetailView(root, state.selectedServerId, () => {
|
||||||
window.location.hash = '#dashboard';
|
window.location.hash = '#dashboard';
|
||||||
});
|
}),
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (route === 'config') {
|
if (route === 'config') {
|
||||||
|
const { renderConfigView } = await import('./views/config-view.js');
|
||||||
|
if (mySeq !== renderSeq) return;
|
||||||
|
captureCleanup(
|
||||||
|
mySeq,
|
||||||
await renderConfigView(root, state.overview!, state, wsClient, async () => {
|
await renderConfigView(root, state.overview!, state, wsClient, async () => {
|
||||||
await refreshOverview();
|
await refreshOverview();
|
||||||
await renderCurrentView();
|
await renderCurrentView();
|
||||||
});
|
}),
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (route === 'vault') {
|
if (route === 'vault') {
|
||||||
|
const { renderVaultView } = await import('./views/vault-view.js');
|
||||||
|
if (mySeq !== renderSeq) return;
|
||||||
|
captureCleanup(
|
||||||
|
mySeq,
|
||||||
await renderVaultView(
|
await renderVaultView(
|
||||||
root,
|
root,
|
||||||
state,
|
state,
|
||||||
|
|
@ -214,10 +262,15 @@ async function renderCurrentView(): Promise<void> {
|
||||||
await syncStatusAndRender();
|
await syncStatusAndRender();
|
||||||
},
|
},
|
||||||
triggerPanicLock,
|
triggerPanicLock,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (route === 'settings') {
|
if (route === 'settings') {
|
||||||
|
const { renderSettingsView } = await import('./views/settings-view.js');
|
||||||
|
if (mySeq !== renderSeq) return;
|
||||||
|
captureCleanup(
|
||||||
|
mySeq,
|
||||||
await renderSettingsView(
|
await renderSettingsView(
|
||||||
root,
|
root,
|
||||||
state,
|
state,
|
||||||
|
|
@ -227,33 +280,57 @@ async function renderCurrentView(): Promise<void> {
|
||||||
updateTopBarUi();
|
updateTopBarUi();
|
||||||
},
|
},
|
||||||
syncStatusAndRender,
|
syncStatusAndRender,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (route === 'terminal') {
|
if (route === 'terminal') {
|
||||||
const { renderTerminalView } = await import('./views/terminal-view.js');
|
const { renderTerminalView } = await import('./views/terminal-view.js');
|
||||||
await renderTerminalView(root, state, wsClient);
|
if (mySeq !== renderSeq) return;
|
||||||
|
captureCleanup(mySeq, await renderTerminalView(root, state, wsClient));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (route === 'sftp') {
|
if (route === 'sftp') {
|
||||||
const { renderSftpView } = await import('./views/sftp-view.js');
|
const { renderSftpView } = await import('./views/sftp-view.js');
|
||||||
await renderSftpView(root, state);
|
if (mySeq !== renderSeq) return;
|
||||||
|
captureCleanup(mySeq, await renderSftpView(root, state));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (route === 'systems') {
|
if (route === 'systems') {
|
||||||
const { renderSystemsView } = await import('./views/systems-view.js');
|
const { renderSystemsView } = await import('./views/systems-view.js');
|
||||||
await renderSystemsView(root, state, wsClient);
|
if (mySeq !== renderSeq) return;
|
||||||
|
captureCleanup(mySeq, await renderSystemsView(root, state, wsClient));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (route === 'workflows') {
|
if (route === 'workflows') {
|
||||||
const { renderWorkflowsView } = await import('./views/workflows-view.js');
|
const { renderWorkflowsView } = await import('./views/workflows-view.js');
|
||||||
await renderWorkflowsView(root, state, wsClient);
|
if (mySeq !== renderSeq) return;
|
||||||
|
captureCleanup(mySeq, await renderWorkflowsView(root, state, wsClient));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (route === 'alerts') {
|
if (route === 'alerts') {
|
||||||
const { renderAlertsView } = await import('./views/alerts-view.js');
|
const { renderAlertsView } = await import('./views/alerts-view.js');
|
||||||
await renderAlertsView(root, state, wsClient);
|
if (mySeq !== renderSeq) return;
|
||||||
|
captureCleanup(mySeq, await renderAlertsView(root, state, wsClient));
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (mySeq !== renderSeq) return;
|
||||||
|
const msg = extractErrorMessage(err);
|
||||||
|
showToast(`View error: ${msg}`, 'err');
|
||||||
|
const retryBtn = el('button', { type: 'button', class: 'btn btn-primary' }, 'Retry View');
|
||||||
|
retryBtn.addEventListener('click', () => {
|
||||||
|
void renderCurrentView();
|
||||||
|
});
|
||||||
|
root.replaceChildren(
|
||||||
|
el(
|
||||||
|
'section',
|
||||||
|
{ class: 'panel panel-region' },
|
||||||
|
el('h2', { class: 'err-text' }, 'View Render Error'),
|
||||||
|
el('p', { class: 'mono muted' }, msg),
|
||||||
|
retryBtn,
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -261,10 +338,41 @@ async function triggerPanicLock(): Promise<void> {
|
||||||
const confirmed = await confirmDialog('dialog-panic');
|
const confirmed = await confirmDialog('dialog-panic');
|
||||||
if (!confirmed) return;
|
if (!confirmed) return;
|
||||||
await apiFetch('/api/security/panic-lock', { method: 'POST' });
|
await apiFetch('/api/security/panic-lock', { method: 'POST' });
|
||||||
|
showToast('Panic lock engaged: Vault zeroized and sessions revoked.', 'warn');
|
||||||
handleLocalSessionReset(true);
|
handleLocalSessionReset(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function lockVaultAction(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await apiFetch('/api/vault/lock', { method: 'POST', body: {} });
|
||||||
|
state.vaultState = 'locked';
|
||||||
|
updateTopBarUi();
|
||||||
|
showToast('Vault locked (write-only mode).', 'ok');
|
||||||
|
if (state.route === 'vault') void renderCurrentView();
|
||||||
|
} catch (err) {
|
||||||
|
showToast(extractErrorMessage(err), 'err');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleSafeMode(): Promise<void> {
|
||||||
|
const next = !state.safeMode;
|
||||||
|
localStorage.setItem(SAFE_MODE_STORAGE_KEY, next ? '1' : '0');
|
||||||
|
state.safeMode = next;
|
||||||
|
setApiSafeMode(next);
|
||||||
|
if (next) state.elevatedUntil = null;
|
||||||
|
wsClient.send({ type: 'safe-mode', enabled: next });
|
||||||
|
if (state.authenticated) {
|
||||||
|
await apiFetch('/api/auth/safe-mode', {
|
||||||
|
method: 'POST',
|
||||||
|
body: { enabled: next },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
updateTopBarUi();
|
||||||
|
showToast(`Safe Mode ${next ? 'enabled (read-only)' : 'disabled'}.`, next ? 'warn' : 'ok');
|
||||||
|
}
|
||||||
|
|
||||||
function handleLocalSessionReset(panic = false): void {
|
function handleLocalSessionReset(panic = false): void {
|
||||||
|
runActiveCleanup();
|
||||||
wsClient.disconnect();
|
wsClient.disconnect();
|
||||||
setCsrfToken(null);
|
setCsrfToken(null);
|
||||||
state.authenticated = false;
|
state.authenticated = false;
|
||||||
|
|
@ -410,6 +518,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
void renderCurrentView();
|
void renderCurrentView();
|
||||||
}
|
}
|
||||||
} else if (frame.type === 'security:panic-lock') {
|
} else if (frame.type === 'security:panic-lock') {
|
||||||
|
showToast('Panic lock engaged remotely — session terminated.', 'err');
|
||||||
handleLocalSessionReset(true);
|
handleLocalSessionReset(true);
|
||||||
} else if (frame.type === 'config:updated' && state.authenticated) {
|
} else if (frame.type === 'config:updated' && state.authenticated) {
|
||||||
void refreshOverview().then(() => {
|
void refreshOverview().then(() => {
|
||||||
|
|
@ -418,35 +527,80 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else if (frame.type === 'metrics:tick' && state.authenticated && state.route === 'dashboard') {
|
} else if (frame.type === 'metrics:tick' && state.authenticated && state.route === 'dashboard') {
|
||||||
patchDashboardServerTick(frame);
|
getDashboardLivePatchers()?.onTick(frame);
|
||||||
} else if (frame.type === 'servers:state' && state.authenticated && state.route === 'dashboard') {
|
} else if (frame.type === 'servers:state' && state.authenticated && state.route === 'dashboard') {
|
||||||
const needsRefresh = patchDashboardServerStates(frame.states);
|
const needsRefresh = getDashboardLivePatchers()?.onStates(frame.states) ?? false;
|
||||||
if (needsRefresh) {
|
if (needsRefresh) {
|
||||||
void renderCurrentView();
|
void renderCurrentView();
|
||||||
}
|
}
|
||||||
} else if (frame.type === 'alerts:update') {
|
} else if (frame.type === 'alerts:update') {
|
||||||
|
const prevAlerts = state.activeAlertCount;
|
||||||
state.activeAlertCount = frame.activeCount;
|
state.activeAlertCount = frame.activeCount;
|
||||||
updateTopBarUi();
|
updateTopBarUi();
|
||||||
|
if (state.authenticated && frame.activeCount > prevAlerts) {
|
||||||
|
showToast(`Active alerts increased to ${frame.activeCount}.`, 'warn');
|
||||||
|
}
|
||||||
if (state.authenticated && state.route === 'alerts') {
|
if (state.authenticated && state.route === 'alerts') {
|
||||||
void renderCurrentView();
|
void renderCurrentView();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('safe-toggle-btn')!.addEventListener('click', async () => {
|
const openPalette = async () => {
|
||||||
const next = !state.safeMode;
|
if (!state.authenticated) return;
|
||||||
localStorage.setItem(SAFE_MODE_STORAGE_KEY, next ? '1' : '0');
|
const { openCommandPalette } = await import('./command-palette.js');
|
||||||
|
openCommandPalette({
|
||||||
|
state,
|
||||||
|
navigate: (hash) => {
|
||||||
|
window.location.hash = hash;
|
||||||
|
},
|
||||||
|
toggleSafeMode,
|
||||||
|
lockVault: lockVaultAction,
|
||||||
|
triggerPanic: triggerPanicLock,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
document.getElementById('cmd-palette-btn')!.addEventListener('click', () => {
|
||||||
|
void openPalette();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('safe-toggle-btn')!.addEventListener('click', () => {
|
||||||
|
void toggleSafeMode();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('keydown', (ev) => {
|
||||||
|
const active = document.activeElement;
|
||||||
|
if (active && active.closest('.xterm')) return;
|
||||||
|
|
||||||
|
if ((ev.ctrlKey || ev.metaKey || ev.altKey) && ev.key.toLowerCase() === 'k') {
|
||||||
|
if (!state.authenticated) return;
|
||||||
|
ev.preventDefault();
|
||||||
|
void openPalette();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === 's') {
|
||||||
|
if (!state.authenticated || document.querySelector('dialog[open]')) return;
|
||||||
|
ev.preventDefault();
|
||||||
|
window.dispatchEvent(new CustomEvent('gcoord:save'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('storage', (ev) => {
|
||||||
|
if (ev.key === THEME_STORAGE_KEY && ev.newValue) {
|
||||||
|
state.theme = ev.newValue;
|
||||||
|
document.documentElement.setAttribute('data-theme', ev.newValue);
|
||||||
|
updateTopBarUi();
|
||||||
|
} else if (ev.key === SAFE_MODE_STORAGE_KEY && ev.newValue !== null) {
|
||||||
|
const next = ev.newValue === '1';
|
||||||
|
if (next !== state.safeMode) {
|
||||||
state.safeMode = next;
|
state.safeMode = next;
|
||||||
setApiSafeMode(next);
|
setApiSafeMode(next);
|
||||||
if (next) state.elevatedUntil = null;
|
if (next) state.elevatedUntil = null;
|
||||||
wsClient.send({ type: 'safe-mode', enabled: next });
|
wsClient.send({ type: 'safe-mode', enabled: next });
|
||||||
if (state.authenticated) {
|
|
||||||
await apiFetch('/api/auth/safe-mode', {
|
|
||||||
method: 'POST',
|
|
||||||
body: { enabled: next },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
updateTopBarUi();
|
updateTopBarUi();
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('theme-select')!.addEventListener('change', (ev) => {
|
document.getElementById('theme-select')!.addEventListener('change', (ev) => {
|
||||||
|
|
|
||||||
|
|
@ -221,3 +221,40 @@ export function fmtUptime(sec: number): string {
|
||||||
export function extractErrorMessage(err: unknown): string {
|
export function extractErrorMessage(err: unknown): string {
|
||||||
return err instanceof Error ? err.message : String(err);
|
return err instanceof Error ? err.message : String(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface DashboardLivePatchers {
|
||||||
|
onTick: (tick: {
|
||||||
|
serverId: string;
|
||||||
|
sample: MetricSample;
|
||||||
|
disks: DiskSample[];
|
||||||
|
probes?: ProbeSample[];
|
||||||
|
}) => void;
|
||||||
|
onStates: (states: ServerRuntimeState[]) => boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
let dashboardPatchers: DashboardLivePatchers | null = null;
|
||||||
|
const activeCleanups: Array<() => void> = [];
|
||||||
|
|
||||||
|
export function registerDashboardLivePatchers(patchers: DashboardLivePatchers | null): void {
|
||||||
|
dashboardPatchers = patchers;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDashboardLivePatchers(): DashboardLivePatchers | null {
|
||||||
|
return dashboardPatchers;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerViewCleanup(fn: () => void): void {
|
||||||
|
activeCleanups.push(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function flushViewCleanups(): void {
|
||||||
|
while (activeCleanups.length > 0) {
|
||||||
|
const fn = activeCleanups.pop();
|
||||||
|
if (!fn) continue;
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch {
|
||||||
|
// Ignore view teardown errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
42
src/client/ts/toast.ts
Normal file
42
src/client/ts/toast.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
import { el } from './state.js';
|
||||||
|
|
||||||
|
export type ToastKind = 'info' | 'ok' | 'warn' | 'err';
|
||||||
|
|
||||||
|
const MAX_TOASTS = 4;
|
||||||
|
|
||||||
|
export function showToast(
|
||||||
|
message: string,
|
||||||
|
kind: ToastKind = 'info',
|
||||||
|
durationMs = 4500,
|
||||||
|
): void {
|
||||||
|
const region = document.getElementById('toast-region');
|
||||||
|
if (!region) return;
|
||||||
|
|
||||||
|
while (region.children.length >= MAX_TOASTS) {
|
||||||
|
region.firstElementChild?.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeBtn = el(
|
||||||
|
'button',
|
||||||
|
{ type: 'button', class: 'btn btn-sm toast-close', 'aria-label': 'Dismiss notification' },
|
||||||
|
'X',
|
||||||
|
);
|
||||||
|
const item = el(
|
||||||
|
'div',
|
||||||
|
{ class: `toast-item toast-${kind}`, role: 'status' },
|
||||||
|
el('span', { class: 'toast-msg' }, message),
|
||||||
|
closeBtn,
|
||||||
|
);
|
||||||
|
|
||||||
|
let timer: number | undefined;
|
||||||
|
const dismiss = () => {
|
||||||
|
if (timer !== undefined) window.clearTimeout(timer);
|
||||||
|
item.remove();
|
||||||
|
};
|
||||||
|
closeBtn.addEventListener('click', dismiss);
|
||||||
|
|
||||||
|
if (durationMs > 0) {
|
||||||
|
timer = window.setTimeout(dismiss, durationMs);
|
||||||
|
}
|
||||||
|
region.append(item);
|
||||||
|
}
|
||||||
|
|
@ -16,6 +16,8 @@ import {
|
||||||
extractErrorMessage,
|
extractErrorMessage,
|
||||||
fmtBytesPerSec,
|
fmtBytesPerSec,
|
||||||
fmtUptime,
|
fmtUptime,
|
||||||
|
registerDashboardLivePatchers,
|
||||||
|
registerViewCleanup,
|
||||||
type ClientState,
|
type ClientState,
|
||||||
type ServerEntry,
|
type ServerEntry,
|
||||||
} from '../state.js';
|
} from '../state.js';
|
||||||
|
|
@ -234,6 +236,13 @@ export async function renderDashboardView(
|
||||||
state: ClientState,
|
state: ClientState,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
root.replaceChildren();
|
root.replaceChildren();
|
||||||
|
registerDashboardLivePatchers({
|
||||||
|
onTick: patchDashboardServerTick,
|
||||||
|
onStates: patchDashboardServerStates,
|
||||||
|
});
|
||||||
|
registerViewCleanup(() => {
|
||||||
|
registerDashboardLivePatchers(null);
|
||||||
|
});
|
||||||
const [res, pinnedRes] = await Promise.all([
|
const [res, pinnedRes] = await Promise.all([
|
||||||
apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
|
apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
|
||||||
apiFetch<{
|
apiFetch<{
|
||||||
|
|
|
||||||
|
|
@ -2,16 +2,24 @@ import type { ClientWsFrame, ServerWsFrame } from '../../shared/ws-protocol.js';
|
||||||
|
|
||||||
export type WsConnectionStatus = 'online' | 'reconnecting' | 'offline';
|
export type WsConnectionStatus = 'online' | 'reconnecting' | 'offline';
|
||||||
|
|
||||||
|
const CORE_CHANNELS = ['config', 'alerts', 'metrics', 'workflows'] as const;
|
||||||
|
|
||||||
export class MultiplexWsClient {
|
export class MultiplexWsClient {
|
||||||
private ws: WebSocket | null = null;
|
private ws: WebSocket | null = null;
|
||||||
private reconnectAttempt = 0;
|
private reconnectAttempt = 0;
|
||||||
private reconnectTimer: number | null = null;
|
private reconnectTimer: number | null = null;
|
||||||
private pingTimer: number | null = null;
|
private pingTimer: number | null = null;
|
||||||
private shouldRun = false;
|
private shouldRun = false;
|
||||||
private channels = new Set<string>(['config', 'alerts', 'metrics', 'workflows']);
|
private readonly channelRefs = new Map<string, number>();
|
||||||
private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>();
|
private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>();
|
||||||
private readonly statusListeners = new Set<(status: WsConnectionStatus) => void>();
|
private readonly statusListeners = new Set<(status: WsConnectionStatus) => void>();
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
for (const ch of CORE_CHANNELS) {
|
||||||
|
this.channelRefs.set(ch, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onFrame(listener: (frame: ServerWsFrame) => void): () => void {
|
onFrame(listener: (frame: ServerWsFrame) => void): () => void {
|
||||||
this.frameListeners.add(listener);
|
this.frameListeners.add(listener);
|
||||||
return () => this.frameListeners.delete(listener);
|
return () => this.frameListeners.delete(listener);
|
||||||
|
|
@ -37,6 +45,11 @@ export class MultiplexWsClient {
|
||||||
window.clearInterval(this.pingTimer);
|
window.clearInterval(this.pingTimer);
|
||||||
this.pingTimer = null;
|
this.pingTimer = null;
|
||||||
}
|
}
|
||||||
|
for (const ch of [...this.channelRefs.keys()]) {
|
||||||
|
if (!(CORE_CHANNELS as readonly string[]).includes(ch)) {
|
||||||
|
this.channelRefs.delete(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
if (this.ws) {
|
if (this.ws) {
|
||||||
this.ws.close(1000, 'Client disconnect');
|
this.ws.close(1000, 'Client disconnect');
|
||||||
this.ws = null;
|
this.ws = null;
|
||||||
|
|
@ -50,14 +63,54 @@ export class MultiplexWsClient {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
subscribe(channels: string[]): void {
|
/**
|
||||||
for (const ch of channels) this.channels.add(ch);
|
* Reference-counted channel subscription. Returns a cleanup callback that
|
||||||
this.send({ type: 'sub', channels });
|
* releases this caller's references and sends `{ type: 'unsub' }` once refcount hits 0.
|
||||||
|
*/
|
||||||
|
subscribe(channels: string[]): () => void {
|
||||||
|
const addedNow: string[] = [];
|
||||||
|
const tracked: string[] = [];
|
||||||
|
for (const ch of channels) {
|
||||||
|
if (!ch) continue;
|
||||||
|
tracked.push(ch);
|
||||||
|
const prev = this.channelRefs.get(ch) ?? 0;
|
||||||
|
this.channelRefs.set(ch, prev + 1);
|
||||||
|
if (prev === 0) addedNow.push(ch);
|
||||||
|
}
|
||||||
|
if (addedNow.length > 0) {
|
||||||
|
this.send({ type: 'sub', channels: addedNow });
|
||||||
|
}
|
||||||
|
let disposed = false;
|
||||||
|
return () => {
|
||||||
|
if (disposed) return;
|
||||||
|
disposed = true;
|
||||||
|
this.unsubscribe(tracked);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
unsubscribe(channels: string[]): void {
|
||||||
|
const dropped: string[] = [];
|
||||||
|
for (const ch of channels) {
|
||||||
|
if ((CORE_CHANNELS as readonly string[]).includes(ch)) continue;
|
||||||
|
const cur = this.channelRefs.get(ch) ?? 0;
|
||||||
|
if (cur <= 1) {
|
||||||
|
this.channelRefs.delete(ch);
|
||||||
|
if (cur === 1) dropped.push(ch);
|
||||||
|
} else {
|
||||||
|
this.channelRefs.set(ch, cur - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (dropped.length > 0) {
|
||||||
|
this.send({ type: 'unsub', channels: dropped });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private openSocket(): void {
|
private openSocket(): void {
|
||||||
if (!this.shouldRun) return;
|
if (!this.shouldRun) return;
|
||||||
if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
|
if (
|
||||||
|
this.ws &&
|
||||||
|
(this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)
|
||||||
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -68,8 +121,9 @@ export class MultiplexWsClient {
|
||||||
socket.addEventListener('open', () => {
|
socket.addEventListener('open', () => {
|
||||||
this.reconnectAttempt = 0;
|
this.reconnectAttempt = 0;
|
||||||
this.emitStatus('online');
|
this.emitStatus('online');
|
||||||
if (this.channels.size > 0) {
|
const allActive = [...this.channelRefs.keys()];
|
||||||
this.send({ type: 'sub', channels: [...this.channels] });
|
if (allActive.length > 0) {
|
||||||
|
this.send({ type: 'sub', channels: allActive });
|
||||||
}
|
}
|
||||||
if (this.pingTimer !== null) window.clearInterval(this.pingTimer);
|
if (this.pingTimer !== null) window.clearInterval(this.pingTimer);
|
||||||
this.pingTimer = window.setInterval(() => {
|
this.pingTimer = window.setInterval(() => {
|
||||||
|
|
|
||||||
|
|
@ -5,18 +5,74 @@ export interface DiffLine {
|
||||||
text: string;
|
text: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type CollapsedDiffEntry =
|
||||||
|
| DiffLine
|
||||||
|
| { type: 'hunk'; omittedCount: number; text: string };
|
||||||
|
|
||||||
export interface DiffResult {
|
export interface DiffResult {
|
||||||
lines: DiffLine[];
|
lines: DiffLine[];
|
||||||
|
collapsedLines: CollapsedDiffEntry[];
|
||||||
unified: string;
|
unified: string;
|
||||||
additions: number;
|
additions: number;
|
||||||
deletions: number;
|
deletions: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function collapseDiffHunks(lines: DiffLine[], contextLines = 3): CollapsedDiffEntry[] {
|
||||||
|
const ctx = Math.max(0, Math.floor(contextLines));
|
||||||
|
const keep = new Uint8Array(lines.length);
|
||||||
|
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
if (lines[i]!.type !== 'equal') {
|
||||||
|
const start = Math.max(0, i - ctx);
|
||||||
|
const end = Math.min(lines.length - 1, i + ctx);
|
||||||
|
for (let k = start; k <= end; k++) keep[k] = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!keep.some((v) => v === 1)) {
|
||||||
|
return lines.length <= ctx * 2 + 2
|
||||||
|
? [...lines]
|
||||||
|
: [
|
||||||
|
...lines.slice(0, ctx),
|
||||||
|
{
|
||||||
|
type: 'hunk',
|
||||||
|
omittedCount: lines.length - ctx,
|
||||||
|
text: `... ${lines.length - ctx} unchanged lines omitted ...`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const out: CollapsedDiffEntry[] = [];
|
||||||
|
let i = 0;
|
||||||
|
while (i < lines.length) {
|
||||||
|
if (keep[i]) {
|
||||||
|
out.push(lines[i]!);
|
||||||
|
i++;
|
||||||
|
} else {
|
||||||
|
let j = i;
|
||||||
|
while (j < lines.length && !keep[j]) j++;
|
||||||
|
const count = j - i;
|
||||||
|
if (count === 1) {
|
||||||
|
out.push(lines[i]!);
|
||||||
|
} else {
|
||||||
|
out.push({
|
||||||
|
type: 'hunk',
|
||||||
|
omittedCount: count,
|
||||||
|
text: `... ${count} unchanged lines omitted ...`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
i = j;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
export function computeLineDiff(
|
export function computeLineDiff(
|
||||||
oldText: string,
|
oldText: string,
|
||||||
newText: string,
|
newText: string,
|
||||||
oldLabel = 'revision',
|
oldLabel = 'revision',
|
||||||
newLabel = 'current',
|
newLabel = 'current',
|
||||||
|
opts: { contextLines?: number } = {},
|
||||||
): DiffResult {
|
): DiffResult {
|
||||||
const a = oldText.replace(/\r\n/g, '\n').split('\n');
|
const a = oldText.replace(/\r\n/g, '\n').split('\n');
|
||||||
const b = newText.replace(/\r\n/g, '\n').split('\n');
|
const b = newText.replace(/\r\n/g, '\n').split('\n');
|
||||||
|
|
@ -75,21 +131,25 @@ export function computeLineDiff(
|
||||||
|
|
||||||
let additions = 0;
|
let additions = 0;
|
||||||
let deletions = 0;
|
let deletions = 0;
|
||||||
|
const collapsedLines = collapseDiffHunks(lines, opts.contextLines ?? 3);
|
||||||
const body: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`];
|
const body: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`];
|
||||||
for (const line of lines) {
|
for (const entry of collapsedLines) {
|
||||||
if (line.type === 'add') {
|
if (entry.type === 'hunk') {
|
||||||
|
body.push(`@@ ${entry.text} @@`);
|
||||||
|
} else if (entry.type === 'add') {
|
||||||
additions++;
|
additions++;
|
||||||
body.push(`+${line.text}`);
|
body.push(`+${entry.text}`);
|
||||||
} else if (line.type === 'del') {
|
} else if (entry.type === 'del') {
|
||||||
deletions++;
|
deletions++;
|
||||||
body.push(`-${line.text}`);
|
body.push(`-${entry.text}`);
|
||||||
} else {
|
} else {
|
||||||
body.push(` ${line.text}`);
|
body.push(` ${entry.text}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
lines,
|
lines,
|
||||||
|
collapsedLines,
|
||||||
unified: body.join('\n'),
|
unified: body.join('\n'),
|
||||||
additions,
|
additions,
|
||||||
deletions,
|
deletions,
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue