#5052 Knowledge Graph HTML/CSS/JS Application for Systems Decomposition
#5052 Knowledge Graph HTML/CSS/JS Application for Systems Decomposition
#5052 Create an HTML/CSS/JS application displaying a knowledge graph based on a user-specified system, where subsystems, components and parts are nodes with links to online information about each
I will now build the interactive System Knowledge Graph Explorer web application in a single HTML file, featuring D3.js visualizations (Force-Directed, Hierarchical Tree, and Radial Tree), 4 pre-loaded engineering presets, Gemini API dynamic system decomposition, an interactive Node Inspector with online reference links, and full node editing plus JSON export/import.
I have created the System Knowledge Graph Explorer (knowledge_graph.html) with the following features:
Dynamic System Generation & Presets: Enter any system (such as Mars Rover, Mechanical Watch, or Nuclear Reactor) to decompose it via the Gemini API into a 4-tier hierarchy (System → Subsystems → Components → Parts), or explore 4 pre-loaded engineering presets (Electric Vehicle, Commercial Jet Engine, Smartphone, Espresso Machine).
Interactive D3.js Graph: Switch seamlessly between Force-Directed, Hierarchical Tree, and Radial Tree layouts with smooth pan/zoom, draggable nodes, hover lineage highlighting, double-click collapse/expand, live node search, and tier visibility filters.
Node Inspector & Online Information: Click any node to open the right-hand drawer displaying clickable breadcrumbs, technical overview, key function, direct external links (Wikipedia, Google Scholar, HowStuffWorks/Technical Search, plus custom URLs), child navigation, and Add / Edit / Delete node controls.
JSON Export & Import: Save your custom or generated knowledge graphs to JSON and re-import them anytime.
I have rebuilt knowledge_graph.html to fix the Generate Graph issue and make the API key behavior completely transparent:
API Key & Engine Status Pill + Settings Modal: By default, the app uses
const apiKey = ""(relying on the preview environment's injected key, with no hardcoded key). Clicking the Engine: Auto (Gemini/Wiki) pill in the header lets you paste your own Gemini API key (saved inlocalStorage), pick a model (gemini-2.5-flashby default, plusgemini-3-flash-preview,gemini-3.5-flash-lite, orgemini-3.6-flash), switch modes (Auto, Live Wikipedia Only, or Gemini AI Only), and click Test Connection to see the exact HTTP status.Bulletproof 3-Stage Generation Pipeline: Pressing Generate Graph (or Enter) uses a 12-second
AbortControllertimeout andtry / catch / finallyso it never hangs. In Auto mode it tries Gemini AI first, automatically falls back to the Live English Wikipedia API (no API key needed) to build a real 4-tier hierarchy from article sections and links, and finally falls back to a local engineering blueprint if offline.Clean D3.js Re-rendering: Every new graph, preset, or JSON import stops the active simulation, resets search/tier filters, clears and re-renders the SVG, auto-fits the view, and opens the Node Inspector on the new root node.
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>System Knowledge Graph Explorer</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- D3.js v7 -->
<script src="https://d3js.org/d3.v7.min.js"></script>
<!-- Google Fonts: Inter & JetBrains Mono -->
<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=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" />
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
mono: ['JetBrains Mono', 'monospace'],
},
colors: {
slatebg: '#090d16',
panel: 'rgba(15, 23, 42, 0.82)',
}
}
}
};
</script>
<style>
* {
box-sizing: border-box;
}
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: #090d16;
color: #e2e8f0;
font-family: 'Inter', sans-serif;
}
/* Engineering Dot-Grid Background */
.dot-grid {
background-color: #090d16;
background-image: radial-gradient(rgba(148, 163, 184, 0.16) 1px, transparent 1px);
background-size: 24px 24px;
}
/* Glassmorphism utility */
.glass {
background: rgba(15, 23, 42, 0.78);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
border: 1px solid rgba(148, 163, 184, 0.16);
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: rgba(15, 23, 42, 0.4);
}
::-webkit-scrollbar-thumb {
background: rgba(100, 116, 139, 0.45);
border-radius: 9999px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(148, 163, 184, 0.65);
}
/* SVG Graph Transitions & Styles */
#graph-svg {
width: 100%;
height: 100%;
cursor: grab;
user-select: none;
touch-action: none;
}
#graph-svg:active {
cursor: grabbing;
}
.node-group {
cursor: pointer;
transition: opacity 0.22s ease;
}
.node-group.dimmed {
opacity: 0.16;
}
.node-circle {
transition: r 0.2s ease, stroke-width 0.2s ease, filter 0.2s ease;
}
.node-label {
pointer-events: none;
text-shadow: 0 2px 6px rgba(9, 13, 22, 0.95), 0 0 2px rgba(9, 13, 22, 0.95);
transition: opacity 0.22s ease, font-weight 0.2s ease;
}
.link-path {
fill: none;
transition: opacity 0.22s ease, stroke 0.22s ease, stroke-width 0.22s ease;
}
.link-path.dimmed {
opacity: 0.08;
}
.link-path.highlighted {
opacity: 0.95 !important;
stroke-width: 2.5px !important;
}
/* Pulse animation for selected node ring */
@keyframes pulseRing {
0% { transform: scale(1); opacity: 0.85; }
70% { transform: scale(1.45); opacity: 0; }
100% { transform: scale(1.45); opacity: 0; }
}
.selected-pulse {
transform-box: fill-box;
transform-origin: center;
animation: pulseRing 2s cubic-bezier(0.215, 0.61, 0.355, 1) infinite;
}
/* Spinner animation */
@keyframes spinSlow {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spin-slow {
animation: spinSlow 2.4s linear infinite;
}
</style>
</head>
<body class="dot-grid flex flex-col h-screen w-screen overflow-hidden select-none">
<!-- ==================== TOP NAVIGATION BAR ==================== -->
<header class="glass z-30 w-full px-3 sm:px-5 py-2.5 flex flex-wrap items-center justify-between gap-2.5 border-b border-slate-700/50 shrink-0">
<!-- Brand & Title -->
<div class="flex items-center gap-2.5">
<div class="w-9 h-9 rounded-xl bg-gradient-to-br from-amber-400 via-cyan-400 to-violet-500 p-[1.5px] shadow-lg shadow-cyan-500/20 shrink-0">
<div class="w-full h-full bg-slate-950 rounded-[10px] flex items-center justify-center">
<svg class="w-5 h-5 text-cyan-400" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="5" r="2.5"></circle>
<circle cx="5" cy="18" r="2.5"></circle>
<circle cx="19" cy="18" r="2.5"></circle>
<line x1="12" y1="7.5" x2="6.2" y2="15.8"></line>
<line x1="12" y1="7.5" x2="17.8" y2="15.8"></line>
<line x1="7.5" y1="18" x2="16.5" y2="18"></line>
</svg>
</div>
</div>
<div class="leading-tight">
<h1 class="text-sm sm:text-base font-bold tracking-tight text-white flex items-center gap-1.5">
SysGraph
<span class="hidden md:inline-block text-[10px] font-mono uppercase tracking-wider px-1.5 py-0.5 rounded bg-cyan-500/15 text-cyan-300 border border-cyan-500/30">Knowledge Graph</span>
</h1>
<p class="text-[11px] text-slate-400 hidden sm:block">System Decomposition & Reference Explorer</p>
</div>
</div>
<!-- System Generator Input Bar -->
<form id="generate-form" class="flex-1 max-w-xl flex items-center gap-2 min-w-[240px]">
<div class="relative flex-1">
<svg class="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="8"></circle>
<path d="m21 21-4.3-4.3"></path>
</svg>
<input
id="system-input"
type="text"
placeholder="Enter any system (e.g., Mars Rover, Mechanical Watch, Nuclear Reactor)..."
class="w-full bg-slate-900/90 border border-slate-700/80 hover:border-slate-600 focus:border-cyan-400 focus:ring-2 focus:ring-cyan-400/20 rounded-xl pl-9 pr-3 py-2 text-xs sm:text-sm text-slate-100 placeholder-slate-400 outline-none transition"
/>
</div>
<button
type="submit"
id="generate-btn"
class="px-3.5 py-2 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-600 hover:from-cyan-400 hover:to-blue-500 text-white text-xs sm:text-sm font-semibold shadow-lg shadow-cyan-500/25 flex items-center gap-1.5 transition active:scale-95 shrink-0 cursor-pointer"
>
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 3v3m0 12v3M3 12h3m12 0h3M5.6 5.6l2.1 2.1m8.6 8.6 2.1 2.1M5.6 18.4l2.1-2.1m8.6-8.6 2.1-2.1"/>
</svg>
<span>Generate Graph</span>
</button>
</form>
<!-- Presets & Import/Export Actions -->
<div class="flex items-center gap-2">
<select
id="preset-select"
aria-label="Select preset system"
class="bg-slate-900/90 border border-slate-700/80 hover:border-slate-600 rounded-xl px-2.5 py-2 text-xs text-slate-200 outline-none focus:border-cyan-400 cursor-pointer"
>
<option value="ev">Preset: Electric Vehicle</option>
<option value="jet">Preset: Commercial Jet Engine</option>
<option value="smartphone">Preset: Smartphone</option>
<option value="espresso">Preset: Espresso Machine</option>
</select>
<button
id="btn-export"
title="Export Graph as JSON"
class="p-2 rounded-xl bg-slate-800/80 hover:bg-slate-700/80 border border-slate-700 text-slate-300 hover:text-white transition cursor-pointer"
>
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" y1="15" x2="12" y2="3"></line>
</svg>
</button>
<button
id="btn-import"
title="Import Graph from JSON"
class="p-2 rounded-xl bg-slate-800/80 hover:bg-slate-700/80 border border-slate-700 text-slate-300 hover:text-white transition cursor-pointer"
>
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="17 8 12 3 7 8"></polyline>
<line x1="12" y1="3" x2="12" y2="15"></line>
</svg>
</button>
</div>
</header>
<!-- ==================== MAIN WORKSPACE ==================== -->
<main class="relative flex-1 w-full overflow-hidden">
<!-- Interactive D3 Graph SVG -->
<svg id="graph-svg" class="w-full h-full block"></svg>
<!-- FLOATING TOP-LEFT: Node Search & Tier Filters -->
<div class="absolute top-3 left-3 z-20 flex flex-col gap-2 max-w-[270px] sm:max-w-xs pointer-events-auto">
<div class="glass rounded-2xl p-2.5 shadow-xl space-y-2">
<!-- Live Node Search -->
<div class="relative">
<svg class="w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-1/2 -translate-y-1/2 pointer-events-none" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="8"></circle>
<path d="m21 21-4.3-4.3"></path>
</svg>
<input
id="node-search-input"
type="text"
placeholder="Filter or find node..."
class="w-full bg-slate-950/70 border border-slate-700/70 focus:border-cyan-400 rounded-xl pl-8 pr-7 py-1.5 text-xs text-slate-100 placeholder-slate-400 outline-none transition"
/>
<button id="clear-search-btn" class="hidden absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white">
<svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
<!-- Search Results Dropdown -->
<div id="search-results" class="hidden max-h-40 overflow-y-auto space-y-1 pt-1 border-t border-slate-700/60"></div>
<!-- Tier Visibility Toggles -->
<div class="flex flex-wrap items-center gap-1.5 pt-0.5">
<button data-tier="0" class="tier-filter-btn active flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-medium bg-amber-500/15 text-amber-300 border border-amber-500/40 transition cursor-pointer">
<span class="w-2 h-2 rounded-full bg-amber-400"></span> System
</button>
<button data-tier="1" class="tier-filter-btn active flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-medium bg-cyan-500/15 text-cyan-300 border border-cyan-500/40 transition cursor-pointer">
<span class="w-2 h-2 rounded-full bg-cyan-400"></span> Subsystem
</button>
<button data-tier="2" class="tier-filter-btn active flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-medium bg-emerald-500/15 text-emerald-300 border border-emerald-500/40 transition cursor-pointer">
<span class="w-2 h-2 rounded-full bg-emerald-400"></span> Component
</button>
<button data-tier="3" class="tier-filter-btn active flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-medium bg-violet-500/15 text-violet-300 border border-violet-500/40 transition cursor-pointer">
<span class="w-2 h-2 rounded-full bg-violet-400"></span> Part
</button>
</div>
</div>
<!-- Stats Pill -->
<div class="glass rounded-xl px-3 py-1.5 text-[11px] text-slate-300 flex items-center justify-between gap-3 w-fit shadow-lg">
<span id="graph-stats">0 nodes</span>
<span class="text-slate-600">|</span>
<span class="text-slate-400">Double-click node to collapse</span>
</div>
</div>
<!-- FLOATING BOTTOM-LEFT: Layout Switcher & Zoom Controls -->
<div class="absolute bottom-4 left-3 z-20 flex flex-wrap items-center gap-2 pointer-events-auto">
<!-- Layout Switcher -->
<div class="glass rounded-2xl p-1 flex items-center gap-1 shadow-xl">
<button data-layout="force" class="layout-btn px-2.5 py-1.5 rounded-xl text-xs font-medium bg-cyan-500/20 text-cyan-300 border border-cyan-500/40 transition cursor-pointer">
Force
</button>
<button data-layout="tree" class="layout-btn px-2.5 py-1.5 rounded-xl text-xs font-medium text-slate-400 hover:text-white border border-transparent transition cursor-pointer">
Tree
</button>
<button data-layout="radial" class="layout-btn px-2.5 py-1.5 rounded-xl text-xs font-medium text-slate-400 hover:text-white border border-transparent transition cursor-pointer">
Radial
</button>
</div>
<!-- Zoom & Fit Controls -->
<div class="glass rounded-2xl p-1 flex items-center gap-1 shadow-xl">
<button id="zoom-in" title="Zoom In" class="p-1.5 rounded-xl text-slate-300 hover:text-white hover:bg-slate-700/60 transition cursor-pointer">
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>
</button>
<button id="zoom-out" title="Zoom Out" class="p-1.5 rounded-xl text-slate-300 hover:text-white hover:bg-slate-700/60 transition cursor-pointer">
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="8" y1="11" x2="14" y2="11"/></svg>
</button>
<button id="zoom-fit" title="Fit Graph to Screen" class="px-2 py-1.5 rounded-xl text-xs font-medium text-slate-300 hover:text-white hover:bg-slate-700/60 transition cursor-pointer">
Fit
</button>
<button id="expand-all" title="Expand All Nodes" class="px-2 py-1.5 rounded-xl text-xs font-medium text-slate-300 hover:text-white hover:bg-slate-700/60 transition cursor-pointer">
Expand All
</button>
</div>
</div>
<!-- ==================== RIGHT-HAND INSPECTOR DRAWER ==================== -->
<aside
id="inspector-drawer"
class="glass fixed sm:absolute top-0 right-0 h-full w-full sm:w-[370px] md:w-[400px] z-30 transform translate-x-full transition-transform duration-300 ease-out flex flex-col border-l border-slate-700/60 shadow-2xl"
>
<!-- Inspector Header -->
<div class="px-5 py-4 border-b border-slate-700/60 flex items-start justify-between gap-3 shrink-0">
<div class="min-w-0">
<div id="inspector-breadcrumbs" class="flex flex-wrap items-center gap-1 text-[11px] text-slate-400 mb-1.5"></div>
<div class="flex items-center gap-2 flex-wrap">
<h2 id="inspector-title" class="text-lg font-bold text-white leading-snug break-words">Node Name</h2>
<span id="inspector-tier-badge" class="text-[10px] font-mono uppercase tracking-wider px-2 py-0.5 rounded-full border">Tier</span>
</div>
</div>
<button id="close-inspector" title="Close Inspector" class="p-1.5 rounded-xl text-slate-400 hover:text-white hover:bg-slate-800 transition cursor-pointer shrink-0">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
<!-- Inspector Scrollable Body -->
<div class="flex-1 overflow-y-auto px-5 py-4 space-y-5 select-text">
<!-- Technical Description -->
<div>
<h3 class="text-[11px] font-mono uppercase tracking-wider text-slate-400 mb-1.5">Technical Overview</h3>
<p id="inspector-desc" class="text-sm text-slate-200 leading-relaxed bg-slate-900/60 border border-slate-800 rounded-xl p-3"></p>
</div>
<!-- Key Function -->
<div id="inspector-func-wrap">
<h3 class="text-[11px] font-mono uppercase tracking-wider text-slate-400 mb-1.5">Key Function</h3>
<p id="inspector-func" class="text-xs text-cyan-200/90 leading-relaxed bg-cyan-950/30 border border-cyan-500/20 rounded-xl p-3"></p>
</div>
<!-- Online Information Links -->
<div>
<h3 class="text-[11px] font-mono uppercase tracking-wider text-slate-400 mb-2 flex items-center gap-1.5">
<svg class="w-3.5 h-3.5 text-cyan-400" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
Online Information
</h3>
<div id="inspector-links" class="space-y-2"></div>
</div>
<!-- Child Nodes List -->
<div>
<div class="flex items-center justify-between mb-2">
<h3 id="inspector-children-heading" class="text-[11px] font-mono uppercase tracking-wider text-slate-400">Child Nodes</h3>
<button id="inspector-toggle-collapse" class="hidden text-[11px] text-cyan-400 hover:text-cyan-300 font-medium cursor-pointer">
Collapse Children
</button>
</div>
<div id="inspector-children" class="space-y-1.5"></div>
</div>
</div>
<!-- Inspector Footer Actions -->
<div class="px-5 py-3.5 border-t border-slate-700/60 bg-slate-950/60 flex items-center gap-2 shrink-0">
<button id="btn-add-child" class="flex-1 py-2 px-3 rounded-xl bg-cyan-500/20 hover:bg-cyan-500/30 border border-cyan-500/40 text-cyan-200 text-xs font-semibold flex items-center justify-center gap-1.5 transition cursor-pointer">
<svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
Add Child
</button>
<button id="btn-edit-node" class="py-2 px-3 rounded-xl bg-slate-800 hover:bg-slate-700 border border-slate-700 text-slate-200 text-xs font-medium transition cursor-pointer">
Edit
</button>
<button id="btn-delete-node" class="py-2 px-3 rounded-xl bg-rose-500/15 hover:bg-rose-500/25 border border-rose-500/35 text-rose-300 text-xs font-medium transition cursor-pointer">
Delete
</button>
</div>
</aside>
<!-- ==================== LOADING OVERLAY ==================== -->
<div id="loading-overlay" class="hidden absolute inset-0 z-40 bg-slate-950/80 backdrop-blur-md flex flex-col items-center justify-center p-6 text-center">
<div class="relative w-16 h-16 mb-4">
<div class="absolute inset-0 rounded-full border-2 border-cyan-500/20"></div>
<div class="absolute inset-0 rounded-full border-2 border-t-cyan-400 border-r-violet-400 border-b-transparent border-l-transparent spin-slow"></div>
<div class="absolute inset-3 rounded-full bg-cyan-500/15 flex items-center justify-center">
<svg class="w-5 h-5 text-cyan-300" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="5" r="2"></circle><circle cx="5" cy="19" r="2"></circle><circle cx="19" cy="19" r="2"></circle>
<line x1="12" y1="7" x2="6" y2="17"></line><line x1="12" y1="7" x2="18" y2="17"></line>
</svg>
</div>
</div>
<h3 id="loading-title" class="text-base font-semibold text-white mb-1">Decomposing System Architecture...</h3>
<p id="loading-sub" class="text-xs text-slate-400 max-w-sm">Querying Gemini to map Subsystems, Components, Parts, and online references.</p>
</div>
</main>
<!-- ==================== MODAL: ADD / EDIT NODE ==================== -->
<div id="node-modal" class="hidden fixed inset-0 z-50 bg-slate-950/75 backdrop-blur-sm flex items-center justify-center p-4">
<div class="glass rounded-2xl w-full max-w-md p-5 shadow-2xl border border-slate-700/80">
<div class="flex items-center justify-between mb-4">
<h3 id="modal-title" class="text-base font-bold text-white">Add Child Node</h3>
<button id="close-node-modal" class="text-slate-400 hover:text-white p-1 cursor-pointer">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
<form id="node-form" class="space-y-3.5">
<div>
<label class="block text-xs font-medium text-slate-300 mb-1">Node Name *</label>
<input id="form-name" type="text" required placeholder="e.g., Inverter Module" class="w-full bg-slate-900 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white outline-none focus:border-cyan-400" />
</div>
<div>
<label class="block text-xs font-medium text-slate-300 mb-1">Tier</label>
<select id="form-tier" class="w-full bg-slate-900 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white outline-none focus:border-cyan-400">
<option value="0">System (Root)</option>
<option value="1">Subsystem</option>
<option value="2">Component</option>
<option value="3">Part</option>
</select>
</div>
<div>
<label class="block text-xs font-medium text-slate-300 mb-1">Technical Description</label>
<textarea id="form-desc" rows="2" placeholder="Brief technical description..." class="w-full bg-slate-900 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white outline-none focus:border-cyan-400"></textarea>
</div>
<div>
<label class="block text-xs font-medium text-slate-300 mb-1">Key Function</label>
<input id="form-func" type="text" placeholder="Primary role in the system..." class="w-full bg-slate-900 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white outline-none focus:border-cyan-400" />
</div>
<div>
<label class="block text-xs font-medium text-slate-300 mb-1">Wikipedia or Reference URL (optional)</label>
<input id="form-url" type="url" placeholder="https://en.wikipedia.org/wiki/..." class="w-full bg-slate-900 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white outline-none focus:border-cyan-400" />
</div>
<div class="flex justify-end gap-2 pt-2">
<button type="button" id="cancel-node-modal" class="px-4 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium cursor-pointer">Cancel</button>
<button type="submit" class="px-4 py-2 rounded-xl bg-cyan-500 hover:bg-cyan-400 text-slate-950 text-xs font-bold cursor-pointer">Save Node</button>
</div>
</form>
</div>
</div>
<!-- ==================== MODAL: IMPORT JSON ==================== -->
<div id="import-modal" class="hidden fixed inset-0 z-50 bg-slate-950/75 backdrop-blur-sm flex items-center justify-center p-4">
<div class="glass rounded-2xl w-full max-w-lg p-5 shadow-2xl border border-slate-700/80">
<div class="flex items-center justify-between mb-3">
<h3 class="text-base font-bold text-white">Import Knowledge Graph JSON</h3>
<button id="close-import-modal" class="text-slate-400 hover:text-white p-1 cursor-pointer">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
<p class="text-xs text-slate-400 mb-3">Paste a previously exported JSON graph or upload a <code>.json</code> file.</p>
<input id="import-file-input" type="file" accept=".json,application/json" class="block w-full text-xs text-slate-300 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-cyan-500/20 file:text-cyan-300 hover:file:bg-cyan-500/30 mb-3 cursor-pointer" />
<textarea id="import-json-text" rows="7" placeholder='{"id":"root","name":"My System","tier":0,"children":[...]}' class="w-full font-mono text-xs bg-slate-900 border border-slate-700 rounded-xl p-3 text-slate-200 outline-none focus:border-cyan-400"></textarea>
<div class="flex justify-end gap-2 pt-3">
<button id="cancel-import-modal" class="px-4 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium cursor-pointer">Cancel</button>
<button id="confirm-import-btn" class="px-4 py-2 rounded-xl bg-cyan-500 hover:bg-cyan-400 text-slate-950 text-xs font-bold cursor-pointer">Load Graph</button>
</div>
</div>
</div>
<!-- ==================== TOAST NOTIFICATION ==================== -->
<div id="toast" class="fixed bottom-5 right-5 z-50 transform translate-y-20 opacity-0 transition-all duration-300 pointer-events-none">
<div class="glass rounded-xl px-4 py-2.5 shadow-2xl border border-cyan-500/30 flex items-center gap-2 text-xs font-medium text-white">
<span id="toast-dot" class="w-2 h-2 rounded-full bg-cyan-400"></span>
<span id="toast-msg">Notification</span>
</div>
</div>
<!-- ==================== APPLICATION SCRIPT ==================== -->
<script>
// =========================================================================
// 1. CONFIGURATION & TIER METADATA
// =========================================================================
const TIER_META = [
{ label: 'System', color: '#f59e0b', stroke: '#fde68a', radius: 24, badgeClass: 'bg-amber-500/15 text-amber-300 border-amber-500/40' },
{ label: 'Subsystem', color: '#06b6d4', stroke: '#a5f3fc', radius: 17, badgeClass: 'bg-cyan-500/15 text-cyan-300 border-cyan-500/40' },
{ label: 'Component', color: '#10b981', stroke: '#a7f3d0', radius: 12, badgeClass: 'bg-emerald-500/15 text-emerald-300 border-emerald-500/40' },
{ label: 'Part', color: '#8b5cf6', stroke: '#ddd6fe', radius: 8.5, badgeClass: 'bg-violet-500/15 text-violet-300 border-violet-500/40' }
];
// =========================================================================
// 2. PRE-LOADED ENGINEERING PRESETS (4 Rich Systems)
// =========================================================================
const PRESETS = {
ev: {
id: 'ev-root',
name: 'Electric Vehicle',
tier: 0,
description: 'A battery-powered road vehicle propelled by one or more electric traction motors using electrical energy stored in rechargeable lithium-ion battery packs.',
keyFunction: 'Zero-tailpipe-emission personal or commercial transportation with high drivetrain efficiency and regenerative braking.',
wikiUrl: 'https://en.wikipedia.org/wiki/Electric_vehicle',
children: [
{
id: 'ev-powertrain',
name: 'Electric Powertrain',
tier: 1,
description: 'Converts stored DC electrical energy into mechanical torque delivered to the wheels and recovers kinetic energy during deceleration.',
keyFunction: 'Propulsion, torque vectoring, and regenerative energy recovery.',
wikiUrl: 'https://en.wikipedia.org/wiki/Electric_vehicle_powertrain',
children: [
{
id: 'ev-motor',
name: 'Traction Motor',
tier: 2,
description: 'Permanent magnet synchronous motor (PMSM) or AC induction motor that generates rotational torque from three-phase alternating current.',
keyFunction: 'Electromechanical energy conversion for propulsion and regeneration.',
wikiUrl: 'https://en.wikipedia.org/wiki/Traction_motor',
children: [
{ id: 'ev-stator', name: 'Copper Stator Winding', tier: 3, description: 'Stationary laminated steel core wound with insulated copper coils that generate a rotating magnetic field.', keyFunction: 'Produces rotating electromagnetic flux.', wikiUrl: 'https://en.wikipedia.org/wiki/Stator', children: [] },
{ id: 'ev-rotor', name: 'Permanent Magnet Rotor', tier: 3, description: 'Rotating assembly embedded with neodymium-iron-boron magnets locked to the stator field.', keyFunction: 'Transfers magnetic force into shaft torque.', wikiUrl: 'https://en.wikipedia.org/wiki/Rotor_(electric)', children: [] }
]
},
{
id: 'ev-inverter',
name: 'Power Inverter',
tier: 2,
description: 'High-voltage power electronics unit that converts battery DC power into variable-frequency three-phase AC power.',
keyFunction: 'Controls motor speed, torque, and regenerative charging current.',
wikiUrl: 'https://en.wikipedia.org/wiki/Power_inverter',
children: [
{ id: 'ev-sic', name: 'SiC MOSFET Modules', tier: 3, description: 'Silicon carbide semiconductor switches capable of high-frequency, low-loss power switching.', keyFunction: 'High-efficiency DC-to-AC switching.', wikiUrl: 'https://en.wikipedia.org/wiki/Silicon_carbide', children: [] },
{ id: 'ev-dclink', name: 'DC-Link Capacitor', tier: 3, description: 'High-voltage film capacitor bank that smooths voltage ripple between the battery and inverter switches.', keyFunction: 'Stabilizes DC bus voltage.', wikiUrl: 'https://en.wikipedia.org/wiki/Film_capacitor', children: [] }
]
},
{
id: 'ev-gearbox',
name: 'Single-Speed Reduction Gearbox',
tier: 2,
description: 'Fixed-ratio helical gear set and differential that steps down high motor RPM to usable wheel torque.',
keyFunction: 'Multiplies motor torque and splits power between drive wheels.',
wikiUrl: 'https://en.wikipedia.org/wiki/Differential_(mechanical_device)',
children: [
{ id: 'ev-helical', name: 'Helical Reduction Gears', tier: 3, description: 'Precision-ground angled-tooth gears designed for quiet, high-RPM operation.', keyFunction: 'Provides ~9:1 torque multiplication.', wikiUrl: 'https://en.wikipedia.org/wiki/Gear#Helical', children: [] },
{ id: 'ev-halfshaft', name: 'CV Half-Shafts', tier: 3, description: 'Constant-velocity axle shafts connecting the differential to the wheel hubs.', keyFunction: 'Transmits torque through suspension travel.', wikiUrl: 'https://en.wikipedia.org/wiki/Constant-velocity_joint', children: [] }
]
}
]
},
{
id: 'ev-battery',
name: 'High-Voltage Battery System',
tier: 1,
description: 'Underfloor structural energy storage pack housing thousands of lithium-ion cells, monitoring electronics, and safety contactors.',
keyFunction: 'Stores and safely delivers 400V–800V DC electrical energy.',
wikiUrl: 'https://en.wikipedia.org/wiki/Electric_vehicle_battery',
children: [
{
id: 'ev-cells',
name: 'Lithium-Ion Cell Modules',
tier: 2,
description: 'Series-parallel arrays of cylindrical, prismatic, or pouch electrochemical cells (NMC or LFP chemistry).',
keyFunction: 'Electrochemical energy storage.',
wikiUrl: 'https://en.wikipedia.org/wiki/Lithium-ion_battery',
children: [
{ id: 'ev-cathode', name: 'NMC/LFP Cathode', tier: 3, description: 'Positive electrode material that determines energy density and thermal stability.', keyFunction: 'Hosts lithium ions during discharge.', wikiUrl: 'https://en.wikipedia.org/wiki/Lithium_nickel_manganese_cobalt_oxides', children: [] },
{ id: 'ev-separator', name: 'Microporous Separator', tier: 3, description: 'Thin polymer membrane preventing internal short circuits while permitting ion transport.', keyFunction: 'Electrically isolates anode and cathode.', wikiUrl: 'https://en.wikipedia.org/wiki/Separator_(electricity)', children: [] }
]
},
{
id: 'ev-bms',
name: 'Battery Management System (BMS)',
tier: 2,
description: 'Embedded controller monitoring cell voltages, pack temperatures, state-of-charge (SoC), and insulation resistance.',
keyFunction: 'Protects cells from overcharge, over-discharge, and thermal runaway.',
wikiUrl: 'https://en.wikipedia.org/wiki/Battery_management_system',
children: [
{ id: 'ev-contactor', name: 'HV Pyro-Fuse & Contactors', tier: 3, description: 'Electromechanical relays and pyrotechnic disconnect switches that isolate the battery in a crash.', keyFunction: 'Emergency high-voltage isolation.', wikiUrl: 'https://en.wikipedia.org/wiki/Contactor', children: [] },
{ id: 'ev-shunt', name: 'Current Shunt Sensor', tier: 3, description: 'Precision low-resistance sensor measuring real-time pack amperage.', keyFunction: 'Tracks coulomb counting and power draw.', wikiUrl: 'https://en.wikipedia.org/wiki/Shunt_(electrical)', children: [] }
]
}
]
},
{
id: 'ev-thermal',
name: 'Thermal Management System',
tier: 1,
description: 'Integrated liquid cooling and heat-pump network maintaining optimal operating temperatures for the battery, motor, inverter, and cabin.',
keyFunction: 'Prevents overheating during fast charging and maximizes winter range.',
wikiUrl: 'https://en.wikipedia.org/wiki/Heat_pump',
children: [
{
id: 'ev-heatpump',
name: 'Cabin & Battery Heat Pump',
tier: 2,
description: 'Reversible vapor-compression cycle that scavenges waste heat from the powertrain to warm the cabin and battery.',
keyFunction: 'High-efficiency thermal transfer.',
wikiUrl: 'https://en.wikipedia.org/wiki/Vapor-compression_refrigeration',
children: [
{ id: 'ev-compressor', name: 'Electric Scroll Compressor', tier: 3, description: 'High-voltage variable-speed refrigerant compressor.', keyFunction: 'Pressurizes refrigerant loop.', wikiUrl: 'https://en.wikipedia.org/wiki/Scroll_compressor', children: [] },
{ id: 'ev-octovalve', name: 'Multi-Way Coolant Valve', tier: 3, description: 'Electronically actuated manifold routing glycol coolant between loops.', keyFunction: 'Dynamically directs thermal flow.', wikiUrl: 'https://en.wikipedia.org/wiki/Control_valves', children: [] }
]
},
{
id: 'ev-coldplate',
name: 'Battery Cold Plates',
tier: 2,
description: 'Brazed aluminum heat exchangers in direct thermal contact with battery cells.',
keyFunction: 'Extracts heat uniformly across the battery pack.',
wikiUrl: 'https://en.wikipedia.org/wiki/Heat_exchanger',
children: [
{ id: 'ev-tim', name: 'Thermal Interface Material', tier: 3, description: 'Thermally conductive gap-filler paste bridging cells to cooling channels.', keyFunction: 'Minimizes thermal contact resistance.', wikiUrl: 'https://en.wikipedia.org/wiki/Thermal_interface_material', children: [] }
]
}
]
},
{
id: 'ev-charging',
name: 'Charging & Auxiliary Power',
tier: 1,
description: 'Interfaces with external AC wallboxes and DC fast chargers while stepping down high voltage for 12V/48V vehicle electronics.',
keyFunction: 'Recharges the traction battery and powers low-voltage onboard systems.',
wikiUrl: 'https://en.wikipedia.org/wiki/Charging_station',
children: [
{
id: 'ev-obc',
name: 'Onboard Charger (OBC)',
tier: 2,
description: 'AC-to-DC rectifier converting grid alternating current into regulated DC voltage for the battery.',
keyFunction: 'Enables Level 1 and Level 2 AC charging.',
wikiUrl: 'https://en.wikipedia.org/wiki/Battery_charger',
children: [
{ id: 'ev-port', name: 'NACS / CCS Charge Port', tier: 3, description: 'Standardized high-current connector with pilot communication pins.', keyFunction: 'Physical and digital handshake with charger.', wikiUrl: 'https://en.wikipedia.org/wiki/Combined_Charging_System', children: [] },
{ id: 'ev-dcdc', name: 'DC-DC Converter', tier: 3, description: 'Replaces the traditional alternator by stepping 400V/800V down to 12V/48V.', keyFunction: 'Powers lights, infotainment, and ECUs.', wikiUrl: 'https://en.wikipedia.org/wiki/DC-to-DC_converter', children: [] }
]
}
]
}
]
},
jet: {
id: 'jet-root',
name: 'Commercial Jet Engine',
tier: 0,
description: 'A high-bypass turbofan gas turbine engine that produces thrust by accelerating a large mass of bypass air alongside a high-energy core exhaust.',
keyFunction: 'Generates high-efficiency aerodynamic thrust for commercial airliners.',
wikiUrl: 'https://en.wikipedia.org/wiki/Turbofan',
children: [
{
id: 'jet-fan',
name: 'Fan & Intake Section',
tier: 1,
description: 'Front-mounted large-diameter fan and acoustic nacelle that ingests ambient air and splits it into bypass and core streams.',
keyFunction: 'Produces 75%–85% of total engine thrust via bypass airflow.',
wikiUrl: 'https://en.wikipedia.org/wiki/Nacelle',
children: [
{
id: 'jet-fanblades',
name: 'Wide-Chord Fan Assembly',
tier: 2,
description: 'Swept aerodynamic blades rotating at subsonic/transonic tip speeds.',
keyFunction: 'Accelerates bypass air mass.',
wikiUrl: 'https://en.wikipedia.org/wiki/Turbofan#Fan',
children: [
{ id: 'jet-ti-blade', name: 'Carbon-Titanium Fan Blades', tier: 3, description: 'Composite carbon-fiber blades with titanium leading edges for bird-strike resilience.', keyFunction: 'Lightweight high-strength airfoils.', wikiUrl: 'https://en.wikipedia.org/wiki/Composite_material', children: [] },
{ id: 'jet-spinner', name: 'Aerodynamic Nose Cone', tier: 3, description: 'Conical spinner guiding airflow smoothly into the fan root.', keyFunction: 'Reduces intake drag and ice buildup.', wikiUrl: 'https://en.wikipedia.org/wiki/Spinner_(aeronautics)', children: [] }
]
},
{
id: 'jet-case',
name: 'Fan Containment Case',
tier: 2,
description: 'Reinforced Kevlar-wrapped or titanium casing surrounding the fan disk.',
keyFunction: 'Contains debris in the event of a fan blade-off failure.',
wikiUrl: 'https://en.wikipedia.org/wiki/Jet_engine#Safety',
children: [
{ id: 'jet-liner', name: 'Acoustic Honeycomb Liner', tier: 3, description: 'Perforated sound-absorbing panels lining the intake barrel.', keyFunction: 'Attenuates fan noise.', wikiUrl: 'https://en.wikipedia.org/wiki/Acoustic_liner', children: [] }
]
}
]
},
{
id: 'jet-comp',
name: 'Compressor Section',
tier: 1,
description: 'Multi-stage axial-flow low-pressure (LPC) and high-pressure (HPC) compressors raising core air pressure up to 50:1.',
keyFunction: 'Compresses and heats core air prior to fuel combustion.',
wikiUrl: 'https://en.wikipedia.org/wiki/Axial_compressor',
children: [
{
id: 'jet-hpc',
name: 'High-Pressure Compressor (HPC)',
tier: 2,
description: 'Alternating rows of rotating rotor blades and stationary stator vanes.',
keyFunction: 'Delivers dense, high-pressure air to the combustor.',
wikiUrl: 'https://en.wikipedia.org/wiki/Compressor',
children: [
{ id: 'jet-blisk', name: 'Titanium Blisks', tier: 3, description: 'Integrally bladed disks machined from solid titanium or nickel-alloy forgings.', keyFunction: 'Reduces weight and leakage losses.', wikiUrl: 'https://en.wikipedia.org/wiki/Blisk', children: [] },
{ id: 'jet-vsv', name: 'Variable Stator Vanes', tier: 3, description: 'Actuated guide vanes that adjust angle of attack across RPM ranges.', keyFunction: 'Prevents compressor stall and surge.', wikiUrl: 'https://en.wikipedia.org/wiki/Compressor_stall', children: [] }
]
}
]
},
{
id: 'jet-comb',
name: 'Combustion Chamber',
tier: 1,
description: 'Annular high-temperature chamber where atomized Jet-A fuel mixes with compressed air and burns continuously.',
keyFunction: 'Adds thermal energy to the high-pressure airflow.',
wikiUrl: 'https://en.wikipedia.org/wiki/Combustor',
children: [
{
id: 'jet-injectors',
name: 'Fuel Nozzle Assembly',
tier: 2,
description: 'Ring of swirl-atomizing injectors often manufactured via additive manufacturing.',
keyFunction: 'Atomizes fuel for clean, low-NOx combustion.',
wikiUrl: 'https://en.wikipedia.org/wiki/Fuel_injection',
children: [
{ id: 'jet-igniter', name: 'High-Energy Igniter Plugs', tier: 3, description: 'Spark igniters used during engine startup and inclement weather.', keyFunction: 'Initiates combustion flame.', wikiUrl: 'https://en.wikipedia.org/wiki/Ignition_system', children: [] },
{ id: 'jet-liner-c', name: 'Film-Cooled Combustor Liner', tier: 3, description: 'Ceramic-coated nickel-superalloy walls with laser-drilled cooling holes.', keyFunction: 'Withstands ~2,000°C flame temperatures.', wikiUrl: 'https://en.wikipedia.org/wiki/Thermal_barrier_coating', children: [] }
]
}
]
},
{
id: 'jet-turb',
name: 'Turbine & Exhaust Section',
tier: 1,
description: 'Extracts rotational energy from hot expanding gases to drive the compressor and front fan, then expels residual thrust.',
keyFunction: 'Powers the rotating shafts and accelerates core exhaust.',
wikiUrl: 'https://en.wikipedia.org/wiki/Gas_turbine',
children: [
{
id: 'jet-hpt',
name: 'High-Pressure Turbine (HPT)',
tier: 2,
description: 'Directly downstream of the combustor, operating above the melting point of its own metal.',
keyFunction: 'Drives the high-pressure compressor shaft.',
wikiUrl: 'https://en.wikipedia.org/wiki/Turbine_blade',
children: [
{ id: 'jet-sx-blade', name: 'Single-Crystal Superalloy Blades', tier: 3, description: 'Nickel-based single-crystal blades with internal serpentine air-cooling passages.', keyFunction: 'Resists creep at extreme temperatures.', wikiUrl: 'https://en.wikipedia.org/wiki/Single_crystal', children: [] },
{ id: 'jet-shaft', name: 'Concentric Drive Shafts', tier: 3, description: 'Nested N1 (low-pressure) and N2 (high-pressure) steel alloy shafts.', keyFunction: 'Mechanically links turbines to fan and compressors.', wikiUrl: 'https://en.wikipedia.org/wiki/Drive_shaft', children: [] }
]
},
{
id: 'jet-fadec',
name: 'FADEC Control Unit',
tier: 2,
description: 'Full Authority Digital Engine Control dual-channel computer governing fuel flow and vane schedules.',
keyFunction: 'Optimizes thrust, fuel burn, and safety limits automatically.',
wikiUrl: 'https://en.wikipedia.org/wiki/FADEC',
children: [
{ id: 'jet-egt', name: 'EGT Thermocouple Probes', tier: 3, description: 'High-temperature sensors measuring exhaust gas temperature.', keyFunction: 'Monitors turbine thermal margins.', wikiUrl: 'https://en.wikipedia.org/wiki/Thermocouple', children: [] }
]
}
]
}
]
},
smartphone: {
id: 'sp-root',
name: 'Smartphone',
tier: 0,
description: 'A pocket-sized mobile computing device integrating cellular/wireless radios, multi-touch display, computational cameras, and ARM-based System-on-Chip.',
keyFunction: 'Portable communication, computing, sensing, and multimedia capture.',
wikiUrl: 'https://en.wikipedia.org/wiki/Smartphone',
children: [
{
id: 'sp-compute',
name: 'Compute & Memory Subsystem',
tier: 1,
description: 'Main logic board housing the System-on-Chip (SoC), unified LPDDR RAM, and NVMe flash storage.',
keyFunction: 'Executes the operating system, apps, graphics, and on-device AI.',
wikiUrl: 'https://en.wikipedia.org/wiki/System_on_a_chip',
children: [
{
id: 'sp-soc',
name: 'Mobile SoC Processor',
tier: 2,
description: '3nm/4nm silicon die combining CPU cores, GPU, Neural Processing Unit (NPU), and ISP.',
keyFunction: 'Primary heterogeneous computation.',
wikiUrl: 'https://en.wikipedia.org/wiki/Mobile_processor',
children: [
{ id: 'sp-cpu', name: 'ARM CPU Cores', tier: 3, description: 'Big.LITTLE architecture pairing high-performance and high-efficiency cores.', keyFunction: 'General-purpose instruction execution.', wikiUrl: 'https://en.wikipedia.org/wiki/ARM_architecture_family', children: [] },
{ id: 'sp-npu', name: 'Neural Processing Unit', tier: 3, description: 'Dedicated matrix-multiplication accelerator for machine learning inference.', keyFunction: 'Accelerates AI tasks at low wattage.', wikiUrl: 'https://en.wikipedia.org/wiki/AI_accelerator', children: [] }
]
},
{
id: 'sp-storage',
name: 'UFS / NVMe Flash Storage',
tier: 2,
description: 'Non-volatile 3D NAND flash memory storing the OS, apps, and user media.',
keyFunction: 'High-speed persistent data storage.',
wikiUrl: 'https://en.wikipedia.org/wiki/Flash_memory',
children: [
{ id: 'sp-ram', name: 'LPDDR5X DRAM', tier: 3, description: 'Low-power double data rate volatile memory stacked via Package-on-Package (PoP).', keyFunction: 'Fast active working memory.', wikiUrl: 'https://en.wikipedia.org/wiki/LPDDR', children: [] }
]
}
]
},
{
id: 'sp-display',
name: 'Display & Touch Subsystem',
tier: 1,
description: 'High-refresh-rate LTPO OLED panel bonded with a capacitive multi-touch digitizer and strengthened cover glass.',
keyFunction: 'Visual output and primary human-device touch interaction.',
wikiUrl: 'https://en.wikipedia.org/wiki/OLED',
children: [
{
id: 'sp-oled',
name: 'LTPO AMOLED Panel',
tier: 2,
description: 'Self-emissive organic light-emitting diode matrix with variable 1Hz–120Hz refresh rate.',
keyFunction: 'Renders HDR imagery with true blacks and low power draw.',
wikiUrl: 'https://en.wikipedia.org/wiki/AMOLED',
children: [
{ id: 'sp-glass', name: 'Aluminosilicate Cover Glass', tier: 3, description: 'Ion-exchanged chemically strengthened glass (e.g., Gorilla Glass / Ceramic Shield).', keyFunction: 'Protects display from scratches and drops.', wikiUrl: 'https://en.wikipedia.org/wiki/Gorilla_Glass', children: [] },
{ id: 'sp-digitizer', name: 'Capacitive Touch Grid', tier: 3, description: 'Transparent indium tin oxide (ITO) electrode grid sensing finger capacitance.', keyFunction: 'Tracks multi-touch gestures.', wikiUrl: 'https://en.wikipedia.org/wiki/Touchscreen#Capacitive', children: [] }
]
}
]
},
{
id: 'sp-camera',
name: 'Computational Camera System',
tier: 1,
description: 'Multi-lens optical array (wide, ultrawide, telephoto) paired with CMOS sensors and optical image stabilization.',
keyFunction: 'Captures high-dynamic-range still photos and 4K/8K video.',
wikiUrl: 'https://en.wikipedia.org/wiki/Camera_phone',
children: [
{
id: 'sp-cmos',
name: 'Stacked CMOS Image Sensor',
tier: 2,
description: 'Back-illuminated photodiode array converting photons into digital pixel data.',
keyFunction: 'Light capture and analog-to-digital conversion.',
wikiUrl: 'https://en.wikipedia.org/wiki/Active-pixel_sensor',
children: [
{ id: 'sp-ois', name: 'Voice-Coil OIS Actuator', tier: 3, description: 'Miniature electromagnetic suspension shifting the lens or sensor to counter hand shake.', keyFunction: 'Stabilizes exposure and video.', wikiUrl: 'https://en.wikipedia.org/wiki/Image_stabilization', children: [] },
{ id: 'sp-lens', name: 'Aspheric Multi-Element Lens', tier: 3, description: 'Precision-molded 6-to-8 element lens stack correcting chromatic aberration.', keyFunction: 'Focuses light onto the sensor.', wikiUrl: 'https://en.wikipedia.org/wiki/Aspheric_lens', children: [] }
]
}
]
},
{
id: 'sp-rf',
name: 'Connectivity & Power',
tier: 1,
description: '5G/Wi-Fi/Bluetooth transceivers, antennas, lithium-ion pouch battery, and wireless charging coil.',
keyFunction: 'Wireless data communication and portable energy supply.',
wikiUrl: 'https://en.wikipedia.org/wiki/5G',
children: [
{
id: 'sp-modem',
name: '5G Baseband & RF Front-End',
tier: 2,
description: 'Modem chip, power amplifiers, and perimeter frame antennas.',
keyFunction: 'Handles cellular, Wi-Fi 7, Bluetooth, and GNSS signals.',
wikiUrl: 'https://en.wikipedia.org/wiki/Baseband_processor',
children: [
{ id: 'sp-pmic', name: 'Power Management IC (PMIC)', tier: 3, description: 'Regulates battery charging and distributes precise voltage rails to all chips.', keyFunction: 'Manages power efficiency and fast charging.', wikiUrl: 'https://en.wikipedia.org/wiki/Power_management_integrated_circuit', children: [] },
{ id: 'sp-coil', name: 'Qi Inductive Charging Coil', tier: 3, description: 'Flat copper spiral coil mounted behind the rear glass.', keyFunction: 'Enables wireless magnetic induction charging.', wikiUrl: 'https://en.wikipedia.org/wiki/Qi_(standard)', children: [] }
]
}
]
}
]
},
espresso: {
id: 'esp-root',
name: 'Espresso Machine',
tier: 0,
description: 'A precision thermo-hydraulic appliance that forces temperature-stabilized water at ~9 bar of pressure through finely ground, compacted coffee.',
keyFunction: 'Extracts concentrated emulsified coffee (espresso) and steams milk.',
wikiUrl: 'https://en.wikipedia.org/wiki/Espresso_machine',
children: [
{
id: 'esp-thermal',
name: 'Boiler & Thermal System',
tier: 1,
description: 'Pressurized stainless-steel or brass heating vessels maintaining brew water (~93°C) and dry steam (~125°C).',
keyFunction: 'Delivers thermally stable brew water and pressurized steam.',
wikiUrl: 'https://en.wikipedia.org/wiki/Boiler',
children: [
{
id: 'esp-boiler',
name: 'Dual Boiler / Thermoblock',
tier: 2,
description: 'Dedicated brew and steam boilers allowing simultaneous extraction and milk texturing.',
keyFunction: 'Thermal mass and temperature stability.',
wikiUrl: 'https://en.wikipedia.org/wiki/Water_heating',
children: [
{ id: 'esp-element', name: 'Immersion Heating Element', tier: 3, description: 'Resistive tubular heater submerged inside the boiler water.', keyFunction: 'Converts electrical power into heat.', wikiUrl: 'https://en.wikipedia.org/wiki/Heating_element', children: [] },
{ id: 'esp-pid', name: 'PID Temperature Controller', tier: 3, description: 'Closed-loop feedback controller pulsing a solid-state relay to hold ±0.5°C accuracy.', keyFunction: 'Eliminates temperature swings.', wikiUrl: 'https://en.wikipedia.org/wiki/PID_controller', children: [] }
]
}
]
},
{
id: 'esp-hydraulic',
name: 'Hydraulic Pump System',
tier: 1,
description: 'Draws fresh water from a reservoir or plumbed line and pressurizes it to 9 bar for extraction.',
keyFunction: 'Generates consistent brewing pressure and flow rate.',
wikiUrl: 'https://en.wikipedia.org/wiki/Pump',
children: [
{
id: 'esp-pump',
name: 'Rotary Vane / Vibration Pump',
tier: 2,
description: 'Positive-displacement pump generating up to 15 bar of raw hydraulic head.',
keyFunction: 'Pressurizes the water circuit.',
wikiUrl: 'https://en.wikipedia.org/wiki/Rotary_vane_pump',
children: [
{ id: 'esp-opv', name: 'Over-Pressure Valve (OPV)', tier: 3, description: 'Spring-loaded bypass valve capping brew pressure precisely at 9 bar.', keyFunction: 'Regulates peak extraction pressure.', wikiUrl: 'https://en.wikipedia.org/wiki/Relief_valve', children: [] },
{ id: 'esp-solenoid', name: '3-Way Solenoid Valve', tier: 3, description: 'Electromagnetic valve that vents residual puck pressure to the drip tray after brewing.', keyFunction: 'Enables clean portafilter removal.', wikiUrl: 'https://en.wikipedia.org/wiki/Solenoid_valve', children: [] }
]
}
]
},
{
id: 'esp-group',
name: 'Brewing Grouphead',
tier: 1,
description: 'Heavy chrome-plated brass assembly where the portafilter locks in and hot water meets the coffee puck.',
keyFunction: 'Distributes water evenly over coffee grounds while maintaining thermal equilibrium.',
wikiUrl: 'https://en.wikipedia.org/wiki/Espresso#Brewing',
children: [
{
id: 'esp-portafilter',
name: 'Portafilter & Filter Basket',
tier: 2,
description: 'Removable handled holder containing a precision laser-perforated stainless-steel basket.',
keyFunction: 'Holds the tamped coffee puck under 9 bar pressure.',
wikiUrl: 'https://en.wikipedia.org/wiki/Portafilter',
children: [
{ id: 'esp-screen', name: 'Dispersion Shower Screen', tier: 3, description: 'Fine stainless-steel mesh diffuser mounted inside the grouphead.', keyFunction: 'Prevents water channeling into the puck.', wikiUrl: 'https://en.wikipedia.org/wiki/Espresso_machine#Grouphead', children: [] },
{ id: 'esp-gasket', name: 'Silicone Group Gasket', tier: 3, description: 'High-temperature elastomeric ring sealing the portafilter rim.', keyFunction: 'Maintains a watertight pressure seal.', wikiUrl: 'https://en.wikipedia.org/wiki/Gasket', children: [] }
]
}
]
},
{
id: 'esp-steam',
name: 'Steam & Milk Texturing',
tier: 1,
description: 'Articulated insulated steam wand and needle valve tapping dry steam from the top of the steam boiler.',
keyFunction: 'Aerates and heats milk into glossy microfoam.',
wikiUrl: 'https://en.wikipedia.org/wiki/Steamed_milk',
children: [
{
id: 'esp-wand',
name: 'Cool-Touch Steam Wand',
tier: 2,
description: 'Double-walled stainless steel tube with a ball-joint swivel.',
keyFunction: 'Directs high-velocity steam into a milk pitcher.',
wikiUrl: 'https://en.wikipedia.org/wiki/Latte_art',
children: [
{ id: 'esp-tip', name: 'Multi-Hole Steam Tip', tier: 3, description: 'Threaded nozzle with 2 to 4 angled micro-orifices.', keyFunction: 'Creates a vortex for silky microfoam.', wikiUrl: 'https://en.wikipedia.org/wiki/Nozzle', children: [] }
]
}
]
}
]
}
};
// =========================================================================
// 3. APPLICATION STATE
// =========================================================================
let graphData = structuredClone(PRESETS.ev);
let currentLayout = 'force'; // 'force' | 'tree' | 'radial'
let selectedNodeId = null;
let visibleTiers = new Set([0, 1, 2, 3]);
let modalMode = 'add'; // 'add' | 'edit'
let simulation = null;
// D3 Selections
const svg = d3.select('#graph-svg');
const defs = svg.append('defs');
const container = svg.append('g').attr('id', 'zoom-container');
const linkLayer = container.append('g').attr('id', 'link-layer');
const nodeLayer = container.append('g').attr('id', 'node-layer');
// Add SVG Glow Filters for each tier
TIER_META.forEach((meta, idx) => {
const filter = defs.append('filter')
.attr('id', `glow-${idx}`)
.attr('x', '-50%').attr('y', '-50%')
.attr('width', '200%').attr('height', '200%');
filter.append('feGaussianBlur')
.attr('stdDeviation', idx === 0 ? '5' : '3.5')
.attr('result', 'coloredBlur');
const feMerge = filter.append('feMerge');
feMerge.append('feMergeNode').attr('in', 'coloredBlur');
feMerge.append('feMergeNode').attr('in', 'SourceGraphic');
});
// Zoom behavior
const zoom = d3.zoom()
.scaleExtent([0.15, 3.5])
.on('zoom', (event) => {
container.attr('transform', event.transform);
});
svg.call(zoom).on('dblclick.zoom', null);
// =========================================================================
// 4. HELPER UTILITIES
// =========================================================================
function showToast(msg, isError = false) {
const toast = document.getElementById('toast');
const dot = document.getElementById('toast-dot');
document.getElementById('toast-msg').textContent = msg;
dot.className = `w-2 h-2 rounded-full ${isError ? 'bg-rose-400' : 'bg-cyan-400'}`;
toast.classList.remove('translate-y-20', 'opacity-0');
clearTimeout(window._toastTimer);
window._toastTimer = setTimeout(() => {
toast.classList.add('translate-y-20', 'opacity-0');
}, 3200);
}
function generateId() {
return 'node-' + Math.random().toString(36).substring(2, 9);
}
function findNodeAndParent(node, id, parent = null) {
if (node.id === id) return { node, parent };
if (node.children) {
for (const child of node.children) {
const found = findNodeAndParent(child, id, node);
if (found) return found;
}
}
return null;
}
function getPathToNode(node, targetId, path = []) {
const currentPath = [...path, node];
if (node.id === targetId) return currentPath;
if (node.children) {
for (const child of node.children) {
const res = getPathToNode(child, targetId, currentPath);
if (res) return res;
}
}
return null;
}
function countAllNodes(node) {
let c = 1;
if (node.children) node.children.forEach(ch => c += countAllNodes(ch));
return c;
}
function getAllNodesFlat(node, list = []) {
list.push(node);
if (node.children) node.children.forEach(ch => getAllNodesFlat(ch, list));
return list;
}
// Build filtered hierarchy respecting collapsed state & visibleTiers
function buildVisibleHierarchy(rootData) {
function cloneFiltered(node) {
if (!visibleTiers.has(node.tier)) return null;
const copy = { ...node, _rawRef: node, children: [] };
if (!node.collapsed && node.children && node.children.length > 0) {
for (const ch of node.children) {
const filteredChild = cloneFiltered(ch);
if (filteredChild) copy.children.push(filteredChild);
}
}
return copy;
}
const filtered = cloneFiltered(rootData);
return filtered ? d3.hierarchy(filtered) : null;
}
// =========================================================================
// 5. GRAPH RENDERING ENGINE (Force, Tree, Radial)
// =========================================================================
function renderGraph(autoFit = false) {
if (simulation) {
simulation.stop();
simulation = null;
}
linkLayer.selectAll('*').remove();
nodeLayer.selectAll('*').remove();
const totalCount = countAllNodes(graphData);
const root = buildVisibleHierarchy(graphData);
if (!root) {
document.getElementById('graph-stats').textContent = `0 / ${totalCount} nodes visible`;
return;
}
const nodes = root.descendants();
const links = root.links();
document.getElementById('graph-stats').textContent = `${nodes.length} / ${totalCount} nodes`;
const width = svg.node().clientWidth || window.innerWidth;
const height = svg.node().clientHeight || window.innerHeight;
// Compute coordinates based on layout
if (currentLayout === 'tree') {
const treeLayout = d3.tree().nodeSize([38, 220]);
treeLayout(root);
// Swap x & y for left-to-right horizontal tree
nodes.forEach(d => {
const tmp = d.x;
d.x = d.y + 120;
d.y = tmp + height / 2;
});
} else if (currentLayout === 'radial') {
const maxRadius = Math.min(width, height) * 0.44;
const radialLayout = d3.tree()
.size([2 * Math.PI, Math.max(maxRadius, 300)])
.separation((a, b) => (a.parent === b.parent ? 1.2 : 2.2) / Math.max(a.depth, 1));
radialLayout(root);
nodes.forEach(d => {
const angle = d.x - Math.PI / 2;
const r = d.y;
d.x = width / 2 + r * Math.cos(angle);
d.y = height / 2 + r * Math.sin(angle);
});
} else {
// Force-directed initial positions centered
nodes.forEach(d => {
if (d.depth === 0) {
d.x = width / 2;
d.y = height / 2;
} else {
const angle = Math.random() * 2 * Math.PI;
const dist = d.depth * 110;
d.x = width / 2 + Math.cos(angle) * dist;
d.y = height / 2 + Math.sin(angle) * dist;
}
});
}
// Draw Links
const linkSel = linkLayer.selectAll('path')
.data(links)
.enter()
.append('path')
.attr('class', 'link-path')
.attr('stroke', d => {
const tier = d.target.data.tier;
return TIER_META[tier]?.color || '#64748b';
})
.attr('stroke-opacity', 0.35)
.attr('stroke-width', d => Math.max(1.2, 2.8 - d.target.data.tier * 0.5));
function updateLinkPaths() {
if (currentLayout === 'tree') {
const linkGen = d3.linkHorizontal().x(d => d.x).y(d => d.y);
linkSel.attr('d', d => linkGen({ source: d.source, target: d.target }));
} else {
linkSel.attr('d', d => `M${d.source.x},${d.source.y} L${d.target.x},${d.target.y}`);
}
}
// Draw Nodes
const nodeSel = nodeLayer.selectAll('g')
.data(nodes, d => d.data.id)
.enter()
.append('g')
.attr('class', 'node-group')
.attr('data-id', d => d.data.id)
.attr('transform', d => `translate(${d.x},${d.y})`);
// Selected pulse ring
nodeSel.append('circle')
.attr('class', 'selected-ring hidden')
.attr('r', d => (TIER_META[d.data.tier]?.radius || 10) + 6)
.attr('fill', 'none')
.attr('stroke', d => TIER_META[d.data.tier]?.stroke || '#fff')
.attr('stroke-width', 2);
// Collapsed indicator outer dashed ring
nodeSel.filter(d => d.data._rawRef.collapsed && d.data._rawRef.children?.length > 0)
.append('circle')
.attr('r', d => (TIER_META[d.data.tier]?.radius || 10) + 5)
.attr('fill', 'none')
.attr('stroke', '#e2e8f0')
.attr('stroke-width', 1.5)
.attr('stroke-dasharray', '3 3')
.attr('opacity', 0.75);
// Main Node Circle
nodeSel.append('circle')
.attr('class', 'node-circle')
.attr('r', d => TIER_META[d.data.tier]?.radius || 10)
.attr('fill', d => TIER_META[d.data.tier]?.color || '#64748b')
.attr('stroke', d => TIER_META[d.data.tier]?.stroke || '#cbd5e1')
.attr('stroke-width', d => d.data.tier === 0 ? 2.5 : 1.5)
.attr('filter', d => `url(#glow-${d.data.tier})`);
// Collapsed count badge inside circle
nodeSel.filter(d => d.data._rawRef.collapsed && d.data._rawRef.children?.length > 0)
.append('text')
.attr('text-anchor', 'middle')
.attr('dy', '0.35em')
.attr('fill', '#090d16')
.attr('font-size', '10px')
.attr('font-weight', '700')
.text(d => `+${d.data._rawRef.children.length}`);
// Node Text Label
nodeSel.append('text')
.attr('class', 'node-label')
.attr('dy', d => (TIER_META[d.data.tier]?.radius || 10) + 14)
.attr('text-anchor', 'middle')
.attr('fill', d => d.data.tier === 0 ? '#fef3c7' : '#e2e8f0')
.attr('font-size', d => d.data.tier === 0 ? '13px' : d.data.tier === 1 ? '11.5px' : '10.5px')
.attr('font-weight', d => d.data.tier <= 1 ? '600' : '400')
.text(d => d.data.name);
// Hover Lineage Highlighting
nodeSel.on('mouseenter', (event, d) => {
const highlightIds = new Set();
// Ancestors
let curr = d;
while (curr) {
highlightIds.add(curr.data.id);
curr = curr.parent;
}
// Direct children
if (d.children) d.children.forEach(c => highlightIds.add(c.data.id));
nodeSel.classed('dimmed', n => !highlightIds.has(n.data.id));
linkSel
.classed('dimmed', l => !(highlightIds.has(l.source.data.id) && highlightIds.has(l.target.data.id)))
.classed('highlighted', l => highlightIds.has(l.source.data.id) && highlightIds.has(l.target.data.id));
}).on('mouseleave', () => {
nodeSel.classed('dimmed', false);
linkSel.classed('dimmed', false).classed('highlighted', false);
});
// Click -> Open Inspector
nodeSel.on('click', (event, d) => {
event.stopPropagation();
selectNode(d.data.id);
});
// Double-click -> Collapse / Expand descendants
nodeSel.on('dblclick', (event, d) => {
event.stopPropagation();
const raw = d.data._rawRef;
if (raw.children && raw.children.length > 0) {
raw.collapsed = !raw.collapsed;
renderGraph(false);
if (selectedNodeId === raw.id) openInspector(raw.id);
}
});
// Background click closes inspector
svg.on('click', () => {
closeInspector();
});
// Setup Force Simulation or Static Placement
if (currentLayout === 'force') {
simulation = d3.forceSimulation(nodes)
.force('link', d3.forceLink(links).id(d => d.data.id).distance(d => {
const tier = d.target.data.tier;
return tier === 1 ? 135 : tier === 2 ? 95 : 68;
}).strength(0.85))
.force('charge', d3.forceManyBody().strength(d => d.data.tier === 0 ? -550 : d.data.tier === 1 ? -320 : -190))
.force('center', d3.forceCenter(width / 2, height / 2))
.force('collide', d3.forceCollide().radius(d => (TIER_META[d.data.tier]?.radius || 10) + 28))
.on('tick', () => {
nodeSel.attr('transform', d => `translate(${d.x},${d.y})`);
updateLinkPaths();
});
// Dragging in Force Layout
nodeSel.call(d3.drag()
.on('start', (event, d) => {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
})
.on('drag', (event, d) => {
d.fx = event.x;
d.fy = event.y;
})
.on('end', (event, d) => {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
})
);
} else {
updateLinkPaths();
// Allow manual node dragging in Tree / Radial too
nodeSel.call(d3.drag()
.on('drag', (event, d) => {
d.x = event.x;
d.y = event.y;
d3.select(event.sourceEvent.target.closest('.node-group'))
.attr('transform', `translate(${d.x},${d.y})`);
updateLinkPaths();
})
);
}
updateSelectedVisuals();
if (autoFit) {
setTimeout(() => fitGraphToScreen(), currentLayout === 'force' ? 450 : 60);
}
}
function updateSelectedVisuals() {
nodeLayer.selectAll('.selected-ring')
.classed('hidden', d => d.data.id !== selectedNodeId)
.classed('selected-pulse', d => d.data.id === selectedNodeId);
}
function fitGraphToScreen() {
const bounds = container.node().getBBox();
if (!bounds.width || !bounds.height) return;
const width = svg.node().clientWidth || window.innerWidth;
const height = svg.node().clientHeight || window.innerHeight;
const padding = 70;
const scale = Math.min(
1.25,
Math.max(0.25, Math.min((width - padding * 2) / bounds.width, (height - padding * 2) / bounds.height))
);
const tx = width / 2 - scale * (bounds.x + bounds.width / 2);
const ty = height / 2 - scale * (bounds.y + bounds.height / 2);
svg.transition().duration(500).call(zoom.transform, d3.zoomIdentity.translate(tx, ty).scale(scale));
}
function focusNodeById(id) {
const nodeEl = nodeLayer.select(`.node-group[data-id="${id}"]`);
if (nodeEl.empty()) return;
const d = nodeEl.datum();
const width = svg.node().clientWidth || window.innerWidth;
const height = svg.node().clientHeight || window.innerHeight;
const scale = 1.15;
const tx = width / 2 - d.x * scale;
const ty = height / 2 - d.y * scale;
svg.transition().duration(550).call(zoom.transform, d3.zoomIdentity.translate(tx, ty).scale(scale));
}
// =========================================================================
// 6. INSPECTOR PANEL LOGIC
// =========================================================================
function selectNode(id) {
selectedNodeId = id;
updateSelectedVisuals();
openInspector(id);
}
function openInspector(id) {
const found = findNodeAndParent(graphData, id);
if (!found) return;
const { node } = found;
const meta = TIER_META[node.tier] || TIER_META[3];
// Breadcrumbs
const path = getPathToNode(graphData, id) || [node];
const bcContainer = document.getElementById('inspector-breadcrumbs');
bcContainer.innerHTML = '';
path.forEach((p, idx) => {
const btn = document.createElement('button');
btn.className = 'hover:text-cyan-300 transition cursor-pointer truncate max-w-[110px]';
btn.textContent = p.name;
btn.onclick = () => { selectNode(p.id); focusNodeById(p.id); };
bcContainer.appendChild(btn);
if (idx < path.length - 1) {
const sep = document.createElement('span');
sep.textContent = '/';
sep.className = 'text-slate-600';
bcContainer.appendChild(sep);
}
});
// Title & Tier Badge
document.getElementById('inspector-title').textContent = node.name;
const badge = document.getElementById('inspector-tier-badge');
badge.textContent = meta.label;
badge.className = `text-[10px] font-mono uppercase tracking-wider px-2 py-0.5 rounded-full border ${meta.badgeClass}`;
// Description & Key Function
document.getElementById('inspector-desc').textContent = node.description || 'No technical description provided.';
const funcWrap = document.getElementById('inspector-func-wrap');
if (node.keyFunction) {
funcWrap.classList.remove('hidden');
document.getElementById('inspector-func').textContent = node.keyFunction;
} else {
funcWrap.classList.add('hidden');
}
// Online Information Links
const linksEl = document.getElementById('inspector-links');
linksEl.innerHTML = '';
const q = encodeURIComponent(`${node.name} ${graphData.name !== node.name ? graphData.name : ''}`.trim());
const wikiHref = node.wikiUrl && node.wikiUrl.startsWith('http')
? node.wikiUrl
: `https://en.wikipedia.org/wiki/Special:Search?search=${encodeURIComponent(node.name)}`;
const refLinks = [
{ title: `Wikipedia: ${node.name}`, subtitle: 'Encyclopedia article & overview', url: wikiHref, accent: 'text-amber-300 border-amber-500/25 bg-amber-500/10' },
{ title: 'Google Scholar Research', subtitle: 'Academic papers & technical literature', url: `https://scholar.google.com/scholar?q=${q}`, accent: 'text-cyan-300 border-cyan-500/25 bg-cyan-500/10' },
{ title: 'HowStuffWorks & Technical Guides', subtitle: 'Engineering diagrams & explainers', url: `https://www.google.com/search?q=${encodeURIComponent('how ' + node.name + ' works engineering')}`, accent: 'text-emerald-300 border-emerald-500/25 bg-emerald-500/10' }
];
if (node.extraLinks && Array.isArray(node.extraLinks)) {
node.extraLinks.forEach(l => {
if (l.url && l.url.startsWith('http')) {
refLinks.push({ title: l.title || 'External Reference', subtitle: l.url, url: l.url, accent: 'text-violet-300 border-violet-500/25 bg-violet-500/10' });
}
});
}
refLinks.forEach(link => {
const a = document.createElement('a');
a.href = link.url;
a.target = '_blank';
a.rel = 'noopener noreferrer';
a.className = `flex items-center justify-between gap-2 p-2.5 rounded-xl border ${link.accent} hover:brightness-125 transition group`;
a.innerHTML = `
<div class="min-w-0">
<div class="text-xs font-semibold truncate">${escapeHtml(link.title)}</div>
<div class="text-[11px] opacity-75 truncate">${escapeHtml(link.subtitle)}</div>
</div>
<svg class="w-4 h-4 shrink-0 opacity-70 group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-transform" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
<polyline points="15 3 21 3 21 9"></polyline>
<line x1="10" y1="14" x2="21" y2="3"></line>
</svg>
`;
linksEl.appendChild(a);
});
// Child Nodes
const childrenEl = document.getElementById('inspector-children');
const toggleBtn = document.getElementById('inspector-toggle-collapse');
const heading = document.getElementById('inspector-children-heading');
childrenEl.innerHTML = '';
const kids = node.children || [];
heading.textContent = `Child Nodes (${kids.length})`;
if (kids.length > 0) {
toggleBtn.classList.remove('hidden');
toggleBtn.textContent = node.collapsed ? 'Expand Children' : 'Collapse Children';
toggleBtn.onclick = () => {
node.collapsed = !node.collapsed;
renderGraph(false);
openInspector(node.id);
};
kids.forEach(child => {
const cMeta = TIER_META[child.tier] || TIER_META[3];
const btn = document.createElement('button');
btn.className = 'w-full flex items-center justify-between gap-2 px-3 py-2 rounded-xl bg-slate-900/70 hover:bg-slate-800 border border-slate-800 hover:border-slate-600 text-left transition cursor-pointer';
btn.innerHTML = `
<div class="flex items-center gap-2 min-w-0">
<span class="w-2.5 h-2.5 rounded-full shrink-0" style="background:${cMeta.color}"></span>
<span class="text-xs font-medium text-slate-200 truncate">${escapeHtml(child.name)}</span>
</div>
<span class="text-[10px] font-mono text-slate-400 shrink-0">${cMeta.label}</span>
`;
btn.onclick = () => {
if (node.collapsed) {
node.collapsed = false;
renderGraph(false);
}
selectNode(child.id);
focusNodeById(child.id);
};
childrenEl.appendChild(btn);
});
} else {
toggleBtn.classList.add('hidden');
childrenEl.innerHTML = `<p class="text-xs text-slate-500 italic">Leaf node — click "+ Add Child" below to expand this branch.</p>`;
}
// Disable delete on root node
const delBtn = document.getElementById('btn-delete-node');
if (node.id === graphData.id) {
delBtn.disabled = true;
delBtn.classList.add('opacity-40', 'cursor-not-allowed');
} else {
delBtn.disabled = false;
delBtn.classList.remove('opacity-40', 'cursor-not-allowed');
}
// Open drawer
document.getElementById('inspector-drawer').classList.remove('translate-x-full');
}
function closeInspector() {
selectedNodeId = null;
updateSelectedVisuals();
document.getElementById('inspector-drawer').classList.add('translate-x-full');
}
function escapeHtml(str) {
return String(str).replace(/[&<>"']/g, m => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[m]));
}
// =========================================================================
// 7. GEMINI API INTEGRATION (Dynamic System Generation)
// =========================================================================
async function fetchWithBackoff(url, options, maxRetries = 5) {
let delay = 1000;
for (let i = 0; i < maxRetries; i++) {
try {
const res = await fetch(url, options);
if (res.ok) return res;
if (res.status !== 429 && res.status < 500) {
throw new Error(`API Error ${res.status}`);
}
} catch (err) {
if (i === maxRetries - 1) throw err;
}
await new Promise(r => setTimeout(r, delay));
delay *= 2;
}
throw new Error('Max retries exceeded');
}
async function generateSystemWithGemini(systemName) {
const overlay = document.getElementById('loading-overlay');
document.getElementById('loading-title').textContent = `Decomposing "${systemName}"...`;
overlay.classList.remove('hidden');
const apiKey = "";
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=${apiKey}`;
const partSchema = {
type: 'OBJECT',
properties: {
name: { type: 'STRING' },
description: { type: 'STRING' },
keyFunction: { type: 'STRING' },
wikiUrl: { type: 'STRING' }
},
required: ['name', 'description', 'keyFunction', 'wikiUrl']
};
const componentSchema = {
type: 'OBJECT',
properties: {
name: { type: 'STRING' },
description: { type: 'STRING' },
keyFunction: { type: 'STRING' },
wikiUrl: { type: 'STRING' },
parts: { type: 'ARRAY', items: partSchema }
},
required: ['name', 'description', 'keyFunction', 'wikiUrl', 'parts']
};
const subsystemSchema = {
type: 'OBJECT',
properties: {
name: { type: 'STRING' },
description: { type: 'STRING' },
keyFunction: { type: 'STRING' },
wikiUrl: { type: 'STRING' },
components: { type: 'ARRAY', items: componentSchema }
},
required: ['name', 'description', 'keyFunction', 'wikiUrl', 'components']
};
const responseSchema = {
type: 'OBJECT',
properties: {
name: { type: 'STRING' },
description: { type: 'STRING' },
keyFunction: { type: 'STRING' },
wikiUrl: { type: 'STRING' },
subsystems: { type: 'ARRAY', items: subsystemSchema }
},
required: ['name', 'description', 'keyFunction', 'wikiUrl', 'subsystems']
};
const prompt = `Decompose the system "${systemName}" into a comprehensive 4-tier engineering knowledge graph:
- 1 root System ("${systemName}")
- 3 to 5 major Subsystems
- 2 to 3 key Components per Subsystem
- 2 to 3 specific Parts per Component
For EVERY node provide:
- name: concise technical name
- description: 1-2 sentence technical explanation
- keyFunction: concise primary role
- wikiUrl: valid English Wikipedia URL (https://en.wikipedia.org/wiki/...) for that topic.`;
const payload = {
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
responseMimeType: 'application/json',
responseSchema
}
};
try {
const response = await fetchWithBackoff(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const result = await response.json();
const rawText = result?.candidates?.[0]?.content?.parts?.[0]?.text;
if (!rawText) throw new Error('Empty response from Gemini');
const parsed = JSON.parse(rawText);
// Convert to internal tree format
const normalized = {
id: generateId(),
name: parsed.name || systemName,
tier: 0,
description: parsed.description || '',
keyFunction: parsed.keyFunction || '',
wikiUrl: parsed.wikiUrl || '',
children: (parsed.subsystems || []).map(sub => ({
id: generateId(),
name: sub.name,
tier: 1,
description: sub.description || '',
keyFunction: sub.keyFunction || '',
wikiUrl: sub.wikiUrl || '',
children: (sub.components || []).map(comp => ({
id: generateId(),
name: comp.name,
tier: 2,
description: comp.description || '',
keyFunction: comp.keyFunction || '',
wikiUrl: comp.wikiUrl || '',
children: (comp.parts || []).map(part => ({
id: generateId(),
name: part.name,
tier: 3,
description: part.description || '',
keyFunction: part.keyFunction || '',
wikiUrl: part.wikiUrl || '',
children: []
}))
}))
}))
};
graphData = normalized;
closeInspector();
renderGraph(true);
showToast(`Generated knowledge graph for "${normalized.name}"`);
} catch (err) {
console.error(err);
showToast('Failed to generate graph. Please try again.', true);
} finally {
overlay.classList.add('hidden');
}
}
// =========================================================================
// 8. EVENT LISTENERS & UI INTERACTIONS
// =========================================================================
// Generate System Form
document.getElementById('generate-form').addEventListener('submit', (e) => {
e.preventDefault();
const val = document.getElementById('system-input').value.trim();
if (!val) {
showToast('Please enter a system name first.', true);
return;
}
generateSystemWithGemini(val);
});
// Preset Selector
document.getElementById('preset-select').addEventListener('change', (e) => {
const key = e.target.value;
if (PRESETS[key]) {
graphData = structuredClone(PRESETS[key]);
closeInspector();
renderGraph(true);
showToast(`Loaded preset: ${graphData.name}`);
}
});
// Layout Switcher
document.querySelectorAll('.layout-btn').forEach(btn => {
btn.addEventListener('click', () => {
currentLayout = btn.dataset.layout;
document.querySelectorAll('.layout-btn').forEach(b => {
b.className = 'layout-btn px-2.5 py-1.5 rounded-xl text-xs font-medium text-slate-400 hover:text-white border border-transparent transition cursor-pointer';
});
btn.className = 'layout-btn px-2.5 py-1.5 rounded-xl text-xs font-medium bg-cyan-500/20 text-cyan-300 border border-cyan-500/40 transition cursor-pointer';
renderGraph(true);
});
});
// Zoom Controls
document.getElementById('zoom-in').addEventListener('click', () => {
svg.transition().duration(250).call(zoom.scaleBy, 1.3);
});
document.getElementById('zoom-out').addEventListener('click', () => {
svg.transition().duration(250).call(zoom.scaleBy, 0.77);
});
document.getElementById('zoom-fit').addEventListener('click', fitGraphToScreen);
document.getElementById('expand-all').addEventListener('click', () => {
getAllNodesFlat(graphData).forEach(n => n.collapsed = false);
renderGraph(true);
showToast('Expanded all nodes');
});
// Tier Visibility Toggles
document.querySelectorAll('.tier-filter-btn').forEach(btn => {
btn.addEventListener('click', () => {
const tier = Number(btn.dataset.tier);
if (visibleTiers.has(tier)) {
if (tier === 0) {
showToast('Root System tier must remain visible.', true);
return;
}
visibleTiers.delete(tier);
btn.classList.add('opacity-35');
} else {
visibleTiers.add(tier);
btn.classList.remove('opacity-35');
}
renderGraph(false);
});
});
// Live Node Search
const searchInput = document.getElementById('node-search-input');
const searchResults = document.getElementById('search-results');
const clearSearchBtn = document.getElementById('clear-search-btn');
searchInput.addEventListener('input', () => {
const q = searchInput.value.trim().toLowerCase();
clearSearchBtn.classList.toggle('hidden', !q);
if (!q) {
searchResults.classList.add('hidden');
searchResults.innerHTML = '';
return;
}
const matches = getAllNodesFlat(graphData).filter(n =>
n.name.toLowerCase().includes(q) || (n.description && n.description.toLowerCase().includes(q))
);
searchResults.innerHTML = '';
searchResults.classList.remove('hidden');
if (matches.length === 0) {
searchResults.innerHTML = `<div class="text-[11px] text-slate-500 px-2 py-1">No matching nodes</div>`;
return;
}
matches.slice(0, 10).forEach(m => {
const meta = TIER_META[m.tier] || TIER_META[3];
const item = document.createElement('button');
item.className = 'w-full flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg hover:bg-slate-800/80 text-left transition cursor-pointer';
item.innerHTML = `
<span class="flex items-center gap-1.5 min-w-0">
<span class="w-2 h-2 rounded-full shrink-0" style="background:${meta.color}"></span>
<span class="text-xs text-slate-200 truncate">${escapeHtml(m.name)}</span>
</span>
<span class="text-[10px] font-mono text-slate-500 shrink-0">${meta.label}</span>
`;
item.onclick = () => {
// Ensure ancestors are expanded
const path = getPathToNode(graphData, m.id) || [];
path.forEach(p => p.collapsed = false);
visibleTiers.add(m.tier);
renderGraph(false);
selectNode(m.id);
focusNodeById(m.id);
searchResults.classList.add('hidden');
};
searchResults.appendChild(item);
});
});
clearSearchBtn.addEventListener('click', () => {
searchInput.value = '';
clearSearchBtn.classList.add('hidden');
searchResults.classList.add('hidden');
});
// Inspector Buttons
document.getElementById('close-inspector').addEventListener('click', closeInspector);
// Add / Edit Node Modal
const nodeModal = document.getElementById('node-modal');
function openNodeModal(mode) {
if (!selectedNodeId) return;
const found = findNodeAndParent(graphData, selectedNodeId);
if (!found) return;
modalMode = mode;
if (mode === 'add') {
document.getElementById('modal-title').textContent = `Add Child to "${found.node.name}"`;
document.getElementById('form-name').value = '';
document.getElementById('form-tier').value = String(Math.min(3, found.node.tier + 1));
document.getElementById('form-desc').value = '';
document.getElementById('form-func').value = '';
document.getElementById('form-url').value = '';
} else {
document.getElementById('modal-title').textContent = `Edit "${found.node.name}"`;
document.getElementById('form-name').value = found.node.name;
document.getElementById('form-tier').value = String(found.node.tier);
document.getElementById('form-desc').value = found.node.description || '';
document.getElementById('form-func').value = found.node.keyFunction || '';
document.getElementById('form-url').value = found.node.wikiUrl || '';
}
nodeModal.classList.remove('hidden');
document.getElementById('form-name').focus();
}
document.getElementById('btn-add-child').addEventListener('click', () => openNodeModal('add'));
document.getElementById('btn-edit-node').addEventListener('click', () => openNodeModal('edit'));
document.getElementById('close-node-modal').addEventListener('click', () => nodeModal.classList.add('hidden'));
document.getElementById('cancel-node-modal').addEventListener('click', () => nodeModal.classList.add('hidden'));
document.getElementById('node-form').addEventListener('submit', (e) => {
e.preventDefault();
const found = findNodeAndParent(graphData, selectedNodeId);
if (!found) return;
const name = document.getElementById('form-name').value.trim();
const tier = Number(document.getElementById('form-tier').value);
const description = document.getElementById('form-desc').value.trim();
const keyFunction = document.getElementById('form-func').value.trim();
const wikiUrl = document.getElementById('form-url').value.trim();
if (modalMode === 'add') {
const newNode = {
id: generateId(),
name,
tier,
description,
keyFunction,
wikiUrl,
children: []
};
if (!found.node.children) found.node.children = [];
found.node.children.push(newNode);
found.node.collapsed = false;
nodeModal.classList.add('hidden');
renderGraph(false);
selectNode(newNode.id);
showToast(`Added "${name}"`);
} else {
found.node.name = name;
found.node.tier = tier;
found.node.description = description;
found.node.keyFunction = keyFunction;
found.node.wikiUrl = wikiUrl;
nodeModal.classList.add('hidden');
renderGraph(false);
openInspector(found.node.id);
showToast(`Updated "${name}"`);
}
});
// Delete Node
document.getElementById('btn-delete-node').addEventListener('click', () => {
if (!selectedNodeId || selectedNodeId === graphData.id) return;
const found = findNodeAndParent(graphData, selectedNodeId);
if (!found || !found.parent) return;
const removedName = found.node.name;
found.parent.children = found.parent.children.filter(c => c.id !== selectedNodeId);
closeInspector();
renderGraph(false);
showToast(`Deleted "${removedName}"`);
});
// Export JSON
document.getElementById('btn-export').addEventListener('click', () => {
const jsonStr = JSON.stringify(graphData, null, 2);
const blob = new Blob([jsonStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${graphData.name.toLowerCase().replace(/\s+/g, '_')}_graph.json`;
a.click();
URL.revokeObjectURL(url);
showToast('Exported graph as JSON');
});
// Import JSON Modal
const importModal = document.getElementById('import-modal');
document.getElementById('btn-import').addEventListener('click', () => {
document.getElementById('import-json-text').value = '';
importModal.classList.remove('hidden');
});
document.getElementById('close-import-modal').addEventListener('click', () => importModal.classList.add('hidden'));
document.getElementById('cancel-import-modal').addEventListener('click', () => importModal.classList.add('hidden'));
document.getElementById('import-file-input').addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (ev) => {
document.getElementById('import-json-text').value = ev.target.result;
};
reader.readAsText(file);
});
document.getElementById('confirm-import-btn').addEventListener('click', () => {
try {
const parsed = JSON.parse(document.getElementById('import-json-text').value);
if (!parsed.name || !Array.isArray(parsed.children)) {
throw new Error('Invalid graph structure');
}
// Ensure IDs exist
function ensureIds(n, depth = 0) {
if (!n.id) n.id = generateId();
if (typeof n.tier !== 'number') n.tier = Math.min(3, depth);
if (!Array.isArray(n.children)) n.children = [];
n.children.forEach(c => ensureIds(c, depth + 1));
}
ensureIds(parsed);
graphData = parsed;
importModal.classList.add('hidden');
closeInspector();
renderGraph(true);
showToast(`Imported "${graphData.name}"`);
} catch (err) {
showToast('Invalid JSON format. Please check your file.', true);
}
});
// Resize listener
window.addEventListener('resize', () => {
if (currentLayout !== 'force') {
renderGraph(false);
}
});
// =========================================================================
// 9. INITIALIZE ON LOAD
// =========================================================================
window.addEventListener('DOMContentLoaded', () => {
renderGraph(true);
});
</script>
</body>
</html>
From <https://gemini.google.com/app/c4195815f83dc434> Google Gemini (4 Neon)


Comments
Post a Comment