Spaces:
Sleeping

studiq-backend / make_fast_graph.py
StudIQ Deploy Bot
Deploy StudIQ v0.5.1 β€” 2026-07-17 08:37 UTC
358492d
Raw History Blame Contribute Delete
50.9 kB
#!/usr/bin/env python3 """ Generate a fast, cluster-first graph viewer from graphify graph.json. Uses Canvas2D with viewport culling, squared distance tests, and batched stroke drawing. """ import json import math import random import sys import os from collections import defaultdict, Counter random.seed(42) SCOPE_CONFIGS = { "studiq": { "json": "/Users/baljotchohan/Projects/StudIQ/studiq/graphify-out/graph.json", "out": "/Users/baljotchohan/Projects/StudIQ/studiq/graphify-out/graph_fast.html", "title": "StudIQ Codebase Graph", }, "root": { "json": "/Users/baljotchohan/Projects/StudIQ/graphify-out/graph.json", "out": "/Users/baljotchohan/Projects/StudIQ/graphify-out/graph_fast.html", "title": "StudIQ Root Graph", } } COLORS = [ "#00f2fe", "#b224ef", "#ff007f", "#39ff14", "#ff00ff", "#00ffff", "#ffb703", "#fb8500", "#ff006e", "#8338ec", "#3a86c8", "#ffbe0b", "#4895ef", "#4cc9f0", "#7209b7", "#f72585", "#3f37c9", "#3b28cc", "#a900ff", "#00bbf9", ] def spiral_layout(communities): """Place communities in a tight spiral layout.""" comms = sorted(communities.items(), key=lambda x: -len(x[1])) positions = {} golden = (1 + math.sqrt(5)) / 2 for i, (cid, nodes) in enumerate(comms): r = math.sqrt(i + 1) * 160 theta = 2 * math.pi * i / (golden ** 2) positions[cid] = (r * math.cos(theta), r * math.sin(theta)) return positions def build_fast_html(scope: str): cfg = SCOPE_CONFIGS[scope] print(f"[{scope}] Reading {cfg['json']}...") with open(cfg["json"]) as f: data = json.load(f) raw_nodes = data["nodes"] raw_links = data["links"] target_dir = "/Users/baljotchohan/Projects/StudIQ" if scope == "root" else "/Users/baljotchohan/Projects/StudIQ/studiq" # Determine top-level folder prefix for each node node_folder = {} for n in raw_nodes: sf = n.get("source_file", "") sf = sf.replace("\\", "/") folder = "root" if sf.startswith(target_dir): rel = sf[len(target_dir):].lstrip("/") parts = rel.split("/") if parts and parts[0]: folder = parts[0] node_folder[n["id"]] = folder # Re-map small communities (size < min_size) to folder-specific misc communities min_size = 15 if scope == "root" else 6 orig_comm_sizes = Counter(n.get("community", 0) for n in raw_nodes) for n in raw_nodes: cid = n.get("community", 0) if orig_comm_sizes[cid] < min_size: folder = node_folder.get(n["id"], "other") n["community"] = f"misc_{folder}" # Build community structure comm_nodes = defaultdict(list) node_by_id = {} for n in raw_nodes: cid = n["community"] comm_nodes[cid].append(n) node_by_id[n["id"]] = n # Assign colors to communities comm_hex = {} comm_rgb = {} comm_list = sorted(comm_nodes.keys(), key=lambda x: str(x)) for i, cid in enumerate(comm_list): hex_color = COLORS[i % len(COLORS)] comm_hex[cid] = hex_color # Parse hex to rgb string for Canvas usage r_val = int(hex_color[1:3], 16) g_val = int(hex_color[3:5], 16) b_val = int(hex_color[5:7], 16) comm_rgb[cid] = f"{r_val},{g_val},{b_val}" # Determine community labels comm_label = {} for cid, ns in comm_nodes.items(): if str(cid).startswith("misc_"): folder = str(cid)[5:] comm_label[cid] = f"Other {folder} files ({len(ns)})" else: folders = [node_folder.get(n["id"], "other") for n in ns] dom_folder = Counter(folders).most_common(1)[0][0] if folders else "other" comm_label[cid] = f"{dom_folder} - Comm {cid} ({len(ns)})" # Spiral layout for communities comm_positions = spiral_layout(comm_nodes) # Pre-compute node positions within each community (mini circle) node_positions = {} for cid, ns in comm_nodes.items(): cx, cy = comm_positions.get(cid, (0, 0)) count = len(ns) radius = max(30, math.sqrt(count) * 20) for i, n in enumerate(ns): angle = 2 * math.pi * i / max(count, 1) nx = cx + radius * math.cos(angle) ny = cy + radius * math.sin(angle) node_positions[n["id"]] = (nx, ny) # Build lightweight node list for cluster view cluster_nodes = [] for cid in comm_list: ns = comm_nodes[cid] cx, cy = comm_positions.get(cid, (0, 0)) sz = max(15, min(65, math.sqrt(len(ns)) * 8)) cluster_nodes.append({ "id": f"c_{cid}", "cid": cid, "label": comm_label.get(cid, str(cid)), "x": cx, "y": cy, "r": sz, "color": comm_hex.get(cid, "#4E79A7"), "color_rgb": comm_rgb.get(cid, "78,121,167"), "count": len(ns), }) # Build cluster-level edges (edges between communities) cluster_edge_counts = defaultdict(int) for lnk in raw_links: src = node_by_id.get(lnk["source"]) tgt = node_by_id.get(lnk["target"]) if src and tgt: sc = src["community"] tc = tgt["community"] if sc != tc: key = (min(str(sc), str(tc)), max(str(sc), str(tc))) cluster_edge_counts[key] += 1 cluster_edges = [] for (sc, tc), cnt in cluster_edge_counts.items(): cluster_edges.append({ "source": f"c_{sc}", "target": f"c_{tc}", "w": min(4, 1 + cnt // 5) }) # Full nodes per community (for drill-down) community_data = {} for cid, ns in comm_nodes.items(): community_data[str(cid)] = { "nodes": [ { "id": n["id"], "label": n.get("label", n["id"])[:40], "file_type": n.get("file_type", "code"), "source_file": n.get("source_file", ""), "x": node_positions[n["id"]][0], "y": node_positions[n["id"]][1], "color": comm_hex.get(cid, "#4E79A7"), "color_rgb": comm_rgb.get(cid, "78,121,167"), } for n in ns ], "links": [ {"s": lnk["source"], "t": lnk["target"]} for lnk in raw_links if node_by_id.get(lnk["source"], {}).get("community") == cid and node_by_id.get(lnk["target"], {}).get("community") == cid ], "color": comm_hex.get(cid, "#4E79A7"), "color_rgb": comm_rgb.get(cid, "78,121,167"), "label": comm_label.get(cid, str(cid)), } stats_str = f"{len(raw_nodes):,} nodes Β· {len(raw_links):,} edges Β· {len(comm_list):,} communities" # Compute bounding box for initial viewport all_cx = [c["x"] for c in cluster_nodes] all_cy = [c["y"] for c in cluster_nodes] if all_cx: min_x, max_x = min(all_cx), max(all_cx) min_y, max_y = min(all_cy), max(all_cy) else: min_x = max_x = min_y = max_y = 0 center_x = (min_x + max_x) / 2 center_y = (min_y + max_y) / 2 html = f"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{cfg['title']} β€” Fast Viewer</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"> <style> :root {{ --bg-color: #f8fafc; --panel-bg: rgba(255, 255, 255, 0.85); --panel-border: rgba(0, 0, 0, 0.08); --primary: #0284c7; --primary-glow: rgba(2, 132, 199, 0.08); --secondary: #7c3aed; --text-primary: #0f172a; --text-secondary: #475569; --text-muted: #64748b; --font-sans: 'Outfit', -apple-system, sans-serif; --font-mono: 'JetBrains Mono', monospace; }} * {{ box-sizing: border-box; margin: 0; padding: 0; }} body {{ background: var(--bg-color); color: var(--text-primary); font-family: var(--font-sans); height: 100vh; overflow: hidden; position: relative; }} /* Fullscreen Canvas background */ #main {{ width: 100vw; height: 100vh; position: absolute; inset: 0; overflow: hidden; z-index: 1; }} #canvas-wrap {{ width: 100%; height: 100%; position: relative; cursor: grab; }} #canvas-wrap.dragging {{ cursor: grabbing; }} canvas {{ display: block; width: 100%; height: 100%; }} /* Floating glassmorphism HUD panels */ .glass-panel {{ background: var(--panel-bg); border: 1px solid var(--panel-border); backdrop-filter: blur(18px) saturate(140%); -webkit-backdrop-filter: blur(18px) saturate(140%); border-radius: 20px; box-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.08), 0 1px 3px rgba(0,0,0,0.02); z-index: 10; }} /* Top HUD bar */ #topbar {{ position: absolute; top: 20px; left: 20px; right: 20px; height: 64px; display: flex; align-items: center; gap: 16px; padding: 0 24px; }} #topbar h1 {{ font-size: 17px; font-weight: 800; letter-spacing: -0.02em; background: linear-gradient(135deg, var(--primary), var(--secondary)); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; display: flex; align-items: center; gap: 8px; }} #search-container {{ position: relative; flex: 1; max-width: 280px; }} #search {{ width: 100%; background: #ffffff; border: 1px solid #d1d5db; border-radius: 12px; color: var(--text-primary); padding: 10px 16px; font-size: 13px; outline: none; transition: all 0.2s; }} #search:focus {{ border-color: var(--primary); box-shadow: 0 0 0 2px var(--primary-glow); }} #search-results {{ position: absolute; top: calc(100% + 8px); left: 0; right: 0; background: #ffffff; border: 1px solid var(--panel-border); border-radius: 12px; max-height: 250px; overflow-y: auto; display: none; box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1), 0 8px 10px -6px rgba(0,0,0,0.1); }} .sr-item {{ padding: 10px 16px; cursor: pointer; font-size: 12px; border-bottom: 1px solid #f1f5f9; transition: all 0.2s; color: var(--text-primary); }} .sr-item:hover {{ background: rgba(2, 132, 199, 0.06); color: var(--primary); }} #back-btn {{ display: none; align-items: center; gap: 6px; background: rgba(2, 132, 199, 0.08); border: 1px solid rgba(2, 132, 199, 0.15); color: var(--primary); padding: 10px 20px; border-radius: 12px; cursor: pointer; font-size: 13px; font-weight: 600; transition: all 0.2s; }} #back-btn:hover {{ background: rgba(2, 132, 199, 0.15); box-shadow: 0 0 10px rgba(2, 132, 199, 0.1); }} #mode-label {{ font-size: 12px; font-weight: 700; color: var(--text-secondary); background: rgba(0,0,0,0.02); padding: 6px 12px; border-radius: 8px; border: 1px solid rgba(0,0,0,0.03); }} #stats-bar {{ font-size: 12px; color: var(--text-muted); margin-left: auto; font-family: var(--font-mono); }} /* Right Sidebar Panel */ #sidebar {{ position: absolute; top: 104px; right: 20px; bottom: 20px; width: 360px; display: flex; flex-direction: column; overflow: hidden; }} #info-title {{ font-size: 11px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.1em; padding: 20px 24px 12px; border-bottom: 1px solid rgba(0, 0, 0, 0.05); }} #info-content {{ padding: 24px; font-size: 13.5px; line-height: 1.6; flex: 1; overflow-y: auto; }} /* Custom components inside info panel */ .inspect-card {{ background: #ffffff; border: 1px solid rgba(0, 0, 0, 0.05); border-radius: 16px; padding: 16px; margin-bottom: 20px; animation: fadeIn 0.4s ease; }} .inspect-title {{ font-size: 16px; font-weight: 700; color: var(--text-primary); margin-bottom: 12px; word-break: break-all; }} .badge {{ display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 99px; font-size: 9.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 14px; }} .badge-community {{ background: rgba(2, 132, 199, 0.08); color: var(--primary); border: 1px solid rgba(2, 132, 199, 0.15); }} .badge-file {{ background: rgba(124, 58, 237, 0.08); color: var(--secondary); border: 1px solid rgba(124, 58, 237, 0.15); }} .prop-list {{ display: flex; flex-direction: column; gap: 10px; }} .prop-item {{ display: flex; justify-content: space-between; font-size: 12px; border-bottom: 1px dashed rgba(0,0,0,0.05); padding-bottom: 6px; }} .prop-lbl {{ color: var(--text-secondary); }} .prop-val {{ font-weight: 600; font-family: var(--font-mono); }} .path-box {{ background: #f1f5f9; border: 1px solid #e2e8f0; border-radius: 8px; padding: 8px 12px; font-family: var(--font-mono); font-size: 11px; color: #0369a1; word-break: break-all; margin-top: 6px; }} #info-content .empty {{ color: var(--text-muted); font-style: italic; text-align: center; display: block; margin-top: 40px; }} /* Connections HUD */ #neighbors {{ padding: 0 24px 20px; border-top: 1px solid rgba(0, 0, 0, 0.05); }} #neighbors h4 {{ font-size: 11px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.08em; margin: 16px 0 10px; }} #nb-list {{ display: flex; flex-direction: column; gap: 6px; max-height: 180px; overflow-y: auto; }} .nb-link {{ display: flex; align-items: center; padding: 8px 12px; border-radius: 8px; cursor: pointer; font-size: 11px; color: var(--text-secondary); border: 1px solid #f1f5f9; background: #ffffff; border-left-width: 4px; transition: all 0.2s; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }} .nb-link:hover {{ background: #f8fafc; color: var(--text-primary); transform: translateX(4px); border-color: #e2e8f0; }} /* Legend HUD cards */ #legend-section {{ padding: 20px 24px; border-top: 1px solid rgba(0, 0, 0, 0.05); overflow-y: auto; max-height: 250px; }} #legend-section h4 {{ font-size: 11px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 12px; }} #legend {{ display: flex; flex-direction: column; gap: 8px; }} .lg-item {{ display: flex; align-items: center; gap: 10px; padding: 8px 12px; cursor: pointer; border-radius: 10px; border: 1px solid #f1f5f9; background: #ffffff; transition: all 0.2s; }} .lg-item:hover {{ background: #f8fafc; border-color: #e2e8f0; transform: translateY(-1px); }} .lg-dot {{ width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }} .lg-label {{ font-size: 11px; font-weight: 500; color: var(--text-secondary); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }} .lg-cnt {{ font-size: 10px; color: var(--text-muted); font-family: var(--font-mono); background: rgba(0,0,0,0.05); padding: 2px 6px; border-radius: 4px; }} /* Zoom Control Buttons */ #zoom-ctrl {{ position: absolute; bottom: 20px; left: 20px; display: flex; gap: 8px; z-index: 10; }} .zoom-btn {{ width: 42px; height: 42px; background: var(--panel-bg); border: 1px solid var(--panel-border); color: var(--text-secondary); border-radius: 12px; font-size: 20px; font-weight: 600; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05); backdrop-filter: blur(8px); transition: all 0.2s; }} .zoom-btn:hover {{ background: #ffffff; color: var(--text-primary); border-color: rgba(0, 0, 0, 0.15); transform: translateY(-2px); }} /* Beautiful glowing Tooltip */ #tooltip {{ position: absolute; background: rgba(255, 255, 255, 0.95); border: 1px solid rgba(2, 132, 199, 0.2); border-radius: 12px; padding: 10px 14px; font-size: 12px; color: #0f172a; pointer-events: none; display: none; max-width: 250px; backdrop-filter: blur(12px); z-index: 100; line-height: 1.5; box-shadow: 0 10px 20px -5px rgba(0, 0, 0, 0.1); animation: scaleIn 0.15s cubic-bezier(0.16, 1, 0.3, 1); }} #loading {{ position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; background: var(--bg-color); z-index: 1000; flex-direction: column; gap: 16px; }} #loading-bar-wrap {{ width: 240px; height: 4px; background: rgba(0,0,0,0.05); border-radius: 2px; overflow: hidden; }} #loading-bar {{ height: 100%; width: 0%; background: linear-gradient(90deg, var(--primary), var(--secondary)); transition: width 0.3s; }} #loading-text {{ font-size: 12px; color: var(--text-muted); font-family: var(--font-mono); text-transform: uppercase; letter-spacing: 0.1em; }} @keyframes fadeIn {{ from {{ opacity: 0; transform: translateY(4px); }} to {{ opacity: 1; transform: translateY(0); }} }} @keyframes scaleIn {{ from {{ opacity: 0; transform: scale(0.95); }} to {{ opacity: 1; transform: scale(1); }} }} </style> </head> <body> <div id="main"> <div id="canvas-wrap"> <canvas id="c"></canvas> </div> </div> <div id="topbar" class="glass-panel"> <h1>⬑ {cfg['title']}</h1> <div id="search-container"> <input id="search" type="text" placeholder="Search files/symbols..." autocomplete="off"> <div id="search-results"></div> </div> <button id="back-btn" onclick="exitDrillDown()">← Back to Overview</button> <span id="mode-label">Community Overview</span> <span id="stats-bar">{stats_str}</span> </div> <div id="sidebar" class="glass-panel"> <div id="info-title">Properties Inspector</div> <div id="info-content"><span class="empty">Click any node in the map to inspect properties</span></div> <div id="neighbors"> <h4>Connected Relationships</h4> <div id="nb-list"></div> </div> <div id="legend-section"> <h4>Top Modules (Sizing)</h4> <div id="legend"></div> </div> </div> <div id="zoom-ctrl"> <button class="zoom-btn" onclick="zoom(1.25)" title="Zoom in">+</button> <button class="zoom-btn" onclick="zoom(0.8)" title="Zoom out">βˆ’</button> <button class="zoom-btn" onclick="resetView()" title="Fit" style="font-size:16px">⊑</button> </div> <div id="tooltip"></div> <div id="loading"> <div id="loading-bar-wrap"><div id="loading-bar"></div></div> <div id="loading-text">Bootstrapping Graphify Workspace…</div> </div> <script> // ── Data ───────────────────────────────────────────────────────────── let CLUSTER_NODES = {json.dumps(cluster_nodes)}; let CLUSTER_EDGES = {json.dumps(cluster_edges)}; let COMMUNITY_DATA = {json.dumps(community_data)}; // ── State ───────────────────────────────────────────────────────────── let mode = 'cluster'; // 'cluster' | 'drill' let drillCid = null; let nodes = []; let edges = []; let nodeById = {{}}; let edgeAdj = {{}}; // nodeId -> [nodeId] let isInteracting = false; let interactionTimeout = null; function startInteraction() {{ isInteracting = true; if (interactionTimeout) clearTimeout(interactionTimeout); interactionTimeout = setTimeout(() => {{ isInteracting = false; requestDraw(); }}, 80); // 80ms debounce for extra responsiveness }} // Viewport let vx = {center_x}, vy = {center_y}, vscale = 1; let W = 0, H = 0; let isDragging = false, dragX = 0, dragY = 0, dragVX = 0, dragVY = 0; // Hover / selection let hoveredId = null, selectedId = null; const canvas = document.getElementById('c'); const ctx = canvas.getContext('2d'); const wrap = document.getElementById('canvas-wrap'); // ── Optimized Preprocessed Structures ── let nodesByColor = {{}}; let edgesByColor = {{}}; const spriteCanvases = {{}}; const searchIndex = []; // Pre-render gorgeous glossy bubble sprites for every color on startup function initSprites() {{ const colors = new Set(); CLUSTER_NODES.forEach(n => {{ if (n.color_rgb) colors.add(n.color_rgb); }}); Object.values(COMMUNITY_DATA).forEach(c => {{ if (c.color_rgb) colors.add(c.color_rgb); }}); colors.add('120,130,200'); // default fallback colors.forEach(rgb => {{ const canvas = document.createElement('canvas'); canvas.width = 128; canvas.height = 128; const sctx = canvas.getContext('2d'); // Draw outer glow shadow using Canvas context properties sctx.shadowColor = 'rgba(0, 0, 0, 0.12)'; sctx.shadowBlur = 10; sctx.shadowOffsetX = 0; sctx.shadowOffsetY = 4; sctx.fillStyle = 'rgba(0,0,0,1)'; sctx.beginPath(); sctx.arc(64, 64, 56, 0, Math.PI * 2); sctx.fill(); sctx.shadowBlur = 0; // reset sctx.shadowOffsetY = 0; // Draw 3D radial gradient bubble const grad = sctx.createRadialGradient(64 - 16, 64 - 16, 2, 64, 64, 58); grad.addColorStop(0, `rgba(\${{rgb}}, 1.0)`); grad.addColorStop(0.3, `rgba(\${{rgb}}, 0.95)`); grad.addColorStop(0.7, `rgba(\${{rgb}}, 0.75)`); grad.addColorStop(1, `rgba(\${{rgb}}, 0.55)`); sctx.fillStyle = grad; sctx.beginPath(); sctx.arc(64, 64, 56, 0, Math.PI * 2); sctx.fill(); // Add realistic 3D gloss highlight curve const highlightGrad = sctx.createLinearGradient(0, 0, 0, 128); highlightGrad.addColorStop(0, 'rgba(255, 255, 255, 0.6)'); highlightGrad.addColorStop(0.5, 'rgba(255, 255, 255, 0.05)'); highlightGrad.addColorStop(1, 'rgba(255, 255, 255, 0)'); sctx.fillStyle = highlightGrad; sctx.beginPath(); sctx.arc(64, 64, 54, 0, Math.PI * 2); sctx.fill(); // Draw fine outer ring sctx.strokeStyle = `rgba(\${{rgb}}, 0.95)`; sctx.lineWidth = 1.5; sctx.stroke(); spriteCanvases[rgb] = canvas; }}); }} function preprocessData() {{ // 1. Group nodes by color_rgb nodesByColor = {{}}; for (let i = 0; i < nodes.length; i++) {{ const n = nodes[i]; const rgb = n.color_rgb || '120,130,200'; if (!nodesByColor[rgb]) nodesByColor[rgb] = []; nodesByColor[rgb].push(n); }} // 2. Group edges by community color (using source node's color) edgesByColor = {{}}; for (let i = 0; i < edges.length; i++) {{ const e = edges[i]; const src = nodeById[e.source]; const rgb = src && src.color_rgb ? src.color_rgb : '120,130,200'; if (!edgesByColor[rgb]) edgesByColor[rgb] = []; edgesByColor[rgb].push(e); }} }} function buildSearchIndex() {{ searchIndex.length = 0; // Clear for (const [cid, cd] of Object.entries(COMMUNITY_DATA)) {{ for (let i = 0; i < cd.nodes.length; i++) {{ const n = cd.nodes[i]; searchIndex.push({{ id: n.id, label: n.label, labelLower: n.label.toLowerCase(), source_file: n.source_file, source_file_lower: n.source_file.toLowerCase(), cid: parseInt(cid) }}); }} }} }} // Throttled Drawing Lock let renderPending = false; function requestDraw() {{ if (!renderPending) {{ renderPending = true; requestAnimationFrame(() => {{ draw(); renderPending = false; }}); }} }} // ── Resize ──────────────────────────────────────────────────────────── function resize() {{ const isFirst = (W === 0 || H === 0); W = canvas.width = wrap.clientWidth || window.innerWidth || 800; H = canvas.height = wrap.clientHeight || window.innerHeight || 600; if (isFirst) {{ fitAll(); }} requestDraw(); }} window.addEventListener('resize', resize); // ── Coordinate helpers ── function screenToWorld(sx, sy) {{ return [(sx - W/2) / vscale + vx, (sy - H/2) / vscale + vy]; }} // ── Initial fit ─────────────────────────────────────────────────────── function fitAll() {{ if (!nodes.length) return; let minX=Infinity, maxX=-Infinity, minY=Infinity, maxY=-Infinity; for (let i = 0; i < nodes.length; i++) {{ const n = nodes[i]; minX = Math.min(minX, n.x); maxX = Math.max(maxX, n.x); minY = Math.min(minY, n.y); maxY = Math.max(maxY, n.y); }} const width = maxX - minX; const height = maxY - minY; const padX = width * 0.1 + 100; const padY = height * 0.1 + 100; vx = (minX + maxX) / 2; vy = (minY + maxY) / 2; const viewW = W || wrap.clientWidth || window.innerWidth || 800; const viewH = H || wrap.clientHeight || window.innerHeight || 600; const sx = viewW / (width + padX * 2 || 1); const sy = viewH / (height + padY * 2 || 1); vscale = Math.min(sx, sy, 3); if (vscale <= 0 || isNaN(vscale)) vscale = 0.5; }} function resetView() {{ fitAll(); requestDraw(); }} function zoom(factor) {{ vscale = Math.max(0.05, Math.min(20, vscale * factor)); requestDraw(); }} // ── Load mode ───────────────────────────────────────────────────────── function loadCluster() {{ mode = 'cluster'; drillCid = null; nodes = CLUSTER_NODES.map(n => ({{...n, _type: 'cluster'}})); edges = CLUSTER_EDGES; buildIndex(); preprocessData(); fitAll(); buildLegend(); document.getElementById('back-btn').style.display = 'none'; document.getElementById('mode-label').textContent = 'Community Overview'; clearInfo(); requestDraw(); }} function loadDrill(cid) {{ const cd = COMMUNITY_DATA[String(cid)]; if (!cd) return; mode = 'drill'; drillCid = cid; nodes = cd.nodes.map(n => ({{...n, _type: 'node'}})); edges = cd.links.map(l => ({{source: l.s, target: l.t, w: 1}})); buildIndex(); preprocessData(); fitAll(); document.getElementById('back-btn').style.display = 'inline-flex'; document.getElementById('mode-label').textContent = cd.label; clearInfo(); requestDraw(); }} function exitDrillDown() {{ loadCluster(); }} function buildIndex() {{ nodeById = {{}}; edgeAdj = {{}}; for (let i = 0; i < nodes.length; i++) {{ const n = nodes[i]; nodeById[n.id] = n; edgeAdj[n.id] = []; }} for (let i = 0; i < edges.length; i++) {{ const e = edges[i]; if (edgeAdj[e.source]) edgeAdj[e.source].push(e.target); if (edgeAdj[e.target]) edgeAdj[e.target].push(e.source); }} }} // ── Rendering (Zero-Allocation Throttled Pipeline) ─────────────────── function draw() {{ ctx.clearRect(0, 0, W, H); ctx.fillStyle = '#f8fafc'; // Matches classy white background color ctx.fillRect(0, 0, W, H); const selectedNeighbors = selectedId ? new Set(edgeAdj[selectedId] || []) : null; // 1. DRAFT MODE RENDER (Panning/Zooming/Interacting) if (isInteracting) {{ // 1.1 Draw selected edges only if (selectedId) {{ ctx.strokeStyle = 'rgba(2, 132, 199, 0.8)'; ctx.lineWidth = 1.8; ctx.beginPath(); for (let i = 0; i < edges.length; i++) {{ const e = edges[i]; if (e.source === selectedId || e.target === selectedId) {{ const src = nodeById[e.source]; const tgt = nodeById[e.target]; if (src && tgt) {{ const sx = W/2 + (src.x - vx) * vscale; const sy = H/2 + (src.y - vy) * vscale; const tx = W/2 + (tgt.x - vx) * vscale; const ty = H/2 + (tgt.y - vy) * vscale; ctx.moveTo(sx, sy); ctx.lineTo(tx, ty); }} }} }} ctx.stroke(); }} // 1.2 Draw all nodes as solid fast circles for (const rgb in nodesByColor) {{ const list = nodesByColor[rgb]; ctx.fillStyle = `rgb(${{rgb}})`; ctx.beginPath(); let hasNodes = false; for (let i = 0; i < list.length; i++) {{ const n = list[i]; const sx = W/2 + (n.x - vx) * vscale; const sy = H/2 + (n.y - vy) * vscale; const r = (n.r || 8) * Math.min(vscale, 2); if (r < 1.0) continue; if (sx + r < -10 || sx - r > W + 10 || sy + r < -10 || sy - r > H + 10) continue; ctx.moveTo(sx + r, sy); ctx.arc(sx, sy, r, 0, Math.PI * 2); hasNodes = true; }} if (hasNodes) ctx.fill(); }} // 1.3 Draw selection ring if (selectedId) {{ const sn = nodeById[selectedId]; if (sn) {{ const sx = W/2 + (sn.x - vx) * vscale; const sy = H/2 + (sn.y - vy) * vscale; const r = (sn.r || 8) * Math.min(vscale, 2); ctx.strokeStyle = '#0284c7'; ctx.lineWidth = 2.5; ctx.beginPath(); ctx.arc(sx, sy, r + 2, 0, Math.PI * 2); ctx.stroke(); }} }} return; }} // 2. FULL HIGH-QUALITY RENDER (Interactive Idle Mode) // 2.1 Draw unselected edges if (mode === 'cluster') {{ // Draw community links individually (few of them, scale by weight) for (let i = 0; i < edges.length; i++) {{ const e = edges[i]; if (selectedId && (e.source === selectedId || e.target === selectedId)) continue; const src = nodeById[e.source]; const tgt = nodeById[e.target]; if (!src || !tgt) continue; const sx = W/2 + (src.x - vx) * vscale; const sy = H/2 + (src.y - vy) * vscale; const tx = W/2 + (tgt.x - vx) * vscale; const ty = H/2 + (tgt.y - vy) * vscale; if (Math.max(sx, tx) < -20 || Math.min(sx, tx) > W + 20 || Math.max(sy, ty) < -20 || Math.min(sy, ty) > H + 20) {{ continue; }} const rgb = src.color_rgb || '120,130,200'; ctx.strokeStyle = `rgba(${{rgb}}, ${{selectedId ? 0.03 : 0.22}})`; ctx.lineWidth = Math.round(e.w || 1) * 0.8; ctx.beginPath(); ctx.moveTo(sx, sy); ctx.lineTo(tx, ty); ctx.stroke(); }} }} else {{ // Draw internal links in community-colored batches (heavy file map mode) const unselAlpha = selectedId ? 0.02 : 0.15; ctx.lineWidth = 0.8; for (const rgb in edgesByColor) {{ ctx.strokeStyle = `rgba(${{rgb}}, ${{unselAlpha}})`; ctx.beginPath(); const list = edgesByColor[rgb]; for (let i = 0; i < list.length; i++) {{ const e = list[i]; if (selectedId && (e.source === selectedId || e.target === selectedId)) continue; const src = nodeById[e.source]; const tgt = nodeById[e.target]; if (!src || !tgt) continue; const sx = W/2 + (src.x - vx) * vscale; const sy = H/2 + (src.y - vy) * vscale; const tx = W/2 + (tgt.x - vx) * vscale; const ty = H/2 + (tgt.y - vy) * vscale; if (Math.max(sx, tx) < -20 || Math.min(sx, tx) > W + 20 || Math.max(sy, ty) < -20 || Math.min(sy, ty) > H + 20) {{ continue; }} ctx.moveTo(sx, sy); ctx.lineTo(tx, ty); }} ctx.stroke(); }} }} // 2.2 Draw selected/highlighted edges if (selectedId) {{ ctx.strokeStyle = 'rgba(2, 132, 199, 0.95)'; ctx.lineWidth = 2.5; ctx.beginPath(); for (let i = 0; i < edges.length; i++) {{ const e = edges[i]; if (e.source === selectedId || e.target === selectedId) {{ const src = nodeById[e.source]; const tgt = nodeById[e.target]; if (src && tgt) {{ const sx = W/2 + (src.x - vx) * vscale; const sy = H/2 + (src.y - vy) * vscale; const tx = W/2 + (tgt.x - vx) * vscale; const ty = H/2 + (tgt.y - vy) * vscale; ctx.moveTo(sx, sy); ctx.lineTo(tx, ty); }} }} }} ctx.stroke(); }} // 2.3 Draw nodes using pre-rendered high-performance bubble sprites for (const rgb in nodesByColor) {{ const list = nodesByColor[rgb]; const sprite = spriteCanvases[rgb]; if (!sprite) continue; for (let i = 0; i < list.length; i++) {{ const n = list[i]; const sx = W/2 + (n.x - vx) * vscale; const sy = H/2 + (n.y - vy) * vscale; const r = (n.r || 8) * Math.min(vscale, 2); if (r < 0.5) continue; if (sx + r < -20 || sx - r > W + 20 || sy + r < -20 || sy - r > H + 20) continue; const isSelected = n.id === selectedId; const isHovered = n.id === hoveredId; const isNeighbor = selectedNeighbors && selectedNeighbors.has(n.id); const isDimmed = selectedId && !isSelected && !isNeighbor; // Outer glow for selected/hovered nodes if (isSelected || isHovered) {{ ctx.globalAlpha = 0.25; ctx.fillStyle = `rgb(${{rgb}})`; ctx.beginPath(); ctx.arc(sx, sy, r + 8, 0, Math.PI * 2); ctx.fill(); }} // Draw tinted pre-rendered bubble ctx.globalAlpha = isDimmed ? 0.15 : 1.0; ctx.drawImage(sprite, sx - r, sy - r, r*2, r*2); // White outline for selection if (isSelected) {{ ctx.globalAlpha = 1.0; ctx.strokeStyle = '#0284c7'; ctx.lineWidth = 2.0; ctx.beginPath(); ctx.arc(sx, sy, r + 2, 0, Math.PI * 2); ctx.stroke(); }} }} }} ctx.globalAlpha = 1.0; // Reset // 2.4 Draw labels in a single batch (with culling and limit check) const minZoomForLabel = mode === 'cluster' ? 0.3 : 0.8; if (vscale >= minZoomForLabel) {{ ctx.font = "500 11px 'Outfit', -apple-system, sans-serif"; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; let labelsDrawn = 0; for (const rgb in nodesByColor) {{ const list = nodesByColor[rgb]; for (let i = 0; i < list.length; i++) {{ const n = list[i]; const sx = W/2 + (n.x - vx) * vscale; const sy = H/2 + (n.y - vy) * vscale; const r = (n.r || 8) * Math.min(vscale, 2); if (r <= 6) continue; if (sx + r < -20 || sx - r > W + 20 || sy + r < -20 || sy - r > H + 20) continue; const isSelected = n.id === selectedId; const isHovered = n.id === hoveredId; const isNeighbor = selectedNeighbors && selectedNeighbors.has(n.id); const isDimmed = selectedId && !isSelected && !isNeighbor; if (isDimmed && !isSelected && !isHovered) continue; if (labelsDrawn > 150 && !isSelected && !isHovered) continue; // Prevent label clutter const label = n.label || n.id; const lbl = label.length > 20 ? label.slice(0, 19) + '…' : label; ctx.fillStyle = isDimmed ? 'rgba(100, 110, 140, 0.15)' : (isSelected || isHovered ? '#0284c7' : '#334155'); const maxW = r * 4; ctx.fillText(lbl, sx, sy + r + 11, maxW); labelsDrawn++; }} }} }} }} // ── Hit test ── function hitTest(mx, my) {{ const [wx, wy] = screenToWorld(mx, my); let best = null, bestDistSq = Infinity; for (let i = 0; i < nodes.length; i++) {{ const n = nodes[i]; const dx = n.x - wx, dy = n.y - wy; const distSq = dx*dx + dy*dy; const threshold = (n.r || 8) / Math.min(vscale, 2) + 5 / vscale; const thresholdSq = threshold * threshold; if (distSq < thresholdSq && distSq < bestDistSq) {{ best = n; bestDistSq = distSq; }} }} return best; }} // ── Mouse events ────────────────────────────────────────────────────── canvas.addEventListener('mousedown', e => {{ isDragging = true; dragX = e.clientX; dragY = e.clientY; dragVX = vx; dragVY = vy; wrap.classList.add('dragging'); startInteraction(); }}); canvas.addEventListener('mousemove', e => {{ const rect = canvas.getBoundingClientRect(); const mx = e.clientX - rect.left; const my = e.clientY - rect.top; if (isDragging) {{ vx = dragVX - (e.clientX - dragX) / vscale; vy = dragVY - (e.clientY - dragY) / vscale; startInteraction(); requestDraw(); return; }} const n = hitTest(mx, my); const newHov = n ? n.id : null; if (newHov !== hoveredId) {{ hoveredId = newHov; if (hoveredId) {{ const nd = nodeById[hoveredId]; const tt = document.getElementById('tooltip'); tt.style.display = 'block'; tt.style.left = (mx + 14) + 'px'; tt.style.top = (my - 10) + 'px'; const label = nd.label || nd.id; tt.innerHTML = `<b>\${{label}}</b><br>\${{nd.file_type || ''}}\ \${{nd.source_file ? '<br><span style="color:#555;font-size:10px;word-break:break-all">' + nd.source_file + '</span>' : ''}}\ \${{nd.count ? '<br><span style="color:#0284c7;font-weight:700">' + nd.count + ' nodes</span>' : ''}}`; }} else {{ document.getElementById('tooltip').style.display = 'none'; }} requestDraw(); }} }}); canvas.addEventListener('mouseup', e => {{ const moved = Math.abs(e.clientX - dragX) + Math.abs(e.clientY - dragY) > 5; isDragging = false; isInteracting = false; wrap.classList.remove('dragging'); if (!moved) {{ const rect = canvas.getBoundingClientRect(); const n = hitTest(e.clientX - rect.left, e.clientY - rect.top); if (n) {{ handleNodeClick(n); }} else {{ selectedId = null; clearInfo(); requestDraw(); }} }} else {{ requestDraw(); // Draw final high quality frame }} }}); canvas.addEventListener('wheel', e => {{ e.preventDefault(); const rect = canvas.getBoundingClientRect(); const mx = e.clientX - rect.left; const my = e.clientY - rect.top; const [wx, wy] = screenToWorld(mx, my); const factor = e.deltaY < 0 ? 1.15 : 0.87; vscale = Math.max(0.05, Math.min(20, vscale * factor)); vx = wx - (mx - W/2) / vscale; vy = wy - (my - H/2) / vscale; startInteraction(); requestDraw(); }}, {{ passive: false }}); canvas.addEventListener('mouseleave', () => {{ isDragging = false; hoveredId = null; document.getElementById('tooltip').style.display = 'none'; wrap.classList.remove('dragging'); requestDraw(); }}); // ── Node click ──────────────────────────────────────────────────────── function handleNodeClick(n) {{ if (mode === 'cluster') {{ if (selectedId === n.id) {{ loadDrill(n.cid); return; }} selectedId = n.id; showClusterInfo(n); requestDraw(); return; }} selectedId = n.id; showNodeInfo(n); requestDraw(); }} canvas.addEventListener('dblclick', e => {{ const rect = canvas.getBoundingClientRect(); const n = hitTest(e.clientX - rect.left, e.clientY - rect.top); if (n && mode === 'cluster') {{ loadDrill(n.cid); }} }}); // ── Info panel ──────────────────────────────────────────────────────── function clearInfo() {{ selectedId = null; document.getElementById('info-content').innerHTML = '<span class="empty">Click any node in the map to inspect properties</span>'; document.getElementById('nb-list').innerHTML = ''; }} function showClusterInfo(n) {{ const cd = COMMUNITY_DATA[String(n.cid)]; const info = document.getElementById('info-content'); info.innerHTML = ` <div class="inspect-card"> <span class="badge badge-community">πŸ—‚οΈ Community Node</span> <div class="inspect-title">\${{n.label}}</div> <div class="prop-list"> <div class="prop-item"> <span class="prop-lbl">Community ID</span> <span class="prop-val">\${{n.cid}}</span> </div> <div class="prop-item"> <span class="prop-lbl">Files count</span> <span class="prop-val">\${{n.count}}</span> </div> </div> <div style="margin-top: 14px; font-size: 11.5px; color: var(--text-secondary); line-height: 1.5; background: rgba(2, 132, 199, 0.04); border: 1px solid rgba(2, 132, 199, 0.1); border-radius: 8px; padding: 10px;"> πŸ’‘ <b>Tip:</b> Click twice (or double-click) to zoom in and expand this community to view its internal file structure. </div> </div> `; if (cd) {{ const nb = document.getElementById('nb-list'); const samples = cd.nodes.slice(0, 12); nb.innerHTML = samples.map(sn => ` <span class="nb-link" style="border-left-color:\${{n.color}}" onclick="focusNodeInCommunity('\${{n.cid}}', '\${{sn.id}}')"> πŸ“„ \${{sn.label}} </span> `).join(''); }} }} function focusNodeInCommunity(cid, nodeId) {{ loadDrill(cid); setTimeout(() => {{ focusNode(nodeId); }}, 100); }} // Path cleaner for display function getDisplayPath(p) {{ return p || 'β€”'; }} function showNodeInfo(n) {{ const info = document.getElementById('info-content'); const pathVal = getDisplayPath(n.source_file); info.innerHTML = ` <div class="inspect-card"> <span class="badge badge-file">πŸ“„ \${{n.file_type || 'code'}}</span> <div class="inspect-title">\${{n.label}}</div> <div class="prop-list"> <div class="prop-item"> <span class="prop-lbl">Node ID</span> <span class="prop-val" style="font-size:10px; color: var(--primary);">\${{n.id}}</span> </div> <div class="prop-item"> <span class="prop-lbl">Type</span> <span class="prop-val">\${{n.file_type || 'code'}}</span> </div> </div> <div style="margin-top: 14px;"> <span class="prop-lbl" style="font-size: 11px; text-transform: uppercase; font-weight:700;">Source File Path</span> <div class="path-box">\${{pathVal}}</div> </div> </div> `; const neighbors = edgeAdj[n.id] || []; const nb = document.getElementById('nb-list'); nb.innerHTML = neighbors.slice(0, 20).map(nid => {{ const nd = nodeById[nid]; return nd ? ` <span class="nb-link" style="border-left-color:\${{n.color}}" onclick="focusNode('\${{nid}}')"> πŸ”— \${{nd.label}} </span> ` : ''; }}).join(''); }} function focusNode(id) {{ const n = nodeById[id]; if (!n) return; selectedId = id; vx = n.x; vy = n.y; if (vscale < 1.2) vscale = 1.5; showNodeInfo(n); requestDraw(); }} // ── Legend ──────────────────────────────────────────────────────────── function buildLegend() {{ const el = document.getElementById('legend'); const sorted = [...CLUSTER_NODES].sort((a,b) => b.count - a.count).slice(0, 20); el.innerHTML = sorted.map(n => ` <div class="lg-item" onclick="focusCluster(\${{n.cid}})"> <div class="lg-dot" style="background:\${{n.color}}; color:\${{n.color}}; box-shadow: 0 0 6px \${{n.color}}"></div> <span class="lg-label">\${{n.label}}</span> <span class="lg-cnt">\${{n.count}}</span> </div> `).join(''); }} // Legend focus function focusCluster(cid) {{ const n = CLUSTER_NODES.find(x => x.cid === cid); if (!n) return; selectedId = n.id; vx = n.x; vy = n.y; vscale = Math.max(vscale, 0.8); showClusterInfo(n); requestDraw(); }} // ── Search ──────────────────────────────────────────────────────────── const searchInput = document.getElementById('search'); const searchResults = document.getElementById('search-results'); searchInput.addEventListener('input', () => {{ const q = searchInput.value.trim().toLowerCase(); if (!q) {{ searchResults.style.display = 'none'; return; }} const matches = []; for (let i = 0; i < searchIndex.length; i++) {{ const item = searchIndex[i]; if (item.labelLower.includes(q) || item.source_file_lower.includes(q)) {{ matches.push(item); if (matches.length >= 15) break; }} }} if (!matches.length) {{ searchResults.style.display = 'none'; return; }} searchResults.innerHTML = matches.map(n => `<div class="sr-item" onclick="jumpToNode(\${{n.cid}}, '\${{n.id}}')">\${{n.label}} <span style="color:#666;font-size:10px">\${{n.source_file}}</span></div>` ).join(''); searchResults.style.display = 'block'; }}); document.addEventListener('click', e => {{ if (!searchResults.contains(e.target) && e.target !== searchInput) {{ searchResults.style.display = 'none'; }} }}); function jumpToNode(cid, nodeId) {{ searchResults.style.display = 'none'; searchInput.value = ''; if (mode !== 'drill' || drillCid !== cid) {{ loadDrill(cid); }} setTimeout(() => {{ const n = nodeById[nodeId]; if (n) {{ focusNode(nodeId); }} }}, 50); }} // ── Init ───────────────────────────────────────────────────────────── function init() {{ const lb = document.getElementById('loading-bar'); lb.style.width = '30%'; document.getElementById('loading-text').textContent = 'Generating visual assets…'; setTimeout(() => {{ initSprites(); lb.style.width = '60%'; document.getElementById('loading-text').textContent = 'Indexing codebase components…'; setTimeout(() => {{ buildSearchIndex(); lb.style.width = '90%'; document.getElementById('loading-text').textContent = 'Arranging layouts…'; setTimeout(() => {{ resize(); loadCluster(); lb.style.width = '100%'; setTimeout(() => {{ document.getElementById('loading').style.display = 'none'; }}, 150); }}, 50); }}, 50); }}, 50); }} init(); // ── WebSocket Live Sync ─────────────────────────────────────────────── function setupWebSocketSync() {{ const params = new URLSearchParams(window.location.search); const token = params.get('token') || ''; const scope = params.get('scope') || 'studiq'; // Construct WebSocket URL const wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = `\${{wsProto}}//\${{window.location.host}}/api/v1/admin/code-graphs/ws?token=\${{token}}&scope=\${{scope}}`; console.log('[Live Sync] Connecting to WebSocket...', wsUrl); let ws = new WebSocket(wsUrl); ws.onmessage = function(event) {{ try {{ const msg = JSON.parse(event.data); if (msg.event === 'graph_updated' && msg.scope === scope) {{ console.log('[Live Sync] Graph update notification received! Fetching latest data...'); fetchLatestGraphData(scope, token); }} }} catch (err) {{ console.error('[Live Sync] Error parsing WebSocket message:', err); }} }}; ws.onclose = function() {{ console.log('[Live Sync] WebSocket connection closed. Retrying in 5 seconds...'); setTimeout(setupWebSocketSync, 5000); }}; ws.onerror = function(err) {{ console.error('[Live Sync] WebSocket error:', err); ws.close(); }}; }} async function fetchLatestGraphData(scope, token) {{ const dataUrl = `/api/v1/admin/code-graphs/data?scope=\${{scope}}&token=\${{token}}`; try {{ const res = await fetch(dataUrl); if (!res.ok) throw new Error(`HTTP error \${{res.status}}`); const data = await res.json(); // Update data in memory CLUSTER_NODES = data.cluster_nodes; CLUSTER_EDGES = data.cluster_edges; COMMUNITY_DATA = data.community_data; console.log('[Live Sync] Graph data updated. Nodes:', CLUSTER_NODES.length); // Rebuild indexes and redraw keeping viewport buildSearchIndex(); if (mode === 'cluster') {{ loadCluster(); }} else if (mode === 'drill') {{ if (COMMUNITY_DATA[drillCid]) {{ loadDrill(drillCid); }} else {{ loadCluster(); }} }} showLiveSyncNotification(); }} catch (err) {{ console.error('[Live Sync] Failed to fetch latest graph data:', err); }} }} function showLiveSyncNotification() {{ let toast = document.getElementById('live-sync-toast'); if (!toast) {{ toast = document.createElement('div'); toast.id = 'live-sync-toast'; toast.style.cssText = 'position:fixed;bottom:20px;right:20px;background:#10b981;color:#fff;padding:10px 20px;border-radius:8px;font-family:sans-serif;font-size:12px;font-weight:bold;box-shadow:0 4px 12px rgba(0,0,0,0.3);z-index:9999;transition:opacity 0.5s;opacity:0;pointer-events:none;'; document.body.appendChild(toast); }} toast.textContent = '⚑ Codebase Graph Synchronized!'; toast.style.opacity = '1'; setTimeout(() => {{ toast.style.opacity = '0'; }}, 2500); }} setupWebSocketSync(); </script> </html>""" with open(cfg["out"], "w") as f: f.write(html) # Write data JSON too for live updates try: json_out = cfg["out"].replace(".html", ".json") with open(json_out, "w", encoding="utf-8") as f_json: json.dump({ "cluster_nodes": cluster_nodes, "cluster_edges": cluster_edges, "community_data": community_data, "stats": stats_str }, f_json) print(f"[{scope}] Written layout data to {json_out}") except Exception as je: print(f"[{scope}] Error writing layout data: {je}") size = os.path.getsize(cfg["out"]) print(f"[{scope}] Written {cfg['out']} ({size/1024:.0f} KB)") return cfg["out"] if __name__ == "__main__": scopes = sys.argv[1:] or ["studiq", "root"] for scope in scopes: if scope in SCOPE_CONFIGS: build_fast_html(scope) else: print(f"Unknown scope: {scope}")
#!/usr/bin/env python3
"""
Generate a fast, cluster-first graph viewer from graphify graph.json.
Uses Canvas2D with viewport culling, squared distance tests, and batched stroke drawing.
"""
import json
import math
import random
import sys
import os
from collections import defaultdict, Counter
random.seed(42)
SCOPE_CONFIGS = {
"studiq": {
"json": "/Users/baljotchohan/Projects/StudIQ/studiq/graphify-out/graph.json",
"out": "/Users/baljotchohan/Projects/StudIQ/studiq/graphify-out/graph_fast.html",
"title": "StudIQ Codebase Graph",
},
"root": {
"json": "/Users/baljotchohan/Projects/StudIQ/graphify-out/graph.json",
"out": "/Users/baljotchohan/Projects/StudIQ/graphify-out/graph_fast.html",
"title": "StudIQ Root Graph",
}
}
COLORS = [
"#00f2fe", "#b224ef", "#ff007f", "#39ff14", "#ff00ff",
"#00ffff", "#ffb703", "#fb8500", "#ff006e", "#8338ec",
"#3a86c8", "#ffbe0b", "#4895ef", "#4cc9f0", "#7209b7",
"#f72585", "#3f37c9", "#3b28cc", "#a900ff", "#00bbf9",
]
def spiral_layout(communities):
"""Place communities in a tight spiral layout."""
comms = sorted(communities.items(), key=lambda x: -len(x[1]))
positions = {}
golden = (1 + math.sqrt(5)) / 2
for i, (cid, nodes) in enumerate(comms):
r = math.sqrt(i + 1) * 160
theta = 2 * math.pi * i / (golden ** 2)
positions[cid] = (r * math.cos(theta), r * math.sin(theta))
return positions
def build_fast_html(scope: str):
cfg = SCOPE_CONFIGS[scope]
print(f"[{scope}] Reading {cfg['json']}...")
with open(cfg["json"]) as f:
data = json.load(f)
raw_nodes = data["nodes"]
raw_links = data["links"]
target_dir = "/Users/baljotchohan/Projects/StudIQ" if scope == "root" else "/Users/baljotchohan/Projects/StudIQ/studiq"
# Determine top-level folder prefix for each node
node_folder = {}
for n in raw_nodes:
sf = n.get("source_file", "")
sf = sf.replace("\\", "/")
folder = "root"
if sf.startswith(target_dir):
rel = sf[len(target_dir):].lstrip("/")
parts = rel.split("/")
if parts and parts[0]:
folder = parts[0]
node_folder[n["id"]] = folder
# Re-map small communities (size < min_size) to folder-specific misc communities
min_size = 15 if scope == "root" else 6
orig_comm_sizes = Counter(n.get("community", 0) for n in raw_nodes)
for n in raw_nodes:
cid = n.get("community", 0)
if orig_comm_sizes[cid] < min_size:
folder = node_folder.get(n["id"], "other")
n["community"] = f"misc_{folder}"
# Build community structure
comm_nodes = defaultdict(list)
node_by_id = {}
for n in raw_nodes:
cid = n["community"]
comm_nodes[cid].append(n)
node_by_id[n["id"]] = n
# Assign colors to communities
comm_hex = {}
comm_rgb = {}
comm_list = sorted(comm_nodes.keys(), key=lambda x: str(x))
for i, cid in enumerate(comm_list):
hex_color = COLORS[i % len(COLORS)]
comm_hex[cid] = hex_color
# Parse hex to rgb string for Canvas usage
r_val = int(hex_color[1:3], 16)
g_val = int(hex_color[3:5], 16)