feat: refactoring

This commit is contained in:
2026-04-05 10:24:01 +02:00
parent e1db06104e
commit ad89f409bf
15 changed files with 662 additions and 756 deletions

View File

@@ -0,0 +1,74 @@
import FloatingWindow from "@/components/shared/FloatingWindow";
import type { ManagedWindow } from "@/hooks/useWindowManager";
import type { BrowseWinData } from "./types";
interface BrowseNodeWindowProps {
win: ManagedWindow<BrowseWinData>;
focused: boolean;
onUpdate: (id: string, patch: Partial<ManagedWindow<BrowseWinData>>) => void;
onClose: (id: string) => void;
onFocus: (id: string) => void;
onNavBack: (winId: string, data: BrowseWinData) => void;
onNavForward: (winId: string, data: BrowseWinData) => void;
onNavReload: (winId: string, data: BrowseWinData) => void;
onContentClick: (e: React.MouseEvent, winId: string, data: BrowseWinData) => void;
}
export default function BrowseNodeWindow({
win, focused, onUpdate, onClose, onFocus,
onNavBack, onNavForward, onNavReload, onContentClick,
}: BrowseNodeWindowProps) {
const d = win.data;
const canBack = d.historyIndex > 0;
const canFwd = d.historyIndex < d.history.length - 1;
return (
<FloatingWindow
id={win.id}
title={d.node.name}
x={win.x} y={win.y} w={win.w} h={win.h}
zIndex={win.zIndex}
focused={focused}
onUpdate={onUpdate}
onClose={onClose}
onFocus={onFocus}
addressBar={
<div className="flex items-center gap-1.5 px-2 py-1 border-b border-border shrink-0 bg-muted/15">
<button onClick={() => onNavBack(win.id, d)} disabled={!canBack || d.pageLoading}
className="w-5 h-5 flex items-center justify-center rounded text-[10px] text-muted-foreground hover:text-foreground disabled:opacity-30 disabled:cursor-default transition-colors" title="Back">
&#9664;
</button>
<button onClick={() => onNavForward(win.id, d)} disabled={!canFwd || d.pageLoading}
className="w-5 h-5 flex items-center justify-center rounded text-[10px] text-muted-foreground hover:text-foreground disabled:opacity-30 disabled:cursor-default transition-colors" title="Forward">
&#9654;
</button>
<button onClick={() => onNavReload(win.id, d)} disabled={d.pageLoading}
className="w-5 h-5 flex items-center justify-center rounded text-[10px] text-muted-foreground hover:text-foreground disabled:opacity-30 disabled:cursor-default transition-colors" title="Reload">
&#8635;
</button>
<div className="flex-1 flex items-center h-5 px-2 bg-background/60 border border-border rounded text-[10px] font-mono text-foreground/80 truncate">
<span className="text-muted-foreground/60 truncate">{d.node.hash.slice(0, 12)}\u2026/</span>{d.currentPath}
</div>
<span className="flex items-center gap-1 text-[9px] uppercase tracking-wider shrink-0">
{d.pageLoading ? <span className="text-muted-foreground animate-pulse">loading</span>
: d.pageError ? <><span className="w-1.5 h-1.5 rounded-full bg-destructive inline-block" /><span className="text-destructive">error</span></>
: d.pageHtml ? <><span className="w-1.5 h-1.5 rounded-full bg-green-500 inline-block" /><span className="text-muted-foreground">ok</span></> : null}
</span>
</div>
}
footer={
<div className="flex items-center gap-3 px-3 py-1 border-t border-border shrink-0 bg-muted/15 rounded-b-lg">
<span className="text-[9px] text-muted-foreground uppercase tracking-wider truncate">{d.node.type ?? "peer"}</span>
{d.node.interface && <span className="text-[9px] text-muted-foreground uppercase tracking-wider truncate">via {d.node.interface}</span>}
</div>
}
>
{/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
<div className="p-3 h-full overflow-auto" onClick={(e) => onContentClick(e, win.id, d)}>
{d.pageLoading && <span className="text-muted-foreground text-xs animate-pulse">Requesting page...</span>}
{d.pageError && <span className="text-destructive text-xs">{d.pageError}</span>}
{d.pageHtml && <div className="font-mono text-[11px] leading-tight" dangerouslySetInnerHTML={{ __html: d.pageHtml }} />}
</div>
</FloatingWindow>
);
}

View File

@@ -0,0 +1,115 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { DITHERED_SHADOW } from "@/components/shared/FloatingWindow";
import type { NetworkNode } from "@/api/client";
interface BrowseSearchBarProps {
filter: string;
onFilterChange: (value: string) => void;
onClear: () => void;
suggestions: NetworkNode[];
onSelectNode: (node: NetworkNode) => void;
focusedWinId: string | null;
windowCount: number;
}
export default function BrowseSearchBar({
filter, onFilterChange, onClear,
suggestions, onSelectNode,
focusedWinId, windowCount,
}: BrowseSearchBarProps) {
const searchInputRef = useRef<HTMLInputElement>(null);
const [selectedSuggestion, setSelectedSuggestion] = useState(-1);
// Reset selection when suggestions change
useEffect(() => { setSelectedSuggestion(-1); }, [suggestions]);
// Auto-focus search when no windows open
useEffect(() => { searchInputRef.current?.focus(); }, []);
useEffect(() => {
if (windowCount === 0) searchInputRef.current?.focus();
}, [windowCount]);
// Capture typing into search when no window is focused
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if (focusedWinId) return;
if (document.activeElement === searchInputRef.current) return;
if (e.metaKey || e.ctrlKey || e.altKey) return;
if (e.key.length !== 1) return;
searchInputRef.current?.focus();
};
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
}, [focusedWinId]);
// Draggable position
const [searchPos, setSearchPos] = useState<{ x: number; y: number } | null>(null);
const searchDragRef = useRef<{ startX: number; startY: number; origX: number; origY: number } | null>(null);
useEffect(() => { setSearchPos({ x: Math.round(window.innerWidth / 2 - 200), y: window.innerHeight - 307 }); }, []);
const onSearchDragStart = useCallback((e: React.MouseEvent) => {
if ((e.target as HTMLElement).tagName === "INPUT") return;
e.preventDefault();
const pos = searchPos ?? { x: 0, y: 0 };
searchDragRef.current = { startX: e.clientX, startY: e.clientY, origX: pos.x, origY: pos.y };
const onMove = (ev: MouseEvent) => { if (!searchDragRef.current) return; setSearchPos({ x: searchDragRef.current.origX + (ev.clientX - searchDragRef.current.startX), y: Math.max(0, searchDragRef.current.origY + (ev.clientY - searchDragRef.current.startY)) }); };
const onUp = () => { searchDragRef.current = null; document.removeEventListener("mousemove", onMove); document.removeEventListener("mouseup", onUp); };
document.addEventListener("mousemove", onMove); document.addEventListener("mouseup", onUp);
}, [searchPos]);
if (!searchPos) return null;
return createPortal(
<div onMouseDown={onSearchDragStart}
className="fixed z-999 flex items-center gap-3 px-3 py-1.5 bg-popover border-2 border-border focus-within:border-primary rounded-lg cursor-grab active:cursor-grabbing transition-[border-color] duration-150"
style={{ left: searchPos.x, top: searchPos.y, width: 400, boxShadow: DITHERED_SHADOW }}>
<input ref={searchInputRef} type="text" value={filter}
onChange={(e) => onFilterChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Escape") { onClear(); e.currentTarget.blur(); return; }
if (e.key === "ArrowDown") { e.preventDefault(); setSelectedSuggestion(i => Math.min(i + 1, suggestions.length - 1)); return; }
if (e.key === "ArrowUp") { e.preventDefault(); setSelectedSuggestion(i => Math.max(i - 1, -1)); return; }
if (e.key === "Enter") {
e.preventDefault();
const entry = selectedSuggestion >= 0 ? suggestions[selectedSuggestion] : suggestions[0];
if (entry && entry.type !== "interface") { onSelectNode(entry); onClear(); }
return;
}
}}
placeholder="Search nodes..."
className="flex-1 h-7 px-2 text-xs bg-background/60 border border-border rounded placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary cursor-text" />
{filter && (
<button onClick={onClear} className="text-muted-foreground hover:text-foreground transition-colors text-xs leading-none px-1" title="Clear search (Esc)">
&times;
</button>
)}
{suggestions.length > 0 && (
<div className="absolute left-0 right-0 top-full mt-1 bg-popover border border-border rounded-lg overflow-hidden"
style={{ boxShadow: "0 4px 12px rgba(0,0,0,0.4)" }}>
{suggestions.map((entry, i) => (
<button
key={entry.hash}
onMouseDown={(e) => { e.preventDefault(); if (entry.type !== "interface") { onSelectNode(entry); onClear(); } }}
onMouseEnter={() => setSelectedSuggestion(i)}
className={`w-full text-left px-3 py-1.5 text-xs font-mono flex items-center gap-2 transition-colors ${i === selectedSuggestion ? "bg-accent text-accent-foreground" : "text-foreground hover:bg-accent/50"
}`}
>
<span className="w-2 h-2 rounded-full shrink-0" style={{
backgroundColor: (() => {
const age = Date.now() / 1000 - (entry.last_seen ?? 0);
if (age < 300) return "var(--primary)";
if (age < 3600) return "var(--muted-foreground)";
return "var(--border)";
})(),
}} />
<span className="truncate">{entry.name}</span>
<span className="ml-auto text-[9px] text-muted-foreground uppercase shrink-0">
{entry.interface ?? "peer"}
</span>
</button>
))}
</div>
)}
</div>, document.body);
}

View File

@@ -0,0 +1,98 @@
import type { NetworkNode } from "@/api/client";
import { statusRGBA, type RGBA, type StatusColors } from "./graphColors";
export const SPACE_SIZE = 4096;
const CENTER = SPACE_SIZE / 2;
export interface BuiltGraph {
entries: NetworkNode[];
positions: Float32Array;
colors: Float32Array;
sizes: Float32Array;
clusterIndices: (number | undefined)[];
clusterPositions: (number | undefined)[];
clusterStrength: Float32Array;
clusterNames: string[];
hashToIndex: Map<string, number>;
}
function findParentIface(
entry: NetworkNode,
interfaces: NetworkNode[],
peerIndex: number,
): string | undefined {
if (entry.interface) {
const iface = interfaces.find(i => i.name === entry.interface);
if (iface) return iface.hash;
}
if (interfaces.length > 0) return interfaces[peerIndex % interfaces.length].hash;
return undefined;
}
export function buildGraphArrays(
rawNodes: NetworkNode[],
prevHashToIndex: Map<string, number>,
prevPositions: number[],
theme: StatusColors,
): BuiltGraph {
const interfaces = rawNodes.filter(e => e.type === "interface").sort((a, b) => a.name.localeCompare(b.name));
const selfNode = rawNodes.find(e => e.is_self && e.type !== "interface");
const peers = rawNodes.filter(e => !e.is_self && e.type !== "interface");
const entries = selfNode ? [selfNode, ...peers] : peers;
const selfIndex = selfNode ? 0 : -1;
const n = entries.length;
const nClusters = interfaces.length;
const hashToIndex = new Map<string, number>();
const positions = new Float32Array(n * 2);
const colors = new Float32Array(n * 4);
const sizes = new Float32Array(n);
const clusterIndices: (number | undefined)[] = [];
const clusterStrength = new Float32Array(n);
const clusterMap = new Map<string, number>();
interfaces.forEach((iface, i) => clusterMap.set(iface.name, i));
const selfClusterIndex = interfaces.length;
const clusterNames = [...interfaces.map(i => i.name), ...(selfNode ? [selfNode.name] : [])];
const clusterPositions: (number | undefined)[] = [];
entries.forEach((entry, i) => {
hashToIndex.set(entry.hash, i);
// Preserve existing position, or jitter near center for new points
const prevIdx = prevHashToIndex.get(entry.hash);
if (prevIdx !== undefined && prevPositions.length >= (prevIdx + 1) * 2) {
positions[i * 2] = prevPositions[prevIdx * 2]!;
positions[i * 2 + 1] = prevPositions[prevIdx * 2 + 1]!;
} else {
positions[i * 2] = CENTER + (Math.random() - 0.5) * SPACE_SIZE * 0.5;
positions[i * 2 + 1] = CENTER + (Math.random() - 0.5) * SPACE_SIZE * 0.5;
}
// Self node = bright white, others by status
const rgba: RGBA = i === selfIndex
? [1, 1, 1, 1]
: statusRGBA(entry, theme);
colors[i * 4 + 0] = rgba[0];
colors[i * 4 + 1] = rgba[1];
colors[i * 4 + 2] = rgba[2];
colors[i * 4 + 3] = rgba[3];
sizes[i] = 3;
// Cluster assignment
if (i === selfIndex) {
clusterIndices.push(selfClusterIndex);
} else {
const pi = peers.indexOf(entry);
const parentHash = findParentIface(entry, interfaces, pi);
const parentName = parentHash ? interfaces.find(f => f.hash === parentHash)?.name : undefined;
clusterIndices.push(parentName !== undefined ? clusterMap.get(parentName) : undefined);
}
clusterStrength[i] = nClusters > 1 ? (nClusters - (i % nClusters)) / nClusters : 1;
});
return { entries, positions, colors, sizes, clusterIndices, clusterPositions, clusterStrength, clusterNames, hashToIndex };
}

View File

@@ -0,0 +1,57 @@
import type { NetworkNode } from "@/api/client";
export type RGBA = [number, number, number, number];
export function cssVarToRGBA(varName: string): RGBA {
const raw = getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
if (!raw) return [0.5, 0.5, 0.5, 1];
const ctx = document.createElement("canvas").getContext("2d")!;
ctx.fillStyle = raw;
// ctx.fillStyle normalizes to #rrggbb
const hex = ctx.fillStyle;
const r = parseInt(hex.slice(1, 3), 16) / 255;
const g = parseInt(hex.slice(3, 5), 16) / 255;
const b = parseInt(hex.slice(5, 7), 16) / 255;
return [r, g, b, 1];
}
export function lerpRGBA(a: RGBA, b: RGBA, t: number): RGBA {
return [
a[0] + (b[0] - a[0]) * t,
a[1] + (b[1] - a[1]) * t,
a[2] + (b[2] - a[2]) * t,
a[3] + (b[3] - a[3]) * t,
];
}
export function brighten(c: RGBA, amount: number): RGBA {
return [
Math.min(1, c[0] + amount),
Math.min(1, c[1] + amount),
Math.min(1, c[2] + amount),
c[3],
];
}
export interface StatusColors {
online: RGBA;
stale: RGBA;
offline: RGBA;
}
export function getThemeStatusColors(): StatusColors {
const primary = brighten(cssVarToRGBA("--primary"), 0.15);
const muted = cssVarToRGBA("--muted-foreground");
return {
online: primary,
stale: lerpRGBA(primary, muted, 0.4),
offline: muted,
};
}
export function statusRGBA(entry: NetworkNode, theme: StatusColors): RGBA {
const age = Date.now() / 1000 - (entry.last_seen ?? 0);
if (age < 300) return theme.online;
if (age < 3600) return theme.stale;
return theme.offline;
}

View File

@@ -0,0 +1,17 @@
import type { NetworkNode } from "@/api/client";
export interface HistoryEntry {
path: string;
html: string | null;
error: string | null;
}
export interface BrowseWinData {
node: NetworkNode;
pageHtml: string | null;
pageLoading: boolean;
pageError: string | null;
currentPath: string;
history: HistoryEntry[];
historyIndex: number;
}