Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

feat(graph-ui): density-aware contrast + Display controls

Martin Vogel8e65f8f1be8d
diff --git a/graph-ui/src/components/DisplaySettingsMenu.tsx b/graph-ui/src/components/DisplaySettingsMenu.tsx
new file mode 100644
index 000000000..3b78f814c
--- /dev/null
+++ b/graph-ui/src/components/DisplaySettingsMenu.tsx
@@ -0,0 +1,149 @@
+import { useEffect, useRef, useState } from "react";
+import { Button } from "@/components/ui/button";
+import {
+ DEFAULT_DISPLAY_SETTINGS,
+ DISPLAY_LIMITS,
+ type DisplaySettings,
+} from "../lib/density";
+
+interface DisplaySettingsMenuProps {
+ settings: DisplaySettings;
+ onChange: (next: DisplaySettings) => void;
+}
+
+interface SliderRowProps {
+ label: string;
+ hint: string;
+ value: number;
+ min: number;
+ max: number;
+ onChange: (value: number) => void;
+}
+
+function SliderRow({ label, hint, value, min, max, onChange }: SliderRowProps) {
+ return (
+ <label className="block">
+ <div className="flex items-center justify-between mb-1">
+ <span className="text-[11px] text-foreground/70">{label}</span>
+ <span className="text-[10px] font-mono text-cyan-300/70 tabular-nums">
+ {value.toFixed(2)}×
+ </span>
+ </div>
+ <input
+ type="range"
+ min={min}
+ max={max}
+ step={0.05}
+ value={value}
+ onChange={(e) => onChange(parseFloat(e.target.value))}
+ className="w-full accent-cyan-400 cursor-pointer"
+ aria-label={`${label} (${hint})`}
+ />
+ <p className="text-[9px] text-foreground/30 mt-0.5">{hint}</p>
+ </label>
+ );
+}
+
+/* Contrast / brightness controls for the 3D graph. These ride on top of the
+ * automatic density compensation — the defaults already adapt to graph size,
+ * so 1.00× is "auto"; the sliders let the user push it. */
+export function DisplaySettingsMenu({
+ settings,
+ onChange,
+}: DisplaySettingsMenuProps) {
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+
+ /* Close on outside click / Escape */
+ useEffect(() => {
+ if (!open) return;
+ const onDown = (e: MouseEvent) => {
+ if (rootRef.current && !rootRef.current.contains(e.target as Node)) {
+ setOpen(false);
+ }
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setOpen(false);
+ };
+ document.addEventListener("mousedown", onDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [open]);
+
+ const set = (patch: Partial<DisplaySettings>) =>
+ onChange({ ...settings, ...patch });
+
+ const isDefault =
+ settings.edgeBrightness === DEFAULT_DISPLAY_SETTINGS.edgeBrightness &&
+ settings.nodeGlow === DEFAULT_DISPLAY_SETTINGS.nodeGlow &&
+ settings.bloom === DEFAULT_DISPLAY_SETTINGS.bloom;
+
+ return (
+ <div ref={rootRef} className="relative">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ aria-haspopup="dialog"
+ title="Contrast & brightness"
+ >
+ Display{!isDefault && <span className="ml-1 text-cyan-300">•</span>}
+ </Button>
+
+ {open && (
+ <div
+ role="dialog"
+ aria-label="Display settings"
+ className="absolute top-10 right-0 w-64 p-4 rounded-lg border border-border/60 bg-[#0b1920]/95 backdrop-blur-md shadow-xl z-20 space-y-3.5"
+ >
+ <div className="flex items-center justify-between">
+ <span className="text-[11px] font-medium text-foreground/50 uppercase tracking-widest">
+ Contrast
+ </span>
+ <button
+ onClick={() => onChange(DEFAULT_DISPLAY_SETTINGS)}
+ className="text-[10px] text-primary/70 hover:text-primary transition-colors disabled:opacity-30"
+ disabled={isDefault}
+ >
+ Reset
+ </button>
+ </div>
+
+ <SliderRow
+ label="Edge brightness"
+ hint="Dim the web of links on dense graphs"
+ value={settings.edgeBrightness}
+ min={DISPLAY_LIMITS.edgeBrightness.min}
+ max={DISPLAY_LIMITS.edgeBrightness.max}
+ onChange={(edgeBrightness) => set({ edgeBrightness })}
+ />
+ <SliderRow
+ label="Node glow"
+ hint="Halo boost around each node"
+ value={settings.nodeGlow}
+ min={DISPLAY_LIMITS.nodeGlow.min}
+ max={DISPLAY_LIMITS.nodeGlow.max}
+ onChange={(nodeGlow) => set({ nodeGlow })}
+ />
+ <SliderRow
+ label="Bloom"
+ hint="Overall glow bloom strength"
+ value={settings.bloom}
+ min={DISPLAY_LIMITS.bloom.min}
+ max={DISPLAY_LIMITS.bloom.max}
+ onChange={(bloom) => set({ bloom })}
+ />
+
+ <p className="text-[9px] text-foreground/30 pt-1 border-t border-border/30">
+ 1.00× follows the automatic density compensation. Lower the
+ edge/glow/bloom values when a large graph washes out to white.
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/graph-ui/src/components/EdgeLines.tsx b/graph-ui/src/components/EdgeLines.tsx
index 50052d821..4cb7eba8e 100644
--- a/graph-ui/src/components/EdgeLines.tsx
+++ b/graph-ui/src/components/EdgeLines.tsx
@@ -1,12 +1,16 @@
import { useMemo } from "react";
import * as THREE from "three";
import type { GraphNode, GraphEdge } from "../lib/types";
+import { edgeIntensityScale } from "../lib/density";
interface EdgeLinesProps {
nodes: GraphNode[];
edges: GraphEdge[];
highlightedIds: Set<number> | null;
opacity?: number;
+ /* User edge-brightness multiplier (see DisplaySettings). Layered on top of
+ * the automatic density scale. */
+ brightness?: number;
/* When set, edge.target is looked up in this array instead of `nodes`.
* Used for cross-galaxy edges where source lives in the primary graph
* and target lives in a linked project's offset-adjusted nodes. */
@@ -52,9 +56,13 @@ export function EdgeLines({
edges,
highlightedIds,
opacity = 1.0,
+ brightness = 1.0,
targetNodes,
}: EdgeLinesProps) {
const geometry = useMemo(() => {
+ /* Shrink per-edge glow as the edge count grows so the additively-blended
+ * center doesn't saturate to white; the user multiplier rides on top. */
+ const densityScale = edgeIntensityScale(edges.length) * brightness;
const srcMap = new Map<number, number>();
for (let i = 0; i < nodes.length; i++) {
srcMap.set(nodes[i].id, i);
@@ -91,7 +99,11 @@ export function EdgeLines({
* With additive blending + dark background, these glow nicely. */
let intensity = sameCluster ? 0.25 : 0.06;
if (hasHighlight) {
- intensity = sHL && tHL ? 0.5 : 0.04;
+ /* A selection stays at full strength (never density-scaled) so it
+ * pops against the dimmed rest; only the un-selected bulk is scaled. */
+ intensity = sHL && tHL ? 0.5 : 0.04 * densityScale;
+ } else {
+ intensity *= densityScale;
}
const off = validCount * 6;
@@ -125,7 +137,7 @@ export function EdgeLines({
new THREE.BufferAttribute(colors.slice(0, validCount * 6), 3),
);
return geo;
- }, [nodes, edges, highlightedIds, targetNodes]);
+ }, [nodes, edges, highlightedIds, targetNodes, brightness]);
return (
<lineSegments geometry={geometry}>
diff --git a/graph-ui/src/components/GraphScene.tsx b/graph-ui/src/components/GraphScene.tsx
index 81ec5c9bc..663c2ad32 100644
--- a/graph-ui/src/components/GraphScene.tsx
+++ b/graph-ui/src/components/GraphScene.tsx
@@ -9,6 +9,14 @@ import { EdgeLines } from "./EdgeLines";
import { NodeLabels } from "./NodeLabels";
import { NodeTooltip } from "./NodeTooltip";
import type { GraphData, GraphNode, LinkedProject } from "../lib/types";
+import {
+ DEFAULT_DISPLAY_SETTINGS,
+ bloomIntensityScale,
+ nodeBoostScale,
+ type DisplaySettings,
+} from "../lib/density";
+
+const BASE_BLOOM_INTENSITY = 1.45;
/* ── Camera fly-to animation ────────────────────────────── */
@@ -107,6 +115,7 @@ interface GraphSceneProps {
highlightedIds: Set<number> | null;
cameraTarget: CameraTarget | null;
showLabels: boolean;
+ display?: DisplaySettings;
onNodeClick: (node: GraphNode) => void;
}
@@ -117,11 +126,21 @@ export function GraphScene({
highlightedIds,
cameraTarget,
showLabels,
+ display = DEFAULT_DISPLAY_SETTINGS,
onNodeClick,
}: GraphSceneProps) {
const [hovered, setHovered] = useState<GraphNode | null>(null);
const controlsRef = useRef<OrbitControlsImpl | null>(null);
+ /* Adaptive density defaults × user multipliers. The automatic scale keeps
+ * contrast roughly constant as the graph grows; the sliders nudge it.
+ * NodeCloud applies `nodeBoost` directly (no internal density scaling),
+ * whereas EdgeLines scales by edge density itself — so it receives only the
+ * user edge-brightness multiplier to avoid double-applying. */
+ const nodeBoost = nodeBoostScale(data.nodes.length) * display.nodeGlow;
+ const bloomIntensity =
+ BASE_BLOOM_INTENSITY * bloomIntensityScale(data.nodes.length) * display.bloom;
+
return (
<Canvas
camera={{ position: [0, 0, 800], fov: 50, near: 0.1, far: 100000 }}
@@ -146,12 +165,14 @@ export function GraphScene({
nodes={data.nodes}
edges={data.edges}
highlightedIds={highlightedIds}
+ brightness={display.edgeBrightness}
/>
<NodeCloud
nodes={data.nodes}
highlightedIds={highlightedIds}
onHover={setHovered}
onClick={onNodeClick}
+ boost={nodeBoost}
/>
{showLabels && <NodeLabels nodes={data.nodes} highlightedIds={highlightedIds} />}
@@ -170,6 +191,7 @@ export function GraphScene({
edges={lp.edges}
highlightedIds={null}
opacity={0.3}
+ brightness={display.edgeBrightness}
/>
<NodeCloud
nodes={offsetNodes}
@@ -177,6 +199,7 @@ export function GraphScene({
onHover={setHovered}
onClick={onNodeClick}
opacity={0.5}
+ boost={nodeBoost}
/>
{/* Inter-galaxy CROSS_* edges: source is in primary, target in
* this linked project's offset nodes. */}
@@ -187,6 +210,7 @@ export function GraphScene({
edges={lp.cross_edges}
highlightedIds={highlightedIds}
opacity={0.85}
+ brightness={display.edgeBrightness}
/>
)}
</group>
@@ -202,7 +226,7 @@ export function GraphScene({
<Bloom
luminanceThreshold={0.3}
luminanceSmoothing={0.7}
- intensity={1.2}
+ intensity={bloomIntensity}
mipmapBlur
radius={0.6}
/>
diff --git a/graph-ui/src/components/GraphTab.tsx b/graph-ui/src/components/GraphTab.tsx
index dde3650f5..75f32a700 100644
--- a/graph-ui/src/components/GraphTab.tsx
+++ b/graph-ui/src/components/GraphTab.tsx
@@ -8,6 +8,12 @@ import {
GRAPH_NODE_BUDGET_MAX,
} from "../hooks/useGraphData";
import { GraphLoader } from "./GraphLoader";
+import { DisplaySettingsMenu } from "./DisplaySettingsMenu";
+import {
+ loadDisplaySettings,
+ saveDisplaySettings,
+ type DisplaySettings,
+} from "../lib/density";
import {
GraphScene,
computeCameraTarget,
@@ -65,6 +71,13 @@ export function GraphTab({ project }: GraphTabProps) {
const [cameraTarget, setCameraTarget] = useState<CameraTarget | null>(null);
const [repoInfo, setRepoInfo] = useState<RepoInfo | null>(null);
const [showLabels, setShowLabels] = useState(true);
+ const [display, setDisplay] = useState<DisplaySettings>(() =>
+ loadDisplaySettings(),
+ );
+ const updateDisplay = useCallback((next: DisplaySettings) => {
+ setDisplay(next);
+ saveDisplaySettings(next);
+ }, []);
const [leftWidth, setLeftWidth] = useState(() => loadWidth("cbm-left-w", 260));
const [rightWidth, setRightWidth] = useState(() => loadWidth("cbm-right-w", 280));
const limitNotice = formatGraphLimitNotice(data);
@@ -375,6 +388,7 @@ export function GraphTab({ project }: GraphTabProps) {
highlightedIds={highlightedIds}
cameraTarget={cameraTarget}
showLabels={showLabels}
+ display={display}
onNodeClick={handleNodeClick}
/>
</ErrorBoundary>
@@ -440,6 +454,7 @@ export function GraphTab({ project }: GraphTabProps) {
title="How many nodes to load (5,000 steps, edges between loaded nodes follow automatically)"
/>
</div>
+ <DisplaySettingsMenu settings={display} onChange={updateDisplay} />
<Button
variant="outline"
size="sm"
diff --git a/graph-ui/src/components/NodeCloud.tsx b/graph-ui/src/components/NodeCloud.tsx
index 60b9aea5a..a8ea2f80e 100644
--- a/graph-ui/src/components/NodeCloud.tsx
+++ b/graph-ui/src/components/NodeCloud.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef } from "react";
import { useThree } from "@react-three/fiber";
import * as THREE from "three";
import type { GraphNode } from "../lib/types";
+import { nodeGlowBoost } from "../lib/density";
interface NodeCloudProps {
nodes: GraphNode[];
@@ -9,6 +10,9 @@ interface NodeCloudProps {
onHover: (node: GraphNode | null) => void;
onClick: (node: GraphNode) => void;
opacity?: number;
+ /* Multiplier on the per-node glow boost. 1 = full boost (sparse graphs),
+ * 0 = flat colors (dense graphs). Adaptive default × user setting. */
+ boost?: number;
}
/* Above this count instanced spheres stop paying off (vertex + matrix cost)
@@ -27,6 +31,7 @@ function nodeColor(
node: GraphNode,
highlightedIds: Set<number> | null,
opacity: number,
+ boost: number,
tempColor: THREE.Color,
): [number, number, number] {
const hasHighlight = highlightedIds && highlightedIds.size > 0;
@@ -34,11 +39,13 @@ function nodeColor(
if (hasHighlight && !highlightedIds.has(node.id)) {
tempColor.multiplyScalar(0.15);
} else {
- /* Boost above 1.0 so bloom picks up the excess as glow corona.
- * Hotter stars (white/blue) get a stronger boost = brighter halo. */
- const brightness = (tempColor.r + tempColor.g + tempColor.b) / 3;
- const boost = 1.2 + brightness * 0.8; /* 1.2x for red, 2.0x for white */
- tempColor.multiplyScalar(boost);
+ /* Boost above 1.0 so bloom picks up the excess as glow corona. Blue hubs
+ * glow most, red leaves modestly, white/yellow least (see nodeGlowBoost).
+ * The boost amount also fades toward 1.0 (flat color) as density rises so
+ * dense graphs stay legible instead of blooming into a white blob. */
+ const fullBoost = nodeGlowBoost(tempColor.r, tempColor.g, tempColor.b);
+ const applied = 1 + (fullBoost - 1) * boost;
+ tempColor.multiplyScalar(applied);
}
return [tempColor.r * opacity, tempColor.g * opacity, tempColor.b * opacity];
}
@@ -73,6 +80,7 @@ function NodePoints({
onHover,
onClick,
opacity,
+ boost,
}: Required<NodeCloudProps>) {
const { raycaster } = useThree();
@@ -94,13 +102,13 @@ function NodePoints({
positions[i * 3] = n.x;
positions[i * 3 + 1] = n.y;
positions[i * 3 + 2] = n.z;
- const [r, g, b] = nodeColor(n, highlightedIds, opacity, tempColor);
+ const [r, g, b] = nodeColor(n, highlightedIds, opacity, boost, tempColor);
colors[i * 3] = r;
colors[i * 3 + 1] = g;
colors[i * 3 + 2] = b;
}
return { positions, colors };
- }, [nodes, highlightedIds, opacity]);
+ }, [nodes, highlightedIds, opacity, boost]);
return (
<points
@@ -145,6 +153,7 @@ function NodeSpheres({
onHover,
onClick,
opacity,
+ boost,
}: Required<NodeCloudProps>) {
const meshRef = useRef<THREE.InstancedMesh>(null);
const tempObj = useMemo(() => new THREE.Object3D(), []);
@@ -155,13 +164,19 @@ function NodeSpheres({
const colors = useMemo(() => {
const arr = new Float32Array(nodes.length * 3);
for (let i = 0; i < nodes.length; i++) {
- const [r, g, b] = nodeColor(nodes[i], highlightedIds, opacity, tempColor);
+ const [r, g, b] = nodeColor(
+ nodes[i],
+ highlightedIds,
+ opacity,
+ boost,
+ tempColor,
+ );
arr[i * 3] = r;
arr[i * 3 + 1] = g;
arr[i * 3 + 2] = b;
}
return arr;
- }, [nodes, highlightedIds, tempColor, opacity]);
+ }, [nodes, highlightedIds, tempColor, opacity, boost]);
/* Node positions are static (the layout is server-computed), so instance
* matrices only change with the node set or the highlight — never rebuild
@@ -221,6 +236,7 @@ export function NodeCloud({
onHover,
onClick,
opacity = 1.0,
+ boost = 1.0,
}: NodeCloudProps) {
if (nodes.length > POINT_MODE_THRESHOLD) {
return (
@@ -230,6 +246,7 @@ export function NodeCloud({
onHover={onHover}
onClick={onClick}
opacity={opacity}
+ boost={boost}
/>
);
}
@@ -240,6 +257,7 @@ export function NodeCloud({
onHover={onHover}
onClick={onClick}
opacity={opacity}
+ boost={boost}
/>
);
}
diff --git a/graph-ui/src/lib/density.test.ts b/graph-ui/src/lib/density.test.ts
new file mode 100644
index 000000000..28a0b9095
--- /dev/null
+++ b/graph-ui/src/lib/density.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from "vitest";
+import {
+ edgeIntensityScale,
+ bloomIntensityScale,
+ nodeBoostScale,
+ nodeGlowBoost,
+ clampDisplaySettings,
+ DEFAULT_DISPLAY_SETTINGS,
+ EDGE_REFERENCE_COUNT,
+ NODE_REFERENCE_COUNT,
+} from "./density";
+
+/* Parse "#rrggbb" to 0..1 channels, matching how the renderer feeds colors. */
+function rgb(hex: string): [number, number, number] {
+ const n = parseInt(hex.slice(1), 16);
+ return [((n >> 16) & 0xff) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];
+}
+const glow = (hex: string) => nodeGlowBoost(...rgb(hex));
+
+describe("edgeIntensityScale", () => {
+ it("is 1 at or below the reference edge count", () => {
+ expect(edgeIntensityScale(0)).toBe(1);
+ expect(edgeIntensityScale(EDGE_REFERENCE_COUNT)).toBe(1);
+ });
+
+ it("shrinks monotonically as edges grow, bounded below", () => {
+ const a = edgeIntensityScale(10_000);
+ const b = edgeIntensityScale(80_000);
+ expect(a).toBeLessThan(1);
+ expect(b).toBeLessThan(a);
+ expect(b).toBeGreaterThanOrEqual(0.05);
+ /* Never collapses to zero even at absurd counts */
+ expect(edgeIntensityScale(50_000_000)).toBeGreaterThanOrEqual(0.05);
+ });
+
+ it("keeps accumulated brightness roughly flat (scale ~ 1/sqrt(n))", () => {
+ /* 4x the edges → each ~half as bright → similar total glow */
+ const ref = edgeIntensityScale(EDGE_REFERENCE_COUNT * 4);
+ expect(ref).toBeCloseTo(0.5, 5);
+ });
+});
+
+describe("bloomIntensityScale", () => {
+ it("stays full through the reference count (preserves the glow), then eases", () => {
+ /* A whole mid-size repo (≤25k nodes) keeps full bloom — the wow effect. */
+ expect(bloomIntensityScale(NODE_REFERENCE_COUNT)).toBe(1);
+ expect(bloomIntensityScale(20_000)).toBe(1);
+ /* Only very large clouds ease back, and never below the floor. */
+ expect(bloomIntensityScale(100_000)).toBeLessThan(1);
+ expect(bloomIntensityScale(10_000_000)).toBeGreaterThanOrEqual(0.7);
+ });
+});
+
+describe("nodeBoostScale", () => {
+ it("keeps node halos bright through the reference count, then eases gently", () => {
+ expect(nodeBoostScale(NODE_REFERENCE_COUNT)).toBe(1);
+ expect(nodeBoostScale(20_000)).toBe(1);
+ const big = nodeBoostScale(100_000);
+ expect(big).toBeGreaterThan(0.8);
+ expect(big).toBeLessThan(1);
+ /* Floored — never fully flat, even at millions of nodes. */
+ expect(nodeBoostScale(10_000_000)).toBeGreaterThanOrEqual(0.8);
+ });
+});
+
+describe("nodeGlowBoost", () => {
+ /* Star-class palette from lib/colors.ts STAR_LEGEND */
+ const BLUE_GIANT = "#80a0ff"; // 50+ connections (hubs)
+ const WHITE = "#e8e8ff"; // mid degree
+ const YELLOW = "#ffe080"; // mid degree
+ const RED_DWARF = "#ff6050"; // leaves
+
+ it("makes blue hubs glow the most", () => {
+ expect(glow(BLUE_GIANT)).toBeGreaterThan(glow(RED_DWARF));
+ expect(glow(BLUE_GIANT)).toBeGreaterThan(glow(WHITE));
+ expect(glow(BLUE_GIANT)).toBeGreaterThan(glow(YELLOW));
+ });
+
+ it("gives red leaves a modest boost — above white/yellow, below blue", () => {
+ expect(glow(RED_DWARF)).toBeGreaterThan(glow(WHITE));
+ expect(glow(RED_DWARF)).toBeGreaterThan(glow(YELLOW));
+ expect(glow(RED_DWARF)).toBeLessThan(glow(BLUE_GIANT));
+ });
+
+ it("keeps white/yellow low so they don't blow out the bloom", () => {
+ /* Old formula gave white ~2.0×; it must now be well under the blue hub. */
+ expect(glow(WHITE)).toBeLessThan(1.7);
+ expect(glow(YELLOW)).toBeLessThan(1.7);
+ });
+
+ it("never dims a node (multiplier ≥ 1)", () => {
+ for (const hex of [BLUE_GIANT, WHITE, YELLOW, RED_DWARF, "#06b6d4", "#a855f7"]) {
+ expect(glow(hex)).toBeGreaterThanOrEqual(1);
+ }
+ });
+});
+
+describe("clampDisplaySettings", () => {
+ it("clamps each setting to its range and fills defaults", () => {
+ expect(clampDisplaySettings({})).toEqual(DEFAULT_DISPLAY_SETTINGS);
+ expect(
+ clampDisplaySettings({ edgeBrightness: 99, nodeGlow: -5, bloom: 1.5 }),
+ ).toEqual({ edgeBrightness: 3, nodeGlow: 0, bloom: 1.5 });
+ expect(clampDisplaySettings({ bloom: Number.NaN }).bloom).toBe(
+ DEFAULT_DISPLAY_SETTINGS.bloom,
+ );
+ });
+});
diff --git a/graph-ui/src/lib/density.ts b/graph-ui/src/lib/density.ts
new file mode 100644
index 000000000..63bea4893
--- /dev/null
+++ b/graph-ui/src/lib/density.ts
@@ -0,0 +1,134 @@
+/* Visual density compensation.
+ *
+ * The white-blob-at-scale failure is dominated by EDGES: they blend
+ * additively and a 15k-node graph carries ~80k long lines crossing the
+ * center, so their glow stacks into an opaque wash. Nodes are far fewer and
+ * discrete — their bloom halos are the whole "wow", so we keep those bright.
+ *
+ * Strategy: dim edges hard (they cause the blob), keep nodes and bloom near
+ * full so the bright stars still pop; only ease nodes/bloom back on genuinely
+ * huge clouds where even discrete points overlap. Highlighted elements are
+ * never scaled — a selection stays bright against the dimmed rest. */
+
+/* Edge counts at/below this render exactly as before. */
+export const EDGE_REFERENCE_COUNT = 2500;
+const EDGE_MIN_SCALE = 0.05;
+
+export function edgeIntensityScale(edgeCount: number): number {
+ if (edgeCount <= EDGE_REFERENCE_COUNT) return 1;
+ /* ~1/sqrt(n): 4× the edges → each ~half as bright → total glow ~flat. */
+ return Math.max(EDGE_MIN_SCALE, Math.sqrt(EDGE_REFERENCE_COUNT / edgeCount));
+}
+
+/* Node glow and bloom stay at full strength up to here — this covers the
+ * common "load the whole repo" case (tens of thousands of nodes) so the
+ * bright-star look is preserved. */
+export const NODE_REFERENCE_COUNT = 25000;
+/* …then ease gently toward these floors as the cloud grows past the fade end,
+ * where even discrete point sprites start to overlap and over-bloom. */
+const NODE_FADE_END = 250000;
+const BLOOM_FLOOR = 0.7;
+const NODE_BOOST_FLOOR = 0.8;
+
+function fadeFactor(nodeCount: number): number {
+ if (nodeCount <= NODE_REFERENCE_COUNT) return 0;
+ return Math.min(
+ 1,
+ (nodeCount - NODE_REFERENCE_COUNT) / (NODE_FADE_END - NODE_REFERENCE_COUNT),
+ );
+}
+
+export function bloomIntensityScale(nodeCount: number): number {
+ return 1 - fadeFactor(nodeCount) * (1 - BLOOM_FLOOR);
+}
+
+/* Per-node glow boost: full up to the reference count, then a gentle,
+ * high-floored fade so large clouds don't merge into mush while moderate
+ * graphs keep their halos. */
+export function nodeBoostScale(nodeCount: number): number {
+ return 1 - fadeFactor(nodeCount) * (1 - NODE_BOOST_FLOOR);
+}
+
+/* Colour-aware glow multiplier applied to each node before bloom.
+ *
+ * Nodes are coloured as star classes by degree: blue giants (high-degree
+ * hubs) → white/yellow (mid) → red dwarfs (leaves). Bloom is luminance-
+ * thresholded, and blue has a tiny luminance weight, so a naive
+ * brightness-based boost makes white/yellow blow out while blue and red stay
+ * flat. Instead we boost by *channel dominance*: a blue-dominant node gets the
+ * strongest boost (the important hubs shine brightest), a red-dominant node a
+ * modest one, and white/yellow — which need no help to bloom — the least.
+ *
+ * r, g, b are 0..1 colour channels. Returns a multiplier ≥ 1. */
+const GLOW_BASE = 1.35;
+const GLOW_BLUE_GAIN = 2.4;
+const GLOW_RED_GAIN = 0.9;
+
+export function nodeGlowBoost(r: number, g: number, b: number): number {
+ /* Blue that exceeds both red and green → cool hub. Red that exceeds both
+ * green and blue → warm leaf (green cutoff keeps yellow/orange out of the
+ * red term so they are not boosted). */
+ const blueness = Math.max(0, b - Math.max(r, g));
+ const redness = Math.max(0, r - Math.max(g, b));
+ return GLOW_BASE + blueness * GLOW_BLUE_GAIN + redness * GLOW_RED_GAIN;
+}
+
+/* ── Manual display settings ──────────────────────────────────── *
+ * User-facing multipliers layered ON TOP of the adaptive scales above:
+ * the adaptive scale picks a sane default for the current density, the
+ * sliders let the user push contrast/brightness around it. Persisted
+ * globally (a display preference, not a per-project fact). */
+
+export interface DisplaySettings {
+ /** Edge brightness multiplier (0.1–3, default 1). */
+ edgeBrightness: number;
+ /** Node glow-boost multiplier (0–2, default 1). */
+ nodeGlow: number;
+ /** Bloom intensity multiplier (0–2, default 1). */
+ bloom: number;
+}
+
+export const DEFAULT_DISPLAY_SETTINGS: DisplaySettings = {
+ edgeBrightness: 1,
+ nodeGlow: 1,
+ bloom: 1,
+};
+
+export const DISPLAY_LIMITS = {
+ edgeBrightness: { min: 0.1, max: 3 },
+ nodeGlow: { min: 0, max: 2 },
+ bloom: { min: 0, max: 2 },
+} as const;
+
+const DISPLAY_STORAGE_KEY = "cbm-display";
+
+function clampSetting(key: keyof DisplaySettings, value: unknown): number {
+ const { min, max } = DISPLAY_LIMITS[key];
+ const n = typeof value === "number" ? value : Number.NaN;
+ if (!Number.isFinite(n)) return DEFAULT_DISPLAY_SETTINGS[key];
+ return Math.min(max, Math.max(min, n));
+}
+
+export function clampDisplaySettings(
+ raw: Partial<DisplaySettings>,
+): DisplaySettings {
+ return {
+ edgeBrightness: clampSetting("edgeBrightness", raw.edgeBrightness),
+ nodeGlow: clampSetting("nodeGlow", raw.nodeGlow),
+ bloom: clampSetting("bloom", raw.bloom),
+ };
+}
+
+export function loadDisplaySettings(): DisplaySettings {
+ try {
+ const raw = localStorage.getItem(DISPLAY_STORAGE_KEY);
+ if (raw) return clampDisplaySettings(JSON.parse(raw));
+ } catch { /* ignore */ }
+ return DEFAULT_DISPLAY_SETTINGS;
+}
+
+export function saveDisplaySettings(settings: DisplaySettings) {
+ try {
+ localStorage.setItem(DISPLAY_STORAGE_KEY, JSON.stringify(settings));
+ } catch { /* ignore */ }
+}