polly-graph 0.2.5 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -31,14 +31,19 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  CanvasManager: () => CanvasManager,
34
+ ConfigPresets: () => ConfigPresets,
34
35
  DEFAULT_COLORS: () => DEFAULT_COLORS,
35
36
  DEFAULT_HOVER_STYLES: () => DEFAULT_HOVER_STYLES,
36
37
  DEFAULT_LINK_LABEL_STYLE: () => DEFAULT_LINK_LABEL_STYLE,
37
38
  DEFAULT_LINK_STYLE: () => DEFAULT_LINK_STYLE,
38
39
  DragManager: () => DragManager,
39
40
  ErrorHandler: () => ErrorHandler,
41
+ ForceGraphConfigBuilder: () => ForceGraphConfigBuilder,
42
+ ForceGraphWrapper: () => ForceGraphWrapper,
40
43
  HoverManager: () => HoverManager,
44
+ LIBRARY_INFO: () => LIBRARY_INFO,
41
45
  NeutralColor: () => NeutralColor,
46
+ PerformanceMonitor: () => PerformanceMonitor,
42
47
  PhysicsManager: () => PhysicsManager,
43
48
  PointerManager: () => PointerManager,
44
49
  PrimaryColor: () => PrimaryColor,
@@ -47,8 +52,10 @@ __export(index_exports, {
47
52
  SelectionManager: () => SelectionManager,
48
53
  StandardColor: () => StandardColor,
49
54
  V2Graph: () => V2Graph,
55
+ VERSION: () => VERSION,
50
56
  ValidationError: () => ValidationError,
51
57
  ZoomManager: () => ZoomManager,
58
+ createForceGraph: () => createForceGraph,
52
59
  createV2Graph: () => createV2Graph,
53
60
  getIcon: () => getIcon,
54
61
  getIconSvg: () => getIconSvg,
@@ -9183,28 +9190,32 @@ function shouldRenderControl(config, key) {
9183
9190
  return value;
9184
9191
  }
9185
9192
 
9186
- // src/shared/icons/fit.svg?raw
9187
- var fit_default = '<svg\n xmlns="http://www.w3.org/2000/svg"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n>\n <path d="M5 9V5H9" />\n <path d="M19 9V5H15" />\n <path d="M5 15V19H9" />\n <path d="M19 15V19H15" />\n</svg>';
9188
-
9189
- // src/shared/icons/reset.svg?raw
9190
- var reset_default = '<svg\n xmlns="http://www.w3.org/2000/svg"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n>\n <path d="M20 12a8 8 0 1 1-2.3-5.7" />\n <path d="M20 4.5v4h-4" />\n</svg>';
9191
-
9192
- // src/shared/icons/plus.svg?raw
9193
- var plus_default = '<svg\n xmlns="http://www.w3.org/2000/svg"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n>\n <path d="M5 12h14m-7-7v14" />\n</svg>';
9194
-
9195
- // src/shared/icons/minus.svg?raw
9196
- var minus_default = '<svg\n xmlns="http://www.w3.org/2000/svg"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n>\n <path d="M19 12H5" />\n</svg>';
9197
-
9198
- // src/shared/icons/caret.svg?raw
9199
- var caret_default = '<svg\n xmlns="http://www.w3.org/2000/svg"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n>\n <path d="M9 20L16.5 12L9 4" />\n</svg>';
9200
-
9201
9193
  // src/shared/icons/index.ts
9194
+ var fitIconSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
9195
+ <path d="M5 9V5H9" />
9196
+ <path d="M19 9V5H15" />
9197
+ <path d="M5 15V19H9" />
9198
+ <path d="M19 15V19H15" />
9199
+ </svg>`;
9200
+ var resetIconSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
9201
+ <path d="M20 12a8 8 0 1 1-2.3-5.7" />
9202
+ <path d="M20 4.5v4h-4" />
9203
+ </svg>`;
9204
+ var plusIconSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
9205
+ <path d="M5 12h14m-7-7v14" />
9206
+ </svg>`;
9207
+ var minusIconSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
9208
+ <path d="M5 12h14" />
9209
+ </svg>`;
9210
+ var caretIconSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
9211
+ <path d="M6 9l6 6 6-6" />
9212
+ </svg>`;
9202
9213
  var icons = {
9203
- fit: fit_default,
9204
- reset: reset_default,
9205
- plus: plus_default,
9206
- minus: minus_default,
9207
- caret: caret_default
9214
+ fit: fitIconSvg,
9215
+ reset: resetIconSvg,
9216
+ plus: plusIconSvg,
9217
+ minus: minusIconSvg,
9218
+ caret: caretIconSvg
9208
9219
  };
9209
9220
  var iconSvg = {
9210
9221
  fit: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@@ -10132,17 +10143,3560 @@ function createV2Graph(config) {
10132
10143
  graph.initialize(config);
10133
10144
  return graph;
10134
10145
  }
10146
+
10147
+ // src/force-graph-wrapper/core/force-graph-wrapper.ts
10148
+ var import_force_graph = __toESM(require("force-graph"), 1);
10149
+
10150
+ // src/force-graph-wrapper/ui/graph-controls.ts
10151
+ function createGraphControls(container, actions, config) {
10152
+ let root2 = null;
10153
+ function mount() {
10154
+ if (!config.enabled) return;
10155
+ root2 = document.createElement("div");
10156
+ root2.className = "fg-controls";
10157
+ const position = config.position || "bottom-left";
10158
+ root2.classList.add(`fg-pos-${position}`);
10159
+ const orientation = config.orientation || "vertical";
10160
+ root2.classList.add(`fg-orient-${orientation}`);
10161
+ if (config.offset) {
10162
+ root2.style.setProperty("--fg-controls-offset-x", `${config.offset.x}px`);
10163
+ root2.style.setProperty("--fg-controls-offset-y", `${config.offset.y}px`);
10164
+ }
10165
+ appendControls2(root2, config, actions);
10166
+ container.appendChild(root2);
10167
+ }
10168
+ function destroy() {
10169
+ if (root2 && root2.parentNode) {
10170
+ root2.parentNode.removeChild(root2);
10171
+ root2 = null;
10172
+ }
10173
+ }
10174
+ return { mount, destroy };
10175
+ }
10176
+ function appendControls2(root2, config, actions) {
10177
+ const controls = [
10178
+ {
10179
+ key: "zoomIn",
10180
+ icon: getControlIcon("zoom-in"),
10181
+ label: "Zoom In",
10182
+ action: () => actions.zoomIn()
10183
+ },
10184
+ {
10185
+ key: "zoomOut",
10186
+ icon: getControlIcon("zoom-out"),
10187
+ label: "Zoom Out",
10188
+ action: () => actions.zoomOut()
10189
+ },
10190
+ {
10191
+ key: "fit",
10192
+ icon: getControlIcon("fit"),
10193
+ label: "Fit View",
10194
+ action: () => actions.fitView()
10195
+ },
10196
+ {
10197
+ key: "reset",
10198
+ icon: getControlIcon("reset"),
10199
+ label: "Reset View",
10200
+ action: () => actions.resetView()
10201
+ }
10202
+ ];
10203
+ controls.forEach((control) => {
10204
+ if (shouldShowControl(config, control.key)) {
10205
+ const button = createControlButton2(control.icon, control.label, control.action);
10206
+ root2.appendChild(button);
10207
+ }
10208
+ });
10209
+ }
10210
+ function shouldShowControl(config, key) {
10211
+ return config.show?.[key] !== false;
10212
+ }
10213
+ function createControlButton2(icon, label, onClick) {
10214
+ const button = document.createElement("button");
10215
+ button.className = "fg-control-btn";
10216
+ button.type = "button";
10217
+ button.innerHTML = icon;
10218
+ button.setAttribute("aria-label", label);
10219
+ button.setAttribute("title", label);
10220
+ button.addEventListener("click", (e) => {
10221
+ e.preventDefault();
10222
+ e.stopPropagation();
10223
+ onClick();
10224
+ });
10225
+ return button;
10226
+ }
10227
+
10228
+ // src/force-graph-wrapper/ui/graph-legends.ts
10229
+ function createGraphLegends(container, config) {
10230
+ let root2 = null;
10231
+ function mount() {
10232
+ if (!config.enabled) return;
10233
+ root2 = document.createElement("div");
10234
+ root2.className = "fg-legends";
10235
+ const position = config.position || "top-right";
10236
+ root2.classList.add(`fg-pos-${position}`);
10237
+ if (config.offset) {
10238
+ root2.style.setProperty("--fg-legends-offset-x", `${config.offset.x}px`);
10239
+ root2.style.setProperty("--fg-legends-offset-y", `${config.offset.y}px`);
10240
+ }
10241
+ container.appendChild(root2);
10242
+ }
10243
+ function destroy() {
10244
+ if (root2 && root2.parentNode) {
10245
+ root2.parentNode.removeChild(root2);
10246
+ root2 = null;
10247
+ }
10248
+ }
10249
+ function update(nodeTypes, colorMap) {
10250
+ if (!root2 || !config.enabled) return;
10251
+ root2.innerHTML = "";
10252
+ const validTypes = nodeTypes.filter((type) => type && type.trim()).sort((a2, b) => a2.localeCompare(b));
10253
+ if (validTypes.length === 0) return;
10254
+ const displayTypes = config.maxItems ? validTypes.slice(0, config.maxItems) : validTypes;
10255
+ if (config.showTitle) {
10256
+ const titleElement = document.createElement("div");
10257
+ titleElement.className = "fg-legend-title";
10258
+ titleElement.textContent = config.title || "Legend";
10259
+ root2.appendChild(titleElement);
10260
+ }
10261
+ displayTypes.forEach((type) => {
10262
+ const itemElement = createLegendItem(type, colorMap[type] || "#ccc");
10263
+ root2.appendChild(itemElement);
10264
+ });
10265
+ if (config.maxItems && validTypes.length > config.maxItems) {
10266
+ const moreElement = document.createElement("div");
10267
+ moreElement.className = "fg-legend-item fg-legend-more";
10268
+ moreElement.innerHTML = `
10269
+ <div class="fg-legend-dot" style="background-color: #999;"></div>
10270
+ <span class="fg-legend-label">and ${validTypes.length - config.maxItems} more...</span>
10271
+ `;
10272
+ root2.appendChild(moreElement);
10273
+ }
10274
+ }
10275
+ function createLegendItem(type, color2) {
10276
+ const itemElement = document.createElement("div");
10277
+ itemElement.className = "fg-legend-item";
10278
+ const dotElement = document.createElement("div");
10279
+ dotElement.className = "fg-legend-dot";
10280
+ dotElement.style.backgroundColor = color2;
10281
+ const labelElement = document.createElement("span");
10282
+ labelElement.className = "fg-legend-label";
10283
+ labelElement.textContent = type;
10284
+ itemElement.appendChild(dotElement);
10285
+ itemElement.appendChild(labelElement);
10286
+ return itemElement;
10287
+ }
10288
+ return { mount, destroy, update };
10289
+ }
10290
+
10291
+ // src/force-graph-wrapper/workers/physics-worker-manager.ts
10292
+ var PhysicsWorkerManagerImpl = class {
10293
+ worker = null;
10294
+ workerUrl = null;
10295
+ messageId = 0;
10296
+ pendingPromises = /* @__PURE__ */ new Map();
10297
+ promiseTimeouts = /* @__PURE__ */ new Map();
10298
+ constructor() {
10299
+ this.initializeWorker();
10300
+ }
10301
+ /**
10302
+ * Initialize the web worker
10303
+ */
10304
+ initializeWorker() {
10305
+ try {
10306
+ const workerScript = this.getWorkerScript();
10307
+ const blob = new Blob([workerScript], { type: "application/javascript" });
10308
+ this.workerUrl = URL.createObjectURL(blob);
10309
+ this.worker = new Worker(this.workerUrl);
10310
+ this.setupWorkerEventListeners();
10311
+ } catch (error) {
10312
+ console.warn("Physics Worker initialization failed:", error);
10313
+ this.worker = null;
10314
+ }
10315
+ }
10316
+ /**
10317
+ * Get the worker script content
10318
+ */
10319
+ getWorkerScript() {
10320
+ return `
10321
+ /**
10322
+ * Physics Web Worker for Force Graph
10323
+ * Runs D3 force simulation in a dedicated worker thread for consistent timing
10324
+ */
10325
+
10326
+ // Import D3 dependencies for force simulation
10327
+ importScripts('https://cdn.jsdelivr.net/npm/d3-dispatch@3/dist/d3-dispatch.min.js');
10328
+ importScripts('https://cdn.jsdelivr.net/npm/d3-quadtree@3/dist/d3-quadtree.min.js');
10329
+ importScripts('https://cdn.jsdelivr.net/npm/d3-timer@3/dist/d3-timer.min.js');
10330
+ importScripts('https://cdn.jsdelivr.net/npm/d3-force@3/dist/d3-force.min.js');
10331
+
10332
+ class PhysicsWorker {
10333
+ constructor() {
10334
+ this.simulation = null;
10335
+ this.nodes = [];
10336
+ this.links = [];
10337
+ this.isRunning = false;
10338
+ this.tickCount = 0;
10339
+ this.maxTicks = 300;
10340
+ this.intervalId = null; // Track interval for cleanup
10341
+ }
10342
+
10343
+ initializeSimulation(config) {
10344
+ const {
10345
+ nodes,
10346
+ links,
10347
+ width = 400,
10348
+ height = 300,
10349
+ forces = {},
10350
+ maxTicks = 300,
10351
+ alphaDecay = 0.0228,
10352
+ velocityDecay = 0.4
10353
+ } = config;
10354
+
10355
+ this.nodes = nodes.map(node => ({ ...node }));
10356
+ this.links = links.map(link => ({ ...link }));
10357
+ this.maxTicks = maxTicks;
10358
+ this.tickCount = 0;
10359
+
10360
+ this.simulation = d3.forceSimulation(this.nodes)
10361
+ .alphaDecay(alphaDecay)
10362
+ .velocityDecay(velocityDecay);
10363
+
10364
+ if (this.links.length > 0) {
10365
+ this.simulation.force('link',
10366
+ d3.forceLink(this.links)
10367
+ .id(d => d.id)
10368
+ .distance(forces.linkDistance || 30)
10369
+ .strength(forces.linkStrength || 1)
10370
+ );
10371
+ }
10372
+
10373
+ this.simulation.force('charge',
10374
+ d3.forceManyBody()
10375
+ .strength(forces.chargeStrength || -300)
10376
+ );
10377
+
10378
+ this.simulation.force('center',
10379
+ d3.forceCenter(width / 2, height / 2)
10380
+ .strength(forces.centerStrength || 1)
10381
+ );
10382
+
10383
+ if (forces.collisionRadius) {
10384
+ this.simulation.force('collision',
10385
+ d3.forceCollide(forces.collisionRadius)
10386
+ .strength(forces.collisionStrength || 0.7)
10387
+ );
10388
+ }
10389
+
10390
+ return {
10391
+ success: true,
10392
+ message: \`Simulation initialized with \${this.nodes.length} nodes and \${this.links.length} links\`
10393
+ };
10394
+ }
10395
+
10396
+ runSimulation() {
10397
+ if (!this.simulation || this.isRunning) {
10398
+ return { success: false, message: 'Simulation not initialized or already running' };
10399
+ }
10400
+
10401
+ // Clear any existing interval
10402
+ this.clearInterval();
10403
+
10404
+ this.isRunning = true;
10405
+ this.tickCount = 0;
10406
+
10407
+ this.intervalId = setInterval(() => {
10408
+ try {
10409
+ if (this.tickCount >= this.maxTicks || this.simulation.alpha() < 0.01) {
10410
+ this.completeSimulation();
10411
+ return;
10412
+ }
10413
+
10414
+ this.simulation.tick();
10415
+ this.tickCount++;
10416
+
10417
+ if (this.tickCount % 20 === 0) {
10418
+ postMessage({
10419
+ type: 'simulation_progress',
10420
+ data: {
10421
+ tickCount: this.tickCount,
10422
+ alpha: this.simulation.alpha(),
10423
+ progress: this.tickCount / this.maxTicks
10424
+ }
10425
+ });
10426
+ }
10427
+ } catch (error) {
10428
+ this.handleSimulationError(error);
10429
+ }
10430
+ }, 16);
10431
+
10432
+ return { success: true, message: 'Simulation started' };
10433
+ }
10434
+
10435
+ completeSimulation() {
10436
+ this.clearInterval();
10437
+ this.isRunning = false;
10438
+
10439
+ // Create final node data with memory-efficient copying
10440
+ const finalNodes = this.nodes.map(node => ({
10441
+ id: node.id,
10442
+ x: node.x || 0,
10443
+ y: node.y || 0,
10444
+ vx: node.vx || 0,
10445
+ vy: node.vy || 0
10446
+ }));
10447
+
10448
+ postMessage({
10449
+ type: 'simulation_complete',
10450
+ data: {
10451
+ nodes: finalNodes,
10452
+ tickCount: this.tickCount,
10453
+ finalAlpha: this.simulation ? this.simulation.alpha() : 0
10454
+ }
10455
+ });
10456
+
10457
+ // Clean up simulation resources
10458
+ this.cleanupSimulation();
10459
+ }
10460
+
10461
+ handleSimulationError(error) {
10462
+ this.clearInterval();
10463
+ this.isRunning = false;
10464
+ this.cleanupSimulation();
10465
+
10466
+ postMessage({
10467
+ type: 'error',
10468
+ data: {
10469
+ success: false,
10470
+ message: 'Simulation error: ' + error.message,
10471
+ stack: error.stack
10472
+ }
10473
+ });
10474
+ }
10475
+
10476
+ stopSimulation() {
10477
+ this.clearInterval();
10478
+
10479
+ if (this.simulation) {
10480
+ this.simulation.stop();
10481
+ this.isRunning = false;
10482
+ this.cleanupSimulation();
10483
+ return { success: true, message: 'Simulation stopped' };
10484
+ }
10485
+ return { success: false, message: 'No active simulation' };
10486
+ }
10487
+
10488
+ clearInterval() {
10489
+ if (this.intervalId) {
10490
+ clearInterval(this.intervalId);
10491
+ this.intervalId = null;
10492
+ }
10493
+ }
10494
+
10495
+ cleanupSimulation() {
10496
+ // Clear D3 simulation references
10497
+ if (this.simulation) {
10498
+ this.simulation.stop();
10499
+ this.simulation = null;
10500
+ }
10501
+
10502
+ // Clear node and link arrays to free memory
10503
+ this.nodes.length = 0;
10504
+ this.links.length = 0;
10505
+
10506
+ // Reset state
10507
+ this.tickCount = 0;
10508
+ this.isRunning = false;
10509
+ }
10510
+ }
10511
+
10512
+ const physicsWorker = new PhysicsWorker();
10513
+
10514
+ self.onmessage = function(event) {
10515
+ const { type, data } = event.data;
10516
+
10517
+ try {
10518
+ let result;
10519
+
10520
+ switch (type) {
10521
+ case 'initialize':
10522
+ result = physicsWorker.initializeSimulation(data);
10523
+ break;
10524
+ case 'run':
10525
+ result = physicsWorker.runSimulation();
10526
+ break;
10527
+ case 'stop':
10528
+ result = physicsWorker.stopSimulation();
10529
+ break;
10530
+ default:
10531
+ result = { success: false, message: \`Unknown command: \${type}\` };
10532
+ }
10533
+
10534
+ postMessage({
10535
+ type: 'response',
10536
+ data: result
10537
+ });
10538
+
10539
+ } catch (error) {
10540
+ postMessage({
10541
+ type: 'error',
10542
+ data: {
10543
+ success: false,
10544
+ message: error.message,
10545
+ stack: error.stack
10546
+ }
10547
+ });
10548
+ }
10549
+ };
10550
+ `;
10551
+ }
10552
+ /**
10553
+ * Set up worker event listeners
10554
+ */
10555
+ setupWorkerEventListeners() {
10556
+ if (!this.worker) return;
10557
+ this.worker.onmessage = (event) => {
10558
+ const { type, data } = event.data;
10559
+ switch (type) {
10560
+ case "response":
10561
+ case "simulation_complete":
10562
+ this.resolvePromise(data);
10563
+ break;
10564
+ case "simulation_progress":
10565
+ break;
10566
+ case "error":
10567
+ this.rejectPromise(new Error(data.message));
10568
+ break;
10569
+ }
10570
+ };
10571
+ this.worker.onerror = (error) => {
10572
+ console.error("Physics Worker error:", error);
10573
+ this.rejectPromise(new Error(`Worker error: ${error.message}`));
10574
+ };
10575
+ }
10576
+ /**
10577
+ * Send message to worker with promise handling
10578
+ */
10579
+ sendMessage(message) {
10580
+ return new Promise((resolve, reject) => {
10581
+ if (!this.worker) {
10582
+ reject(new Error("Physics Worker not available"));
10583
+ return;
10584
+ }
10585
+ const id2 = ++this.messageId;
10586
+ this.pendingPromises.set(id2, {
10587
+ resolve,
10588
+ reject
10589
+ });
10590
+ const timeoutId = window.setTimeout(() => {
10591
+ if (this.pendingPromises.has(id2)) {
10592
+ this.pendingPromises.delete(id2);
10593
+ this.promiseTimeouts.delete(id2);
10594
+ reject(new Error("Physics Worker timeout"));
10595
+ }
10596
+ }, 3e4);
10597
+ this.promiseTimeouts.set(id2, timeoutId);
10598
+ this.worker.postMessage({ ...message, id: id2 });
10599
+ });
10600
+ }
10601
+ /**
10602
+ * Resolve pending promise
10603
+ */
10604
+ resolvePromise(data) {
10605
+ const promises = Array.from(this.pendingPromises.values());
10606
+ this.clearAllTimeouts();
10607
+ this.pendingPromises.clear();
10608
+ promises.forEach(({ resolve }) => resolve(data));
10609
+ }
10610
+ /**
10611
+ * Reject pending promise
10612
+ */
10613
+ rejectPromise(error) {
10614
+ const promises = Array.from(this.pendingPromises.values());
10615
+ this.clearAllTimeouts();
10616
+ this.pendingPromises.clear();
10617
+ promises.forEach(({ reject }) => reject(error));
10618
+ }
10619
+ /**
10620
+ * Clear all promise timeouts
10621
+ */
10622
+ clearAllTimeouts() {
10623
+ for (const timeoutId of this.promiseTimeouts.values()) {
10624
+ window.clearTimeout(timeoutId);
10625
+ }
10626
+ this.promiseTimeouts.clear();
10627
+ }
10628
+ /**
10629
+ * Initialize physics simulation with given configuration
10630
+ */
10631
+ async initialize(config) {
10632
+ if (!this.worker) {
10633
+ console.warn("Physics Worker not available, falling back to main thread");
10634
+ return false;
10635
+ }
10636
+ try {
10637
+ const response = await this.sendMessage({
10638
+ type: "initialize",
10639
+ data: config
10640
+ });
10641
+ return response.success;
10642
+ } catch (error) {
10643
+ console.error("Failed to initialize physics simulation:", error);
10644
+ return false;
10645
+ }
10646
+ }
10647
+ /**
10648
+ * Run the physics simulation and return final node positions
10649
+ */
10650
+ async runSimulation() {
10651
+ if (!this.worker) {
10652
+ throw new Error("Physics Worker not available");
10653
+ }
10654
+ try {
10655
+ await this.sendMessage({
10656
+ type: "run"
10657
+ });
10658
+ return new Promise((resolve, reject) => {
10659
+ if (!this.worker) {
10660
+ reject(new Error("Physics Worker not available"));
10661
+ return;
10662
+ }
10663
+ const handleMessage = (event) => {
10664
+ const { type, data } = event.data;
10665
+ if (type === "simulation_complete") {
10666
+ this.worker?.removeEventListener("message", handleMessage);
10667
+ resolve(data.nodes);
10668
+ } else if (type === "error") {
10669
+ this.worker?.removeEventListener("message", handleMessage);
10670
+ reject(new Error(data.message));
10671
+ }
10672
+ };
10673
+ this.worker.addEventListener("message", handleMessage);
10674
+ });
10675
+ } catch (error) {
10676
+ console.error("Physics simulation failed:", error);
10677
+ throw error;
10678
+ }
10679
+ }
10680
+ /**
10681
+ * Stop the current simulation
10682
+ */
10683
+ stopSimulation() {
10684
+ if (this.worker) {
10685
+ this.worker.postMessage({ type: "stop" });
10686
+ }
10687
+ }
10688
+ /**
10689
+ * Terminate the worker and cleanup resources
10690
+ */
10691
+ terminate() {
10692
+ this.clearAllTimeouts();
10693
+ if (this.worker) {
10694
+ this.worker.terminate();
10695
+ this.worker = null;
10696
+ }
10697
+ if (this.workerUrl) {
10698
+ URL.revokeObjectURL(this.workerUrl);
10699
+ this.workerUrl = null;
10700
+ }
10701
+ this.pendingPromises.clear();
10702
+ this.messageId = 0;
10703
+ }
10704
+ /**
10705
+ * Check if web worker is available
10706
+ */
10707
+ isAvailable() {
10708
+ return this.worker !== null && typeof Worker !== "undefined";
10709
+ }
10710
+ };
10711
+ var physicsWorkerManager = new PhysicsWorkerManagerImpl();
10712
+
10713
+ // src/force-graph-wrapper/utils/performance-monitor.ts
10714
+ var PerformanceMonitor = class {
10715
+ metrics = {
10716
+ creation: 0,
10717
+ dataLoad: 0,
10718
+ firstRender: 0,
10719
+ render: 0,
10720
+ methodCalls: 0,
10721
+ memoryUsage: 0,
10722
+ nodeCount: 0,
10723
+ linkCount: 0,
10724
+ optimizedForNodeCount: 0,
10725
+ timestamp: Date.now()
10726
+ };
10727
+ // Internal detailed tracking
10728
+ methodCallsDetailed = /* @__PURE__ */ new Map();
10729
+ /**
10730
+ * Track execution time of any operation
10731
+ */
10732
+ track(operation, fn) {
10733
+ const start2 = performance.now();
10734
+ const result = fn();
10735
+ const duration = performance.now() - start2;
10736
+ if (!this.methodCallsDetailed.has(operation)) {
10737
+ this.methodCallsDetailed.set(operation, []);
10738
+ }
10739
+ this.methodCallsDetailed.get(operation).push(duration);
10740
+ this.metrics["methodCalls"]++;
10741
+ return result;
10742
+ }
10743
+ /**
10744
+ * Set specific metric values
10745
+ */
10746
+ setMetric(key, value) {
10747
+ if (key !== "timestamp") {
10748
+ this.metrics[key] = value;
10749
+ }
10750
+ }
10751
+ /**
10752
+ * Get current metrics snapshot
10753
+ */
10754
+ getMetrics() {
10755
+ if (typeof performance.memory !== "undefined") {
10756
+ const perfMemory = performance.memory;
10757
+ this.metrics["memoryUsage"] = perfMemory.usedJSHeapSize / 1024 / 1024;
10758
+ }
10759
+ return {
10760
+ ...this.metrics,
10761
+ timestamp: Date.now()
10762
+ };
10763
+ }
10764
+ /**
10765
+ * Get performance summary with statistics
10766
+ */
10767
+ getSummary() {
10768
+ const averages = {};
10769
+ const peaks = {};
10770
+ const warnings = [];
10771
+ this.methodCallsDetailed.forEach((times, operation) => {
10772
+ const avg = times.reduce((sum2, time) => sum2 + time, 0) / times.length;
10773
+ const peak = Math.max(...times);
10774
+ averages[operation] = Math.round(avg * 1e3) / 1e3;
10775
+ peaks[operation] = Math.round(peak * 1e3) / 1e3;
10776
+ if (avg > 100) {
10777
+ warnings.push(`${operation} averaging ${avg.toFixed(1)}ms - consider optimization`);
10778
+ }
10779
+ if (peak > 500) {
10780
+ warnings.push(`${operation} peaked at ${peak.toFixed(1)}ms - investigate bottleneck`);
10781
+ }
10782
+ });
10783
+ averages["creation"] = this.metrics["creation"];
10784
+ averages["dataLoad"] = this.metrics["dataLoad"];
10785
+ averages["firstRender"] = this.metrics["firstRender"];
10786
+ averages["render"] = this.metrics["render"];
10787
+ let nodeScaling = "Linear";
10788
+ if (this.metrics["nodeCount"] > 1e3 && this.metrics["dataLoad"] > 100) {
10789
+ nodeScaling = "Sub-optimal - may be O(n\xB2)";
10790
+ warnings.push("Data loading appears to scale poorly with node count");
10791
+ }
10792
+ return {
10793
+ averages,
10794
+ peaks,
10795
+ warnings,
10796
+ nodeScaling
10797
+ };
10798
+ }
10799
+ /**
10800
+ * Reset all metrics
10801
+ */
10802
+ reset() {
10803
+ this.metrics = {
10804
+ creation: 0,
10805
+ dataLoad: 0,
10806
+ firstRender: 0,
10807
+ render: 0,
10808
+ methodCalls: 0,
10809
+ memoryUsage: 0,
10810
+ nodeCount: 0,
10811
+ linkCount: 0,
10812
+ optimizedForNodeCount: 0,
10813
+ timestamp: Date.now()
10814
+ };
10815
+ this.methodCallsDetailed.clear();
10816
+ }
10817
+ /**
10818
+ * Log performance summary to console
10819
+ */
10820
+ logSummary() {
10821
+ const summary = this.getSummary();
10822
+ console.group("\u{1F680} Force-Graph Wrapper Performance Summary");
10823
+ console.log("\u{1F4CA} Averages:", summary.averages);
10824
+ console.log("\u26A1 Peaks:", summary.peaks);
10825
+ console.log("\u{1F4C8} Node Scaling:", summary.nodeScaling);
10826
+ console.log("\u{1F4BE} Memory Usage:", `${this.metrics["memoryUsage"].toFixed(2)} MB`);
10827
+ console.log("\u{1F4CF} Graph Size:", `${this.metrics["nodeCount"]} nodes, ${this.metrics["linkCount"]} links`);
10828
+ if (summary.warnings.length > 0) {
10829
+ console.warn("\u26A0\uFE0F Performance Warnings:");
10830
+ summary.warnings.forEach((warning) => console.warn(` \u2022 ${warning}`));
10831
+ } else {
10832
+ console.log("\u2705 No performance warnings");
10833
+ }
10834
+ console.groupEnd();
10835
+ }
10836
+ };
10837
+ var globalPerformanceMonitor = new PerformanceMonitor();
10838
+
10839
+ // src/force-graph-wrapper/core/rendering-performance-monitor.ts
10840
+ var RenderingPerformanceMonitor = class {
10841
+ frames = [];
10842
+ frameTimes = [];
10843
+ lastFrameTime = 0;
10844
+ renderCallCount = 0;
10845
+ canvasOpCount = 0;
10846
+ droppedFrameCount = 0;
10847
+ isMonitoring = false;
10848
+ animationFrameId = null;
10849
+ maxSamples = 120;
10850
+ // 2 seconds at 60fps
10851
+ targets = {
10852
+ targetFps: 60,
10853
+ maxFrameTime: 16.67,
10854
+ // 1000ms / 60fps
10855
+ maxDroppedFrames: 5,
10856
+ efficiencyThreshold: 0.8
10857
+ };
10858
+ nodeCount = 0;
10859
+ linkCount = 0;
10860
+ constructor(targets) {
10861
+ if (targets) {
10862
+ this.targets = { ...this.targets, ...targets };
10863
+ }
10864
+ }
10865
+ /**
10866
+ * Start monitoring rendering performance
10867
+ */
10868
+ startMonitoring() {
10869
+ if (this.isMonitoring) return;
10870
+ this.isMonitoring = true;
10871
+ this.frames = [];
10872
+ this.frameTimes = [];
10873
+ this.renderCallCount = 0;
10874
+ this.canvasOpCount = 0;
10875
+ this.droppedFrameCount = 0;
10876
+ this.lastFrameTime = performance.now();
10877
+ this.monitorFrame();
10878
+ }
10879
+ /**
10880
+ * Stop monitoring rendering performance
10881
+ */
10882
+ stopMonitoring() {
10883
+ this.isMonitoring = false;
10884
+ if (this.animationFrameId !== null) {
10885
+ cancelAnimationFrame(this.animationFrameId);
10886
+ this.animationFrameId = null;
10887
+ }
10888
+ }
10889
+ /**
10890
+ * Record a render call (called by wrapper during rendering)
10891
+ */
10892
+ recordRenderCall() {
10893
+ this.renderCallCount++;
10894
+ }
10895
+ /**
10896
+ * Record canvas operations (drawing calls, transforms, etc.)
10897
+ */
10898
+ recordCanvasOperation() {
10899
+ this.canvasOpCount++;
10900
+ }
10901
+ /**
10902
+ * Update node and link counts for efficiency calculations
10903
+ */
10904
+ updateCounts(nodeCount, linkCount) {
10905
+ this.nodeCount = nodeCount;
10906
+ this.linkCount = linkCount;
10907
+ }
10908
+ /**
10909
+ * Get current rendering metrics
10910
+ */
10911
+ getMetrics() {
10912
+ const now2 = performance.now();
10913
+ const currentFps = this.calculateCurrentFps();
10914
+ const averageFps = this.calculateAverageFps();
10915
+ const currentFrameTime = this.calculateCurrentFrameTime();
10916
+ const averageFrameTime = this.calculateAverageFrameTime();
10917
+ return {
10918
+ fps: currentFps,
10919
+ averageFps,
10920
+ frameTime: currentFrameTime,
10921
+ averageFrameTime,
10922
+ droppedFrames: this.droppedFrameCount,
10923
+ renderCalls: this.renderCallCount,
10924
+ canvasOperations: this.canvasOpCount,
10925
+ nodeCount: this.nodeCount,
10926
+ linkCount: this.linkCount,
10927
+ lastMeasurement: now2,
10928
+ renderingEfficiency: this.calculateEfficiency(averageFps, averageFrameTime),
10929
+ memoryUsage: this.getMemoryUsage()
10930
+ };
10931
+ }
10932
+ /**
10933
+ * Check if performance targets are being met
10934
+ */
10935
+ isPerformanceTargetMet() {
10936
+ const metrics = this.getMetrics();
10937
+ return metrics.averageFps >= this.targets.targetFps * 0.9 && // Allow 10% tolerance
10938
+ metrics.averageFrameTime <= this.targets.maxFrameTime * 1.1 && metrics.droppedFrames <= this.targets.maxDroppedFrames && metrics.renderingEfficiency >= this.targets.efficiencyThreshold;
10939
+ }
10940
+ /**
10941
+ * Get performance validation results
10942
+ */
10943
+ validatePerformance() {
10944
+ const metrics = this.getMetrics();
10945
+ const fpsTest = {
10946
+ expected: this.targets.targetFps,
10947
+ actual: metrics.averageFps,
10948
+ passed: metrics.averageFps >= this.targets.targetFps * 0.9
10949
+ };
10950
+ const frameTimeTest = {
10951
+ expected: this.targets.maxFrameTime,
10952
+ actual: metrics.averageFrameTime,
10953
+ passed: metrics.averageFrameTime <= this.targets.maxFrameTime * 1.1
10954
+ };
10955
+ const droppedFramesTest = {
10956
+ expected: this.targets.maxDroppedFrames,
10957
+ actual: metrics.droppedFrames,
10958
+ passed: metrics.droppedFrames <= this.targets.maxDroppedFrames
10959
+ };
10960
+ const efficiencyTest = {
10961
+ expected: this.targets.efficiencyThreshold,
10962
+ actual: metrics.renderingEfficiency,
10963
+ passed: metrics.renderingEfficiency >= this.targets.efficiencyThreshold
10964
+ };
10965
+ const results = {
10966
+ fpsTarget: fpsTest,
10967
+ frameTimeTarget: frameTimeTest,
10968
+ droppedFramesTarget: droppedFramesTest,
10969
+ efficiencyTarget: efficiencyTest
10970
+ };
10971
+ const passedTests = Object.values(results).filter((test) => test.passed).length;
10972
+ const overallScore = passedTests / Object.keys(results).length;
10973
+ const passed = overallScore >= 0.75;
10974
+ return {
10975
+ passed,
10976
+ results,
10977
+ overallScore
10978
+ };
10979
+ }
10980
+ /**
10981
+ * Reset performance counters
10982
+ */
10983
+ reset() {
10984
+ this.frames = [];
10985
+ this.frameTimes = [];
10986
+ this.renderCallCount = 0;
10987
+ this.canvasOpCount = 0;
10988
+ this.droppedFrameCount = 0;
10989
+ this.lastFrameTime = performance.now();
10990
+ }
10991
+ /**
10992
+ * Get rendering optimization recommendations
10993
+ */
10994
+ getOptimizationRecommendations() {
10995
+ const metrics = this.getMetrics();
10996
+ const recommendations = [];
10997
+ if (metrics.averageFps < this.targets.targetFps * 0.8) {
10998
+ recommendations.push("FPS is significantly below target - consider reducing node count or simplifying rendering");
10999
+ }
11000
+ if (metrics.averageFrameTime > this.targets.maxFrameTime * 1.5) {
11001
+ recommendations.push("Frame time is too high - optimize canvas operations or reduce complexity");
11002
+ }
11003
+ if (metrics.droppedFrames > this.targets.maxDroppedFrames * 2) {
11004
+ recommendations.push("Too many dropped frames - consider implementing frame skipping or LOD");
11005
+ }
11006
+ if (metrics.renderingEfficiency < 0.5) {
11007
+ recommendations.push("Low rendering efficiency - review canvas drawing operations");
11008
+ }
11009
+ if (metrics.canvasOperations / metrics.renderCalls > 1e3) {
11010
+ recommendations.push("High canvas operations per render - consider batching or caching");
11011
+ }
11012
+ if (recommendations.length === 0) {
11013
+ recommendations.push("Performance targets are being met - no optimizations needed");
11014
+ }
11015
+ return recommendations;
11016
+ }
11017
+ monitorFrame = () => {
11018
+ if (!this.isMonitoring) return;
11019
+ const currentTime = performance.now();
11020
+ const frameTime = currentTime - this.lastFrameTime;
11021
+ this.frameTimes.push(frameTime);
11022
+ if (this.frameTimes.length > this.maxSamples) {
11023
+ this.frameTimes.shift();
11024
+ }
11025
+ const fps = frameTime > 0 ? 1e3 / frameTime : 0;
11026
+ this.frames.push(fps);
11027
+ if (this.frames.length > this.maxSamples) {
11028
+ this.frames.shift();
11029
+ }
11030
+ if (frameTime > this.targets.maxFrameTime * 2) {
11031
+ this.droppedFrameCount++;
11032
+ }
11033
+ this.lastFrameTime = currentTime;
11034
+ this.animationFrameId = requestAnimationFrame(this.monitorFrame);
11035
+ };
11036
+ calculateCurrentFps() {
11037
+ if (this.frames.length === 0) return 0;
11038
+ return this.frames[this.frames.length - 1] || 0;
11039
+ }
11040
+ calculateAverageFps() {
11041
+ if (this.frames.length === 0) return 0;
11042
+ const sum2 = this.frames.reduce((a2, b) => a2 + b, 0);
11043
+ return sum2 / this.frames.length;
11044
+ }
11045
+ calculateCurrentFrameTime() {
11046
+ if (this.frameTimes.length === 0) return 0;
11047
+ return this.frameTimes[this.frameTimes.length - 1] || 0;
11048
+ }
11049
+ calculateAverageFrameTime() {
11050
+ if (this.frameTimes.length === 0) return 0;
11051
+ const sum2 = this.frameTimes.reduce((a2, b) => a2 + b, 0);
11052
+ return sum2 / this.frameTimes.length;
11053
+ }
11054
+ calculateEfficiency(fps, frameTime) {
11055
+ const fpsEfficiency = Math.min(fps / this.targets.targetFps, 1);
11056
+ const frameTimeEfficiency = Math.min(this.targets.maxFrameTime / frameTime, 1);
11057
+ return fpsEfficiency * 0.7 + frameTimeEfficiency * 0.3;
11058
+ }
11059
+ getMemoryUsage() {
11060
+ if (typeof performance.memory !== "undefined") {
11061
+ return performance.memory.usedJSHeapSize / 1024 / 1024;
11062
+ }
11063
+ return 0;
11064
+ }
11065
+ };
11066
+ var rendering_performance_monitor_default = RenderingPerformanceMonitor;
11067
+
11068
+ // src/force-graph-wrapper/core/canvas-optimizer.ts
11069
+ var CanvasOptimizer = class {
11070
+ canvas = null;
11071
+ context = null;
11072
+ imageDataCache = /* @__PURE__ */ new Map();
11073
+ pathCache = /* @__PURE__ */ new Map();
11074
+ renderQueue = [];
11075
+ isOptimizing = false;
11076
+ settings = {
11077
+ enableBatching: true,
11078
+ enableCaching: true,
11079
+ enableLOD: true,
11080
+ lodThreshold: 500,
11081
+ // Start LOD optimizations at 500+ nodes
11082
+ cacheSize: 100,
11083
+ batchSize: 50,
11084
+ cullingEnabled: true,
11085
+ cullingMargin: 100
11086
+ // pixels outside viewport to still render
11087
+ };
11088
+ viewport = {
11089
+ x: 0,
11090
+ y: 0,
11091
+ width: 800,
11092
+ height: 600,
11093
+ scale: 1
11094
+ };
11095
+ constructor(settings) {
11096
+ if (settings) {
11097
+ this.settings = { ...this.settings, ...settings };
11098
+ }
11099
+ }
11100
+ /**
11101
+ * Initialize optimizer with canvas element
11102
+ */
11103
+ initialize(canvas) {
11104
+ this.canvas = canvas;
11105
+ this.context = canvas.getContext("2d");
11106
+ this.updateViewport();
11107
+ }
11108
+ /**
11109
+ * Clean up all cached data and references
11110
+ */
11111
+ destroy() {
11112
+ console.log("\u{1F9F9} Cleaning up CanvasOptimizer...");
11113
+ this.imageDataCache.clear();
11114
+ this.pathCache.clear();
11115
+ this.renderQueue.length = 0;
11116
+ this.canvas = null;
11117
+ this.context = null;
11118
+ this.isOptimizing = false;
11119
+ console.log("\u2705 CanvasOptimizer cleanup completed");
11120
+ }
11121
+ /**
11122
+ * Update viewport information for culling calculations
11123
+ */
11124
+ updateViewport(x3, y3, scale) {
11125
+ if (!this.canvas) return;
11126
+ this.viewport = {
11127
+ x: x3 ?? this.viewport.x,
11128
+ y: y3 ?? this.viewport.y,
11129
+ width: this.canvas.width,
11130
+ height: this.canvas.height,
11131
+ scale: scale ?? this.viewport.scale
11132
+ };
11133
+ }
11134
+ /**
11135
+ * Optimize node rendering based on current settings and viewport
11136
+ */
11137
+ optimizeNodeRendering(nodes, renderFunction) {
11138
+ if (!this.context || !this.settings.enableLOD) {
11139
+ nodes.forEach((node) => renderFunction(node, 0));
11140
+ return;
11141
+ }
11142
+ const nodeCount = nodes.length;
11143
+ const shouldUseLOD = nodeCount > this.settings.lodThreshold;
11144
+ const lodLevel = shouldUseLOD ? this.calculateLODLevel(nodeCount, this.viewport.scale) : 0;
11145
+ if (this.settings.enableBatching) {
11146
+ this.batchRender(nodes, (node) => renderFunction(node, lodLevel));
11147
+ } else {
11148
+ const visibleNodes = this.settings.cullingEnabled ? this.cullNodes(nodes) : nodes;
11149
+ visibleNodes.forEach((node) => renderFunction(node, lodLevel));
11150
+ }
11151
+ }
11152
+ /**
11153
+ * Optimize link rendering with batching and culling
11154
+ */
11155
+ optimizeLinkRendering(links, renderFunction) {
11156
+ if (!this.context) {
11157
+ links.forEach((link) => renderFunction(link, 0));
11158
+ return;
11159
+ }
11160
+ const linkCount = links.length;
11161
+ const lodLevel = linkCount > this.settings.lodThreshold ? this.calculateLODLevel(linkCount, this.viewport.scale) : 0;
11162
+ if (this.settings.enableBatching) {
11163
+ this.batchRender(links, (link) => renderFunction(link, lodLevel));
11164
+ } else {
11165
+ const visibleLinks = this.settings.cullingEnabled ? this.cullLinks(links) : links;
11166
+ visibleLinks.forEach((link) => renderFunction(link, lodLevel));
11167
+ }
11168
+ }
11169
+ /**
11170
+ * Cache commonly used drawing operations
11171
+ */
11172
+ getCachedPath(key, createPath) {
11173
+ if (!this.settings.enableCaching) {
11174
+ return createPath();
11175
+ }
11176
+ if (this.pathCache.has(key)) {
11177
+ return this.pathCache.get(key);
11178
+ }
11179
+ const path = createPath();
11180
+ if (this.pathCache.size >= this.settings.cacheSize) {
11181
+ const firstKey = this.pathCache.keys().next().value;
11182
+ if (firstKey !== void 0) {
11183
+ this.pathCache.delete(firstKey);
11184
+ }
11185
+ }
11186
+ this.pathCache.set(key, path);
11187
+ return path;
11188
+ }
11189
+ /**
11190
+ * Cache image data for complex shapes or textures
11191
+ */
11192
+ getCachedImageData(key, createImageData) {
11193
+ if (!this.settings.enableCaching) {
11194
+ return createImageData();
11195
+ }
11196
+ if (this.imageDataCache.has(key)) {
11197
+ return this.imageDataCache.get(key);
11198
+ }
11199
+ const imageData = createImageData();
11200
+ if (this.imageDataCache.size >= this.settings.cacheSize) {
11201
+ const firstKey = this.imageDataCache.keys().next().value;
11202
+ if (firstKey !== void 0) {
11203
+ this.imageDataCache.delete(firstKey);
11204
+ }
11205
+ }
11206
+ this.imageDataCache.set(key, imageData);
11207
+ return imageData;
11208
+ }
11209
+ /**
11210
+ * Batch render operations for better performance
11211
+ */
11212
+ batchRender(items, renderFunction) {
11213
+ if (!this.context) return;
11214
+ for (let i = 0; i < items.length; i += this.settings.batchSize) {
11215
+ const batch = items.slice(i, i + this.settings.batchSize);
11216
+ const visibleItems = this.settings.cullingEnabled ? batch.filter((item) => this.isItemVisible(item)) : batch;
11217
+ this.context.save();
11218
+ visibleItems.forEach(renderFunction);
11219
+ this.context.restore();
11220
+ }
11221
+ }
11222
+ /**
11223
+ * Calculate appropriate LOD level based on node count and zoom
11224
+ */
11225
+ calculateLODLevel(itemCount, scale) {
11226
+ if (itemCount < this.settings.lodThreshold) return 0;
11227
+ if (scale > 2) return 0;
11228
+ if (scale > 1) return 1;
11229
+ if (itemCount < 1e3) return 1;
11230
+ if (itemCount < 2e3) return 2;
11231
+ return 3;
11232
+ }
11233
+ /**
11234
+ * Cull nodes outside the visible viewport
11235
+ */
11236
+ cullNodes(nodes) {
11237
+ return nodes.filter((node) => this.isNodeVisible(node));
11238
+ }
11239
+ /**
11240
+ * Cull links outside the visible viewport
11241
+ */
11242
+ cullLinks(links) {
11243
+ return links.filter((link) => this.isLinkVisible(link));
11244
+ }
11245
+ /**
11246
+ * Check if a node is visible in the current viewport
11247
+ */
11248
+ isNodeVisible(node) {
11249
+ if (!node.x || !node.y) return true;
11250
+ const margin = this.settings.cullingMargin;
11251
+ const { x: x3, y: y3, width, height, scale } = this.viewport;
11252
+ const worldX = (node.x - x3) * scale;
11253
+ const worldY = (node.y - y3) * scale;
11254
+ return worldX >= -margin && worldX <= width + margin && worldY >= -margin && worldY <= height + margin;
11255
+ }
11256
+ /**
11257
+ * Check if a link is visible in the current viewport
11258
+ */
11259
+ isLinkVisible(link) {
11260
+ const source = link.source;
11261
+ const target = link.target;
11262
+ if (!source || !target) return true;
11263
+ return this.isNodeVisible(source) || this.isNodeVisible(target) || this.lineIntersectsViewport(source, target);
11264
+ }
11265
+ /**
11266
+ * Generic item visibility check
11267
+ */
11268
+ isItemVisible(item) {
11269
+ const itemWithXY = item;
11270
+ const itemWithSourceTarget = item;
11271
+ if (itemWithXY.x !== void 0 && itemWithXY.y !== void 0) {
11272
+ return this.isNodeVisible(itemWithXY);
11273
+ }
11274
+ if (itemWithSourceTarget.source && itemWithSourceTarget.target) {
11275
+ return this.isLinkVisible(itemWithSourceTarget);
11276
+ }
11277
+ return true;
11278
+ }
11279
+ /**
11280
+ * Check if a line intersects with the viewport
11281
+ */
11282
+ lineIntersectsViewport(source, target) {
11283
+ const { x: x3, y: y3, width, height } = this.viewport;
11284
+ const margin = this.settings.cullingMargin;
11285
+ if (source.x === void 0 || source.y === void 0 || target.x === void 0 || target.y === void 0) {
11286
+ return true;
11287
+ }
11288
+ const minX = Math.min(source.x, target.x);
11289
+ const maxX = Math.max(source.x, target.x);
11290
+ const minY = Math.min(source.y, target.y);
11291
+ const maxY = Math.max(source.y, target.y);
11292
+ return !(maxX < x3 - margin || minX > x3 + width + margin || maxY < y3 - margin || minY > y3 + height + margin);
11293
+ }
11294
+ /**
11295
+ * Clear all caches
11296
+ */
11297
+ clearCaches() {
11298
+ this.imageDataCache.clear();
11299
+ this.pathCache.clear();
11300
+ }
11301
+ /**
11302
+ * Get cache statistics
11303
+ */
11304
+ getCacheStats() {
11305
+ return {
11306
+ pathCacheSize: this.pathCache.size,
11307
+ imageCacheSize: this.imageDataCache.size,
11308
+ pathCacheHitRate: 0,
11309
+ // Would need hit/miss tracking
11310
+ imageCacheHitRate: 0
11311
+ // Would need hit/miss tracking
11312
+ };
11313
+ }
11314
+ /**
11315
+ * Update optimization settings
11316
+ */
11317
+ updateSettings(newSettings) {
11318
+ this.settings = { ...this.settings, ...newSettings };
11319
+ }
11320
+ /**
11321
+ * Get current optimization settings
11322
+ */
11323
+ getSettings() {
11324
+ return { ...this.settings };
11325
+ }
11326
+ };
11327
+ var canvas_optimizer_default = CanvasOptimizer;
11328
+
11329
+ // src/force-graph-wrapper/core/force-graph-wrapper.ts
11330
+ var ForceGraphWrapper = class {
11331
+ // Core force-graph instance (strategic use of 'unknown' for library integration)
11332
+ forceGraph = null;
11333
+ // Container element
11334
+ container;
11335
+ // Performance monitor
11336
+ performanceMonitor;
11337
+ // Step 4: Advanced rendering performance monitoring
11338
+ renderingMonitor = null;
11339
+ canvasOptimizer = null;
11340
+ // Configuration
11341
+ config;
11342
+ // State tracking
11343
+ isInitialized = false;
11344
+ isDestroyed = false;
11345
+ isRenderingOptimized = false;
11346
+ enableVerboseLogging = false;
11347
+ // Disable by default for performance
11348
+ // Page visibility handling for deterministic layouts
11349
+ wasInitializedHidden = false;
11350
+ visibilityChangeHandler = null;
11351
+ // Element viewport visibility handling for deterministic physics
11352
+ wasInitializedOutOfView = false;
11353
+ intersectionObserver = null;
11354
+ // Web Worker physics for all graphs (deterministic layouts)
11355
+ webWorkerPhysicsCompleted = false;
11356
+ physicsTimeoutId = void 0;
11357
+ // Cached container dimensions when visible
11358
+ lastKnownDimensions = null;
11359
+ // Deferred fitView parameters for library-level handling
11360
+ deferredFitViewParams = null;
11361
+ pendingFitView = false;
11362
+ // Performance testing interval tracking for cleanup
11363
+ performanceTestInterval = null;
11364
+ // Canvas event listener for cleanup
11365
+ canvasClickHandler = null;
11366
+ // Export animation timeout for cleanup
11367
+ exportTimeoutId = null;
11368
+ // Graph controls UI
11369
+ controlsInstance = null;
11370
+ // Graph legends UI
11371
+ legendsInstance = null;
11372
+ /**
11373
+ * Helper method to safely cast and call methods on the force graph instance
11374
+ */
11375
+ getGraphInstance() {
11376
+ return this.forceGraph;
11377
+ }
11378
+ /**
11379
+ * Constructor - Step 1 Performance Test
11380
+ * Target: < 1ms creation time
11381
+ */
11382
+ constructor(container, config) {
11383
+ const creationStart = performance.now();
11384
+ if (!container || !(container instanceof HTMLElement)) {
11385
+ throw new Error("Invalid container: must be an HTMLElement");
11386
+ }
11387
+ this.container = container;
11388
+ this.performanceMonitor = new PerformanceMonitor();
11389
+ if (config?.enablePerformanceMonitoring) {
11390
+ this.renderingMonitor = new rendering_performance_monitor_default({
11391
+ targetFps: 60,
11392
+ maxFrameTime: 16.67,
11393
+ maxDroppedFrames: 5,
11394
+ efficiencyThreshold: 0.8
11395
+ });
11396
+ this.canvasOptimizer = new canvas_optimizer_default({
11397
+ enableBatching: false,
11398
+ // Keep it simple like react-force-graph
11399
+ enableCaching: false,
11400
+ enableLOD: false,
11401
+ lodThreshold: 500,
11402
+ cullingEnabled: false
11403
+ });
11404
+ }
11405
+ this.config = {
11406
+ container,
11407
+ width: container.clientWidth || 400,
11408
+ height: container.clientHeight || 300,
11409
+ backgroundColor: "#ffffff",
11410
+ enablePerformanceMonitoring: false,
11411
+ // Disable by default for better performance
11412
+ controls: {
11413
+ enabled: true,
11414
+ position: "bottom-left",
11415
+ orientation: "vertical"
11416
+ },
11417
+ legends: {
11418
+ enabled: true,
11419
+ position: "top-right",
11420
+ maxItems: 10
11421
+ },
11422
+ ...config
11423
+ };
11424
+ this.enableVerboseLogging = config?.enablePerformanceMonitoring === true && config?.performanceTargets?.methodCall !== void 0;
11425
+ this.setupPageVisibilityHandling();
11426
+ this.setupDeterministicPhysics();
11427
+ const creationTime = performance.now() - creationStart;
11428
+ this.performanceMonitor.setMetric("creation", creationTime);
11429
+ if (this.enableVerboseLogging) {
11430
+ this.validateCreationPerformance(creationTime);
11431
+ }
11432
+ }
11433
+ /**
11434
+ * Step 1 Performance Validation
11435
+ */
11436
+ validateCreationPerformance(_creationTime) {
11437
+ }
11438
+ /**
11439
+ * Setup automatic page visibility handling for deterministic layouts
11440
+ * Ensures consistent graph layouts regardless of tab visibility during initialization
11441
+ */
11442
+ setupPageVisibilityHandling() {
11443
+ if (this.config.handlePageVisibility === false) {
11444
+ return;
11445
+ }
11446
+ this.wasInitializedHidden = document.hidden;
11447
+ this.visibilityChangeHandler = () => {
11448
+ if (!document.hidden && this.isInitialized) {
11449
+ if (this.wasInitializedHidden) {
11450
+ if (this.enableVerboseLogging) {
11451
+ console.log("\u{1F504} Restarting simulation due to visibility change for layout consistency");
11452
+ }
11453
+ this.getGraphInstance().d3ReheatSimulation();
11454
+ this.wasInitializedHidden = false;
11455
+ }
11456
+ if (this.pendingFitView) {
11457
+ setTimeout(() => {
11458
+ if (this.enableVerboseLogging) {
11459
+ console.log("\u{1F3AF} Executing deferred fitView after visibility change");
11460
+ }
11461
+ this.zoomToFit(40, 300);
11462
+ }, 100);
11463
+ }
11464
+ }
11465
+ };
11466
+ document.addEventListener("visibilitychange", this.visibilityChangeHandler);
11467
+ }
11468
+ /**
11469
+ * Cleanup page visibility handling
11470
+ */
11471
+ cleanupPageVisibilityHandling() {
11472
+ if (this.visibilityChangeHandler) {
11473
+ document.removeEventListener("visibilitychange", this.visibilityChangeHandler);
11474
+ this.visibilityChangeHandler = null;
11475
+ }
11476
+ }
11477
+ /**
11478
+ * Setup deterministic physics handling for viewport visibility
11479
+ * Ensures consistent physics timing regardless of element visibility
11480
+ */
11481
+ setupDeterministicPhysics() {
11482
+ if (this.config.deterministicLayout === false) {
11483
+ return;
11484
+ }
11485
+ const isInViewport = this.isElementInViewport(this.container);
11486
+ this.wasInitializedOutOfView = !isInViewport;
11487
+ if (this.enableVerboseLogging) {
11488
+ const rect = this.container.getBoundingClientRect();
11489
+ console.log(`\u{1F4CD} Graph initialized:`, {
11490
+ wasInitializedOutOfView: this.wasInitializedOutOfView,
11491
+ isInViewport,
11492
+ containerDimensions: `${this.container.clientWidth}x${this.container.clientHeight}`,
11493
+ boundingRect: {
11494
+ top: rect.top,
11495
+ bottom: rect.bottom,
11496
+ left: rect.left,
11497
+ right: rect.right
11498
+ },
11499
+ windowSize: `${window.innerWidth}x${window.innerHeight}`
11500
+ });
11501
+ }
11502
+ if (typeof IntersectionObserver !== "undefined") {
11503
+ const scrollableParent = this.findScrollableParent(this.container);
11504
+ this.intersectionObserver = new IntersectionObserver((entries) => {
11505
+ entries.forEach((entry) => {
11506
+ if (entry.isIntersecting && this.isInitialized) {
11507
+ if (this.wasInitializedOutOfView) {
11508
+ if (this.enableVerboseLogging) {
11509
+ console.log("\u{1F504} Element entered viewport - ensuring consistent physics");
11510
+ }
11511
+ if (this.physicsTimeoutId) {
11512
+ window.clearTimeout(this.physicsTimeoutId);
11513
+ this.physicsTimeoutId = void 0;
11514
+ }
11515
+ if (!this.webWorkerPhysicsCompleted) {
11516
+ this.runWebWorkerPhysics();
11517
+ }
11518
+ this.wasInitializedOutOfView = false;
11519
+ }
11520
+ if (this.pendingFitView) {
11521
+ setTimeout(() => {
11522
+ if (this.pendingFitView) {
11523
+ if (this.enableVerboseLogging) {
11524
+ console.log("\u{1F3AF} Executing deferred fitView after entering viewport");
11525
+ }
11526
+ this.zoomToFit(40, 300);
11527
+ }
11528
+ }, 100);
11529
+ }
11530
+ }
11531
+ });
11532
+ }, {
11533
+ root: scrollableParent,
11534
+ // Use found scrollable parent as root
11535
+ threshold: 0.1,
11536
+ // Trigger when 10% visible
11537
+ rootMargin: "100px"
11538
+ // Larger margin like Angular component
11539
+ });
11540
+ this.intersectionObserver.observe(this.container);
11541
+ }
11542
+ }
11543
+ /**
11544
+ * Find the scrollable parent container for intersection observer
11545
+ * Similar to Angular component approach but more generic
11546
+ */
11547
+ findScrollableParent(element) {
11548
+ let current = element.parentElement;
11549
+ while (current && current !== document.body) {
11550
+ const style = window.getComputedStyle(current);
11551
+ const overflow = style.overflow + style.overflowY + style.overflowX;
11552
+ if (/(auto|scroll)/.test(overflow) && (current.scrollHeight > current.clientHeight || current.scrollWidth > current.clientWidth)) {
11553
+ if (this.enableVerboseLogging) {
11554
+ console.log("\u{1F4CD} Found scrollable parent:", current.className || current.tagName);
11555
+ }
11556
+ return current;
11557
+ }
11558
+ current = current.parentElement;
11559
+ }
11560
+ if (this.enableVerboseLogging) {
11561
+ console.log("\u{1F4CD} No scrollable parent found, using viewport as root");
11562
+ }
11563
+ return null;
11564
+ }
11565
+ /**
11566
+ * Setup deferred fitView mechanism using IntersectionObserver
11567
+ * This handles library-level viewport-aware fitView
11568
+ */
11569
+ setupDeferredFitView() {
11570
+ if (this.intersectionObserver || !this.container || !this.deferredFitViewParams) {
11571
+ return;
11572
+ }
11573
+ if (this.enableVerboseLogging) {
11574
+ console.log("\u{1F3AF} Setting up library-level deferred fitView");
11575
+ }
11576
+ this.intersectionObserver = new IntersectionObserver((entries) => {
11577
+ entries.forEach((entry) => {
11578
+ if (entry.isIntersecting && this.pendingFitView && this.deferredFitViewParams) {
11579
+ if (this.enableVerboseLogging) {
11580
+ console.log("\u{1F3AF} Library executing deferred fitView (now visible)");
11581
+ }
11582
+ const { padding, duration } = this.deferredFitViewParams;
11583
+ this.pendingFitView = false;
11584
+ this.deferredFitViewParams = null;
11585
+ if (this.intersectionObserver) {
11586
+ this.intersectionObserver.disconnect();
11587
+ this.intersectionObserver = null;
11588
+ }
11589
+ requestAnimationFrame(() => {
11590
+ this.executeFitViewNow(padding, duration);
11591
+ });
11592
+ }
11593
+ });
11594
+ }, {
11595
+ threshold: 0.1,
11596
+ rootMargin: "50px"
11597
+ // Start checking slightly before fully visible
11598
+ });
11599
+ this.intersectionObserver.observe(this.container);
11600
+ }
11601
+ /**
11602
+ * Execute fitView immediately (bypass visibility checks)
11603
+ */
11604
+ executeFitViewNow(padding, duration) {
11605
+ if (!this.forceGraph || !this.container) return;
11606
+ const containerWidth = this.container.clientWidth;
11607
+ const containerHeight = this.container.clientHeight;
11608
+ if (containerWidth === 0 || containerHeight === 0) {
11609
+ if (this.enableVerboseLogging) {
11610
+ console.warn("\u26A0\uFE0F Still no valid dimensions for deferred fitView");
11611
+ }
11612
+ return;
11613
+ }
11614
+ this.cacheContainerDimensions();
11615
+ const bbox = this.getGraphInstance().getGraphBbox();
11616
+ const width = bbox.x[1] - bbox.x[0];
11617
+ const height = bbox.y[1] - bbox.y[0];
11618
+ const centerX = (bbox.x[0] + bbox.x[1]) / 2;
11619
+ const centerY = (bbox.y[0] + bbox.y[1]) / 2;
11620
+ const viewportWidth = containerWidth - padding * 2;
11621
+ const viewportHeight = containerHeight - padding * 2;
11622
+ if (width > 0 && height > 0) {
11623
+ const scale = Math.min(viewportWidth / width, viewportHeight / height);
11624
+ this.getGraphInstance().centerAt(centerX, centerY, duration);
11625
+ this.getGraphInstance().zoom(scale, duration);
11626
+ if (this.enableVerboseLogging) {
11627
+ console.log("\u2705 Library deferred fitView executed successfully");
11628
+ }
11629
+ }
11630
+ }
11631
+ /**
11632
+ * Cleanup deferred fitView intersection observer
11633
+ */
11634
+ cleanupDeferredFitView() {
11635
+ if (this.intersectionObserver) {
11636
+ this.intersectionObserver.disconnect();
11637
+ this.intersectionObserver = null;
11638
+ }
11639
+ this.deferredFitViewParams = null;
11640
+ this.pendingFitView = false;
11641
+ }
11642
+ /**
11643
+ * Cleanup performance test interval
11644
+ */
11645
+ cleanupPerformanceTest() {
11646
+ if (this.performanceTestInterval) {
11647
+ clearInterval(this.performanceTestInterval);
11648
+ this.performanceTestInterval = null;
11649
+ }
11650
+ }
11651
+ /**
11652
+ * Cleanup export animation timeout
11653
+ */
11654
+ cleanupExportTimeout() {
11655
+ if (this.exportTimeoutId) {
11656
+ clearTimeout(this.exportTimeoutId);
11657
+ this.exportTimeoutId = null;
11658
+ }
11659
+ }
11660
+ /**
11661
+ * Cleanup canvas event listeners
11662
+ */
11663
+ cleanupCanvasEventListeners() {
11664
+ if (this.canvasClickHandler && this.container) {
11665
+ const canvas = this.container.querySelector("canvas");
11666
+ if (canvas) {
11667
+ canvas.removeEventListener("click", this.canvasClickHandler);
11668
+ }
11669
+ this.canvasClickHandler = null;
11670
+ }
11671
+ }
11672
+ /**
11673
+ * Check if element is currently visible (even partially) in viewport
11674
+ */
11675
+ isElementInViewport(element) {
11676
+ const rect = element.getBoundingClientRect();
11677
+ const windowHeight = window.innerHeight || document.documentElement.clientHeight;
11678
+ const windowWidth = window.innerWidth || document.documentElement.clientWidth;
11679
+ return rect.bottom > 0 && // Not above viewport
11680
+ rect.right > 0 && // Not to the left of viewport
11681
+ rect.top < windowHeight && // Not below viewport
11682
+ rect.left < windowWidth;
11683
+ }
11684
+ /**
11685
+ * Cache container dimensions when they're valid (non-zero)
11686
+ */
11687
+ cacheContainerDimensions() {
11688
+ const width = this.container.clientWidth;
11689
+ const height = this.container.clientHeight;
11690
+ if (width > 0 && height > 0) {
11691
+ this.lastKnownDimensions = { width, height };
11692
+ if (this.enableVerboseLogging) {
11693
+ console.log("\u{1F4D0} Cached container dimensions:", this.lastKnownDimensions);
11694
+ }
11695
+ }
11696
+ }
11697
+ /**
11698
+ * Check if container has valid dimensions and cache them
11699
+ */
11700
+ hasValidDimensions() {
11701
+ const width = this.container.clientWidth;
11702
+ const height = this.container.clientHeight;
11703
+ if (width > 0 && height > 0) {
11704
+ this.cacheContainerDimensions();
11705
+ return true;
11706
+ }
11707
+ return false;
11708
+ }
11709
+ /**
11710
+ * Run deterministic physics using Web Worker for off-screen graphs only
11711
+ */
11712
+ async runWebWorkerPhysics() {
11713
+ if (!this.config.graphData || !this.container || this.webWorkerPhysicsCompleted) return;
11714
+ const { nodes, links } = this.config.graphData;
11715
+ if (!nodes || nodes.length === 0) return;
11716
+ if (this.physicsTimeoutId) {
11717
+ window.clearTimeout(this.physicsTimeoutId);
11718
+ this.physicsTimeoutId = void 0;
11719
+ }
11720
+ try {
11721
+ if (!physicsWorkerManager.isAvailable()) {
11722
+ if (this.enableVerboseLogging) {
11723
+ console.warn("\u26A0\uFE0F Web Worker not available, using main thread physics");
11724
+ }
11725
+ return;
11726
+ }
11727
+ const containerWidth = this.container.clientWidth || this.config.width || 800;
11728
+ const containerHeight = this.container.clientHeight || this.config.height || 600;
11729
+ const config = {
11730
+ nodes: nodes.map((node) => ({ ...node })),
11731
+ links: links ? links.map((link) => ({ ...link })) : [],
11732
+ width: containerWidth,
11733
+ height: containerHeight,
11734
+ maxTicks: 300,
11735
+ // Deterministic tick count for off-screen graphs
11736
+ alphaDecay: this.config.d3AlphaDecay || 0.0228,
11737
+ // Use wrapper config or default
11738
+ velocityDecay: this.config.d3VelocityDecay || 0.4,
11739
+ // Use wrapper config or default
11740
+ forces: {}
11741
+ // Let worker use force-graph defaults
11742
+ };
11743
+ if (this.enableVerboseLogging) {
11744
+ console.log("\u{1F3AF} Web Worker physics config:", {
11745
+ containerDimensions: `${containerWidth}x${containerHeight}`,
11746
+ configDimensions: `${this.config.width || "auto"}x${this.config.height || "auto"}`,
11747
+ nodeCount: nodes.length
11748
+ });
11749
+ }
11750
+ if (this.enableVerboseLogging) {
11751
+ console.log("\u{1F504} Running Web Worker physics for ALL graphs (visible & hidden)...");
11752
+ }
11753
+ const initialized = await physicsWorkerManager.initialize(config);
11754
+ if (!initialized) {
11755
+ throw new Error("Failed to initialize Web Worker physics");
11756
+ }
11757
+ const finalNodes = await physicsWorkerManager.runSimulation();
11758
+ this.applyWebWorkerResults(finalNodes);
11759
+ this.webWorkerPhysicsCompleted = true;
11760
+ if (this.enableVerboseLogging) {
11761
+ console.log(`\u2705 Web Worker physics completed for ALL graphs with ${finalNodes.length} nodes`);
11762
+ }
11763
+ } catch (error) {
11764
+ if (this.enableVerboseLogging) {
11765
+ console.warn("\u26A0\uFE0F Web Worker physics failed:", error);
11766
+ }
11767
+ }
11768
+ }
11769
+ /**
11770
+ * Apply Web Worker results to force-graph instance WITHOUT disrupting interactions
11771
+ */
11772
+ applyWebWorkerResults(physicsNodes) {
11773
+ if (!this.forceGraph || !this.config.graphData?.nodes) return;
11774
+ const nodeMap = new Map(physicsNodes.map((node) => [node.id, node]));
11775
+ this.config.graphData.nodes.forEach((node) => {
11776
+ const physicsNode = nodeMap.get(node.id);
11777
+ if (physicsNode) {
11778
+ if (typeof node.fx === "undefined") {
11779
+ node.x = physicsNode.x;
11780
+ node.y = physicsNode.y;
11781
+ }
11782
+ }
11783
+ });
11784
+ if (this.forceGraph) {
11785
+ const graphInstance = this.getGraphInstance();
11786
+ graphInstance.graphData(this.config.graphData);
11787
+ if (!document.hidden && this.isElementInViewport(this.container)) {
11788
+ graphInstance.d3ReheatSimulation();
11789
+ }
11790
+ }
11791
+ this.triggerKapsuleUpdate();
11792
+ if (this.enableVerboseLogging) {
11793
+ console.log("\u2705 Applied Web Worker results without disrupting interactions");
11794
+ }
11795
+ }
11796
+ /**
11797
+ * Cleanup deterministic physics handling
11798
+ */
11799
+ cleanupDeterministicPhysics() {
11800
+ if (this.physicsTimeoutId) {
11801
+ window.clearTimeout(this.physicsTimeoutId);
11802
+ this.physicsTimeoutId = void 0;
11803
+ }
11804
+ if (this.intersectionObserver) {
11805
+ this.intersectionObserver.disconnect();
11806
+ this.intersectionObserver = null;
11807
+ }
11808
+ }
11809
+ /**
11810
+ * Initialize the underlying force-graph instance
11811
+ * Step 2: Data loading with performance validation
11812
+ * Target: Linear scaling, < 10ms per 1000 nodes
11813
+ */
11814
+ initializeForceGraph() {
11815
+ if (this.isInitialized || this.isDestroyed) {
11816
+ return;
11817
+ }
11818
+ const initStart = performance.now();
11819
+ try {
11820
+ this.forceGraph = (0, import_force_graph.default)()(this.container);
11821
+ if (!this.forceGraph) {
11822
+ throw new Error("Failed to create force-graph instance");
11823
+ }
11824
+ this.applyConfiguration();
11825
+ this.isInitialized = true;
11826
+ if (this.config.enablePerformanceMonitoring) {
11827
+ this.setupRenderingMonitoring();
11828
+ }
11829
+ const initTime = performance.now() - initStart;
11830
+ this.performanceMonitor.setMetric("firstRender", initTime);
11831
+ if (this.config.enablePerformanceMonitoring) {
11832
+ this.validateInitializationPerformance(initTime);
11833
+ }
11834
+ } catch (error) {
11835
+ this.isInitialized = false;
11836
+ throw new Error(`Failed to initialize force-graph: ${error}`);
11837
+ }
11838
+ }
11839
+ /**
11840
+ * Apply configuration to force-graph instance
11841
+ * Step 2: Performance-optimized configuration application
11842
+ */
11843
+ applyConfiguration() {
11844
+ if (!this.forceGraph || !this.config) return;
11845
+ const graph = this.getGraphInstance();
11846
+ graph.width(this.config.width || 400).height(this.config.height || 300).backgroundColor(this.config.backgroundColor || "#ffffff").autoPauseRedraw(this.config.autoPauseRedraw ?? true);
11847
+ if (this.config.d3AlphaDecay !== void 0) {
11848
+ graph.d3AlphaDecay(this.config.d3AlphaDecay);
11849
+ }
11850
+ if (this.config.d3VelocityDecay !== void 0) {
11851
+ graph.d3VelocityDecay(this.config.d3VelocityDecay);
11852
+ }
11853
+ if (this.config.d3AlphaMin !== void 0) {
11854
+ graph.d3AlphaMin(this.config.d3AlphaMin);
11855
+ }
11856
+ if (this.config.cooldownTime !== void 0) {
11857
+ graph.cooldownTime(this.config.cooldownTime);
11858
+ }
11859
+ if (this.config.cooldownTicks !== void 0) {
11860
+ graph.cooldownTicks(this.config.cooldownTicks);
11861
+ }
11862
+ if (this.config.nodeColor) {
11863
+ graph.nodeColor(this.config.nodeColor);
11864
+ }
11865
+ if (this.config.nodeVal) {
11866
+ graph.nodeVal(this.config.nodeVal);
11867
+ }
11868
+ if (this.config.nodeRelSize !== void 0) {
11869
+ graph.nodeRelSize(this.config.nodeRelSize);
11870
+ }
11871
+ if (this.config.nodeLabel) {
11872
+ graph.nodeLabel(this.config.nodeLabel);
11873
+ }
11874
+ if (this.config.nodeVisibility) {
11875
+ graph.nodeVisibility(this.config.nodeVisibility);
11876
+ }
11877
+ if (this.config.nodeCanvasObjectMode) {
11878
+ graph.nodeCanvasObjectMode(this.config.nodeCanvasObjectMode);
11879
+ }
11880
+ if (this.config.linkColor) {
11881
+ graph.linkColor(this.config.linkColor);
11882
+ }
11883
+ if (this.config.linkWidth) {
11884
+ graph.linkWidth(this.config.linkWidth);
11885
+ }
11886
+ if (this.config.linkLabel) {
11887
+ graph.linkLabel(this.config.linkLabel);
11888
+ }
11889
+ if (this.config.linkVisibility) {
11890
+ graph.linkVisibility(this.config.linkVisibility);
11891
+ }
11892
+ if (this.config.linkDirectionalArrowLength !== void 0) {
11893
+ graph.linkDirectionalArrowLength(this.config.linkDirectionalArrowLength);
11894
+ }
11895
+ if (this.config.linkDirectionalArrowColor) {
11896
+ graph.linkDirectionalArrowColor(this.config.linkDirectionalArrowColor);
11897
+ }
11898
+ if (this.config.linkDirectionalArrowRelPos !== void 0) {
11899
+ graph.linkDirectionalArrowRelPos(this.config.linkDirectionalArrowRelPos);
11900
+ }
11901
+ if (this.config.linkDirectionalParticles !== void 0) {
11902
+ graph.linkDirectionalParticles(this.config.linkDirectionalParticles);
11903
+ }
11904
+ if (this.config.linkDirectionalParticleSpeed !== void 0) {
11905
+ graph.linkDirectionalParticleSpeed(this.config.linkDirectionalParticleSpeed);
11906
+ }
11907
+ if (this.config.linkDirectionalParticleWidth !== void 0) {
11908
+ graph.linkDirectionalParticleWidth(this.config.linkDirectionalParticleWidth);
11909
+ }
11910
+ if (this.config.linkDirectionalParticleColor) {
11911
+ graph.linkDirectionalParticleColor(this.config.linkDirectionalParticleColor);
11912
+ }
11913
+ if (this.config.linkCurvature !== void 0) {
11914
+ graph.linkCurvature(this.config.linkCurvature);
11915
+ }
11916
+ if (this.config.linkCanvasObjectMode) {
11917
+ graph.linkCanvasObjectMode(this.config.linkCanvasObjectMode);
11918
+ }
11919
+ if (this.config.enableNodeDrag !== void 0) {
11920
+ graph.enableNodeDrag(this.config.enableNodeDrag);
11921
+ }
11922
+ if (this.config.enableZoomInteraction !== void 0) {
11923
+ graph.enableZoomInteraction(this.config.enableZoomInteraction);
11924
+ }
11925
+ if (this.config.enablePanInteraction !== void 0) {
11926
+ graph.enablePanInteraction(this.config.enablePanInteraction);
11927
+ }
11928
+ if (this.config.enablePerformanceMonitoring) {
11929
+ this.setupRenderingMonitoring();
11930
+ }
11931
+ if (this.config.onNodeClick) {
11932
+ graph.onNodeClick(this.config.onNodeClick);
11933
+ }
11934
+ if (this.config.onNodeHover) {
11935
+ graph.onNodeHover(this.config.onNodeHover);
11936
+ }
11937
+ if (this.config.onLinkClick) {
11938
+ graph.onLinkClick(this.config.onLinkClick);
11939
+ }
11940
+ if (this.config.onLinkHover) {
11941
+ graph.onLinkHover(this.config.onLinkHover);
11942
+ }
11943
+ if (this.config.onRenderFramePre) {
11944
+ graph.onRenderFramePre(this.config.onRenderFramePre);
11945
+ }
11946
+ if (this.config.onRenderFramePost) {
11947
+ graph.onRenderFramePost(this.config.onRenderFramePost);
11948
+ }
11949
+ if (this.config.onEngineTick) {
11950
+ graph.onEngineTick(this.config.onEngineTick);
11951
+ }
11952
+ if (this.config.onEngineStop) {
11953
+ graph.onEngineStop(this.config.onEngineStop);
11954
+ }
11955
+ }
11956
+ /**
11957
+ * Step 2 Performance Validation for Initialization
11958
+ */
11959
+ validateInitializationPerformance(_initTime) {
11960
+ }
11961
+ /**
11962
+ * Validate data loading performance based on node/link count
11963
+ * Step 2: Linear scaling validation
11964
+ */
11965
+ validateDataLoadingPerformance(_loadTime, nodeCount, linkCount) {
11966
+ this.performanceMonitor.setMetric("nodeCount", nodeCount);
11967
+ this.performanceMonitor.setMetric("linkCount", linkCount);
11968
+ }
11969
+ // =============================================================================
11970
+ // PUBLIC API - ForceGraphMethods
11971
+ // =============================================================================
11972
+ d3ReheatSimulation() {
11973
+ if (!this.isInitialized) this.initializeForceGraph();
11974
+ if (this.forceGraph) {
11975
+ this.getGraphInstance().d3ReheatSimulation();
11976
+ }
11977
+ if (this.enableVerboseLogging) {
11978
+ console.log("\u2705 d3ReheatSimulation called");
11979
+ }
11980
+ }
11981
+ stopAnimation() {
11982
+ if (!this.isInitialized) return;
11983
+ const start2 = performance.now();
11984
+ if (this.forceGraph) {
11985
+ this.getGraphInstance().pauseAnimation();
11986
+ }
11987
+ const duration = performance.now() - start2;
11988
+ if (this.config.enablePerformanceMonitoring) {
11989
+ console.log(`\u2705 stopAnimation completed in ${duration.toFixed(3)}ms`);
11990
+ }
11991
+ }
11992
+ pauseAnimation() {
11993
+ if (!this.isInitialized) return;
11994
+ const start2 = performance.now();
11995
+ if (this.forceGraph) {
11996
+ this.getGraphInstance().pauseAnimation();
11997
+ }
11998
+ const duration = performance.now() - start2;
11999
+ if (this.config.enablePerformanceMonitoring) {
12000
+ console.log(`\u2705 pauseAnimation completed in ${duration.toFixed(3)}ms`);
12001
+ }
12002
+ }
12003
+ resumeAnimation() {
12004
+ if (!this.isInitialized) return;
12005
+ const start2 = performance.now();
12006
+ if (this.forceGraph) {
12007
+ this.getGraphInstance().resumeAnimation();
12008
+ }
12009
+ const duration = performance.now() - start2;
12010
+ if (this.config.enablePerformanceMonitoring) {
12011
+ console.log(`\u2705 resumeAnimation completed in ${duration.toFixed(3)}ms`);
12012
+ }
12013
+ }
12014
+ centerAt(x3, y3, duration) {
12015
+ if (!this.isInitialized) this.initializeForceGraph();
12016
+ const start2 = performance.now();
12017
+ if (this.forceGraph) {
12018
+ this.getGraphInstance().centerAt(x3, y3, duration);
12019
+ }
12020
+ const callDuration = performance.now() - start2;
12021
+ if (this.config.enablePerformanceMonitoring) {
12022
+ console.log(`\u2705 centerAt(${x3}, ${y3}) completed in ${callDuration.toFixed(3)}ms`);
12023
+ }
12024
+ }
12025
+ zoom(scale, duration) {
12026
+ if (!this.isInitialized) this.initializeForceGraph();
12027
+ const start2 = performance.now();
12028
+ let result = void 0;
12029
+ if (this.forceGraph) {
12030
+ if (scale === void 0) {
12031
+ result = this.getGraphInstance().zoom();
12032
+ } else {
12033
+ this.getGraphInstance().zoom(scale, duration);
12034
+ result = void 0;
12035
+ }
12036
+ } else if (scale === void 0) {
12037
+ result = 1;
12038
+ }
12039
+ const callDuration = performance.now() - start2;
12040
+ if (this.config.enablePerformanceMonitoring) {
12041
+ if (scale === void 0) {
12042
+ console.log(`\u2705 zoom() getter completed in ${callDuration.toFixed(3)}ms`);
12043
+ } else {
12044
+ console.log(`\u2705 zoom(${scale}) setter completed in ${callDuration.toFixed(3)}ms`);
12045
+ }
12046
+ }
12047
+ return result;
12048
+ }
12049
+ zoomToFit(padding, duration) {
12050
+ if (!this.isInitialized) this.initializeForceGraph();
12051
+ const start2 = performance.now();
12052
+ const containerWidth = this.container.clientWidth;
12053
+ const containerHeight = this.container.clientHeight;
12054
+ const isInViewport = this.container ? this.isElementInViewport(this.container) : false;
12055
+ const isVisible = !document.hidden && isInViewport;
12056
+ const hasValidDimensions = containerWidth > 0 && containerHeight > 0;
12057
+ let bboxValid = false;
12058
+ if (this.forceGraph) {
12059
+ const bbox = this.getGraphInstance().getGraphBbox();
12060
+ bboxValid = bbox && bbox.x[1] - bbox.x[0] > 0 && bbox.y[1] - bbox.y[0] > 0;
12061
+ }
12062
+ if (this.enableVerboseLogging) {
12063
+ console.log("\u{1F3AF} Library zoomToFit called:", {
12064
+ containerDimensions: `${containerWidth}x${containerHeight}`,
12065
+ isInViewport,
12066
+ isVisible,
12067
+ hasValidDimensions,
12068
+ bboxValid,
12069
+ documentHidden: document.hidden,
12070
+ padding: padding || 40,
12071
+ duration: duration || 300
12072
+ });
12073
+ }
12074
+ if (!isVisible || !hasValidDimensions || !bboxValid) {
12075
+ this.deferredFitViewParams = { padding: padding || 40, duration: duration || 300 };
12076
+ this.pendingFitView = true;
12077
+ if (this.enableVerboseLogging) {
12078
+ console.log("\u{1F3AF} Library DEFERRING fitView:", {
12079
+ reason: !isVisible ? "not visible" : !hasValidDimensions ? "invalid dimensions" : "invalid bbox"
12080
+ });
12081
+ }
12082
+ this.setupDeferredFitView();
12083
+ return;
12084
+ }
12085
+ if (this.forceGraph && this.container) {
12086
+ this.cacheContainerDimensions();
12087
+ const bbox = this.getGraphInstance().getGraphBbox();
12088
+ const width = bbox.x[1] - bbox.x[0];
12089
+ const height = bbox.y[1] - bbox.y[0];
12090
+ const centerX = (bbox.x[0] + bbox.x[1]) / 2;
12091
+ const centerY = (bbox.y[0] + bbox.y[1]) / 2;
12092
+ const paddingValue = padding || 40;
12093
+ const viewportWidth = containerWidth - paddingValue;
12094
+ const viewportHeight = containerHeight - paddingValue;
12095
+ const scale = Math.min(viewportWidth / width, viewportHeight / height);
12096
+ if (this.enableVerboseLogging) {
12097
+ console.log("\u{1F3AF} zoomToFit calculations:", {
12098
+ bbox: { width, height, centerX, centerY },
12099
+ container: {
12100
+ clientWidth: containerWidth,
12101
+ clientHeight: containerHeight,
12102
+ viewportWidth,
12103
+ viewportHeight
12104
+ },
12105
+ scale,
12106
+ willApply: width > 0 && height > 0
12107
+ });
12108
+ }
12109
+ if (width > 0 && height > 0) {
12110
+ this.getGraphInstance().centerAt(centerX, centerY);
12111
+ this.getGraphInstance().zoom(scale, duration || 300);
12112
+ this.pendingFitView = false;
12113
+ if (this.enableVerboseLogging) {
12114
+ console.log("\u2705 zoomToFit applied successfully");
12115
+ }
12116
+ } else if (this.enableVerboseLogging) {
12117
+ console.warn("\u26A0\uFE0F zoomToFit skipped - invalid bbox:", {
12118
+ bboxValid: width > 0 && height > 0
12119
+ });
12120
+ }
12121
+ }
12122
+ const callDuration = performance.now() - start2;
12123
+ if (this.config.enablePerformanceMonitoring) {
12124
+ console.log(`\u2705 zoomToFit() completed in ${callDuration.toFixed(3)}ms`);
12125
+ }
12126
+ }
12127
+ screen2GraphCoords(screenX, screenY) {
12128
+ if (!this.isInitialized) this.initializeForceGraph();
12129
+ const start2 = performance.now();
12130
+ let result = { x: 0, y: 0 };
12131
+ if (this.forceGraph) {
12132
+ result = this.getGraphInstance().screen2GraphCoords(screenX, screenY) || { x: 0, y: 0 };
12133
+ }
12134
+ const callDuration = performance.now() - start2;
12135
+ if (this.config.enablePerformanceMonitoring) {
12136
+ console.log(`\u2705 screen2GraphCoords(${screenX}, ${screenY}) completed in ${callDuration.toFixed(3)}ms`);
12137
+ }
12138
+ return result;
12139
+ }
12140
+ graph2ScreenCoords(graphX, graphY) {
12141
+ if (!this.isInitialized) this.initializeForceGraph();
12142
+ const start2 = performance.now();
12143
+ let result = { x: 0, y: 0 };
12144
+ if (this.forceGraph) {
12145
+ result = this.getGraphInstance().graph2ScreenCoords(graphX, graphY) || { x: 0, y: 0 };
12146
+ }
12147
+ const callDuration = performance.now() - start2;
12148
+ if (this.config.enablePerformanceMonitoring) {
12149
+ console.log(`\u2705 graph2ScreenCoords(${graphX}, ${graphY}) completed in ${callDuration.toFixed(3)}ms`);
12150
+ }
12151
+ return result;
12152
+ }
12153
+ getGraphBbox(nodes) {
12154
+ if (!this.isInitialized) this.initializeForceGraph();
12155
+ const start2 = performance.now();
12156
+ let result = { x: [0, 0], y: [0, 0] };
12157
+ if (this.forceGraph) {
12158
+ result = this.getGraphInstance().getGraphBbox(nodes) || { x: [0, 0], y: [0, 0] };
12159
+ }
12160
+ const callDuration = performance.now() - start2;
12161
+ if (this.config.enablePerformanceMonitoring) {
12162
+ console.log(`\u2705 getGraphBbox() completed in ${callDuration.toFixed(3)}ms`);
12163
+ }
12164
+ return result;
12165
+ }
12166
+ emitParticle(link) {
12167
+ if (!this.isInitialized) this.initializeForceGraph();
12168
+ const start2 = performance.now();
12169
+ if (this.forceGraph) {
12170
+ this.getGraphInstance().emitParticle(link);
12171
+ }
12172
+ const callDuration = performance.now() - start2;
12173
+ if (this.config.enablePerformanceMonitoring) {
12174
+ console.log(`\u2705 emitParticle() completed in ${callDuration.toFixed(3)}ms`);
12175
+ }
12176
+ }
12177
+ d3Force(forceName, forceImpl) {
12178
+ if (!this.isInitialized) this.initializeForceGraph();
12179
+ const start2 = performance.now();
12180
+ if (this.forceGraph) {
12181
+ if (forceImpl !== void 0) {
12182
+ this.getGraphInstance().d3Force(forceName, forceImpl);
12183
+ const callDuration2 = performance.now() - start2;
12184
+ if (this.config.enablePerformanceMonitoring) {
12185
+ console.log(`\u2705 d3Force(set ${forceName}) completed in ${callDuration2.toFixed(3)}ms`);
12186
+ }
12187
+ return this;
12188
+ } else {
12189
+ const result = this.getGraphInstance().d3Force(forceName);
12190
+ const callDuration2 = performance.now() - start2;
12191
+ if (this.config.enablePerformanceMonitoring) {
12192
+ console.log(`\u2705 d3Force(get ${forceName}) completed in ${callDuration2.toFixed(3)}ms`);
12193
+ }
12194
+ return result;
12195
+ }
12196
+ }
12197
+ const callDuration = performance.now() - start2;
12198
+ if (this.config.enablePerformanceMonitoring) {
12199
+ const action = forceImpl !== void 0 ? "set" : "get";
12200
+ console.log(`\u2705 d3Force(${action} ${forceName}) completed in ${callDuration.toFixed(3)}ms`);
12201
+ }
12202
+ return forceImpl !== void 0 ? this : null;
12203
+ }
12204
+ graphData(data) {
12205
+ if (data === void 0) {
12206
+ return this.config.graphData ?? { nodes: [], links: [] };
12207
+ }
12208
+ this.config.graphData = data;
12209
+ const nodeCount = data.nodes.length;
12210
+ const linkCount = data.links.length;
12211
+ this.pendingFitView = false;
12212
+ this.performanceMonitor.setMetric("nodeCount", nodeCount);
12213
+ this.performanceMonitor.setMetric("linkCount", linkCount);
12214
+ this.webWorkerPhysicsCompleted = false;
12215
+ if (!this.isInitialized) {
12216
+ this.initializeForceGraph();
12217
+ }
12218
+ if (this.forceGraph) {
12219
+ const loadStart = performance.now();
12220
+ this.getGraphInstance().graphData(data);
12221
+ const loadTime = performance.now() - loadStart;
12222
+ this.performanceMonitor.setMetric("dataLoad", loadTime);
12223
+ if (this.config.enablePerformanceMonitoring) {
12224
+ this.validateDataLoadingPerformance(loadTime, nodeCount, linkCount);
12225
+ }
12226
+ this.updateLegends();
12227
+ }
12228
+ if (this.enableVerboseLogging) {
12229
+ console.log(`\u{1F50D} Web Worker trigger check:`, {
12230
+ deterministicLayout: this.config.deterministicLayout !== false,
12231
+ wasInitializedOutOfView: this.wasInitializedOutOfView,
12232
+ hasNodes: data?.nodes?.length > 0,
12233
+ webWorkerCompleted: this.webWorkerPhysicsCompleted,
12234
+ nodeCount: data?.nodes?.length || 0
12235
+ });
12236
+ }
12237
+ if (this.config.deterministicLayout !== false && this.wasInitializedOutOfView && data?.nodes?.length > 0 && !this.webWorkerPhysicsCompleted) {
12238
+ if (this.enableVerboseLogging) {
12239
+ console.log(`\u{1F3AF} Triggering Web Worker physics for off-screen graph with ${data.nodes.length} nodes`);
12240
+ }
12241
+ if (this.physicsTimeoutId) {
12242
+ window.clearTimeout(this.physicsTimeoutId);
12243
+ }
12244
+ this.physicsTimeoutId = window.setTimeout(() => {
12245
+ this.runWebWorkerPhysics().catch((error) => {
12246
+ if (this.enableVerboseLogging) {
12247
+ console.warn("\u26A0\uFE0F Web Worker physics failed:", error);
12248
+ }
12249
+ });
12250
+ }, 200);
12251
+ }
12252
+ return this;
12253
+ }
12254
+ width(width) {
12255
+ if (width === void 0) {
12256
+ return this.config.width ?? 400;
12257
+ }
12258
+ const start2 = performance.now();
12259
+ this.config.width = width;
12260
+ if (this.isInitialized && this.forceGraph) {
12261
+ this.getGraphInstance().width(width);
12262
+ }
12263
+ const callDuration = performance.now() - start2;
12264
+ if (this.config.enablePerformanceMonitoring) {
12265
+ console.log(`\u2705 width(${width}) completed in ${callDuration.toFixed(3)}ms`);
12266
+ }
12267
+ return this;
12268
+ }
12269
+ height(height) {
12270
+ if (height === void 0) {
12271
+ return this.config.height ?? 300;
12272
+ }
12273
+ const start2 = performance.now();
12274
+ this.config.height = height;
12275
+ if (this.isInitialized && this.forceGraph) {
12276
+ this.getGraphInstance().height(height);
12277
+ }
12278
+ const callDuration = performance.now() - start2;
12279
+ if (this.config.enablePerformanceMonitoring) {
12280
+ console.log(`\u2705 height(${height}) completed in ${callDuration.toFixed(3)}ms`);
12281
+ }
12282
+ return this;
12283
+ }
12284
+ backgroundColor(color2) {
12285
+ if (color2 === void 0) {
12286
+ return this.config.backgroundColor ?? "#ffffff";
12287
+ }
12288
+ const start2 = performance.now();
12289
+ this.config.backgroundColor = color2;
12290
+ if (this.isInitialized && this.forceGraph) {
12291
+ this.getGraphInstance().backgroundColor(color2);
12292
+ }
12293
+ const callDuration = performance.now() - start2;
12294
+ if (this.config.enablePerformanceMonitoring) {
12295
+ console.log(`\u2705 backgroundColor(${color2}) completed in ${callDuration.toFixed(3)}ms`);
12296
+ }
12297
+ return this;
12298
+ }
12299
+ nodeColor(color2) {
12300
+ if (color2 === void 0) return this.config.nodeColor ?? "#999999";
12301
+ const start2 = performance.now();
12302
+ this.config.nodeColor = color2;
12303
+ if (this.isInitialized && this.forceGraph) {
12304
+ this.getGraphInstance().nodeColor(color2);
12305
+ }
12306
+ const callDuration = performance.now() - start2;
12307
+ if (this.config.enablePerformanceMonitoring) {
12308
+ console.log(`\u2705 nodeColor() completed in ${callDuration.toFixed(3)}ms`);
12309
+ }
12310
+ return this;
12311
+ }
12312
+ nodeVal(val) {
12313
+ if (val === void 0) return this.config.nodeVal ?? 1;
12314
+ const start2 = performance.now();
12315
+ this.config.nodeVal = val;
12316
+ if (this.isInitialized && this.forceGraph) {
12317
+ this.getGraphInstance().nodeVal(val);
12318
+ }
12319
+ const callDuration = performance.now() - start2;
12320
+ if (this.config.enablePerformanceMonitoring) {
12321
+ console.log(`\u2705 nodeVal() completed in ${callDuration.toFixed(3)}ms`);
12322
+ }
12323
+ return this;
12324
+ }
12325
+ nodeRelSize(size) {
12326
+ if (size === void 0) return this.config.nodeRelSize ?? 4;
12327
+ const start2 = performance.now();
12328
+ this.config.nodeRelSize = size;
12329
+ if (this.isInitialized && this.forceGraph) {
12330
+ this.getGraphInstance().nodeRelSize(size);
12331
+ }
12332
+ const callDuration = performance.now() - start2;
12333
+ if (this.config.enablePerformanceMonitoring) {
12334
+ console.log(`\u2705 nodeRelSize(${size}) completed in ${callDuration.toFixed(3)}ms`);
12335
+ }
12336
+ return this;
12337
+ }
12338
+ nodeLabel(label) {
12339
+ if (label === void 0) return this.config.nodeLabel ?? "";
12340
+ const start2 = performance.now();
12341
+ this.config.nodeLabel = label;
12342
+ if (this.isInitialized && this.forceGraph) {
12343
+ this.getGraphInstance().nodeLabel(label);
12344
+ }
12345
+ const callDuration = performance.now() - start2;
12346
+ if (this.config.enablePerformanceMonitoring) {
12347
+ console.log(`\u2705 nodeLabel() completed in ${callDuration.toFixed(3)}ms`);
12348
+ }
12349
+ return this;
12350
+ }
12351
+ nodeVisibility(visibility) {
12352
+ if (visibility === void 0) return this.config.nodeVisibility ?? true;
12353
+ const start2 = performance.now();
12354
+ this.config.nodeVisibility = visibility;
12355
+ if (this.isInitialized && this.forceGraph) {
12356
+ this.getGraphInstance().nodeVisibility(visibility);
12357
+ }
12358
+ const callDuration = performance.now() - start2;
12359
+ if (this.config.enablePerformanceMonitoring) {
12360
+ console.log(`\u2705 nodeVisibility() completed in ${callDuration.toFixed(3)}ms`);
12361
+ }
12362
+ return this;
12363
+ }
12364
+ nodeCanvasObjectMode(mode) {
12365
+ if (mode === void 0) return this.config.nodeCanvasObjectMode ?? "replace";
12366
+ const start2 = performance.now();
12367
+ this.config.nodeCanvasObjectMode = mode;
12368
+ if (this.isInitialized && this.forceGraph) {
12369
+ this.getGraphInstance().nodeCanvasObjectMode(mode);
12370
+ }
12371
+ const callDuration = performance.now() - start2;
12372
+ if (this.config.enablePerformanceMonitoring) {
12373
+ console.log(`\u2705 nodeCanvasObjectMode() completed in ${callDuration.toFixed(3)}ms`);
12374
+ }
12375
+ return this;
12376
+ }
12377
+ linkColor(color2) {
12378
+ if (color2 === void 0) return this.config.linkColor ?? "#999999";
12379
+ const start2 = performance.now();
12380
+ this.config.linkColor = color2;
12381
+ if (this.isInitialized && this.forceGraph) {
12382
+ this.getGraphInstance().linkColor(color2);
12383
+ }
12384
+ const callDuration = performance.now() - start2;
12385
+ if (this.config.enablePerformanceMonitoring) {
12386
+ console.log(`\u2705 linkColor() completed in ${callDuration.toFixed(3)}ms`);
12387
+ }
12388
+ return this;
12389
+ }
12390
+ linkWidth(width) {
12391
+ if (width === void 0) return this.config.linkWidth ?? 1;
12392
+ const start2 = performance.now();
12393
+ this.config.linkWidth = width;
12394
+ if (this.isInitialized && this.forceGraph) {
12395
+ this.getGraphInstance().linkWidth(width);
12396
+ }
12397
+ const callDuration = performance.now() - start2;
12398
+ if (this.config.enablePerformanceMonitoring) {
12399
+ console.log(`\u2705 linkWidth() completed in ${callDuration.toFixed(3)}ms`);
12400
+ }
12401
+ return this;
12402
+ }
12403
+ linkLabel(label) {
12404
+ if (label === void 0) return this.config.linkLabel ?? "";
12405
+ const start2 = performance.now();
12406
+ this.config.linkLabel = label;
12407
+ if (this.isInitialized && this.forceGraph) {
12408
+ this.getGraphInstance().linkLabel(label);
12409
+ }
12410
+ const callDuration = performance.now() - start2;
12411
+ if (this.config.enablePerformanceMonitoring) {
12412
+ console.log(`\u2705 linkLabel() completed in ${callDuration.toFixed(3)}ms`);
12413
+ }
12414
+ return this;
12415
+ }
12416
+ linkVisibility(visibility) {
12417
+ if (visibility === void 0) return this.config.linkVisibility ?? true;
12418
+ const start2 = performance.now();
12419
+ this.config.linkVisibility = visibility;
12420
+ if (this.isInitialized && this.forceGraph) {
12421
+ this.getGraphInstance().linkVisibility(visibility);
12422
+ }
12423
+ const callDuration = performance.now() - start2;
12424
+ if (this.config.enablePerformanceMonitoring) {
12425
+ console.log(`\u2705 linkVisibility() completed in ${callDuration.toFixed(3)}ms`);
12426
+ }
12427
+ return this;
12428
+ }
12429
+ linkDirectionalArrowLength(length) {
12430
+ if (length === void 0) return this.config.linkDirectionalArrowLength ?? 0;
12431
+ const start2 = performance.now();
12432
+ this.config.linkDirectionalArrowLength = length;
12433
+ if (this.isInitialized && this.forceGraph) {
12434
+ this.getGraphInstance().linkDirectionalArrowLength(length);
12435
+ }
12436
+ const callDuration = performance.now() - start2;
12437
+ if (this.config.enablePerformanceMonitoring) {
12438
+ console.log(`\u2705 linkDirectionalArrowLength() completed in ${callDuration.toFixed(3)}ms`);
12439
+ }
12440
+ return this;
12441
+ }
12442
+ linkDirectionalParticles(particles) {
12443
+ if (particles === void 0) return this.config.linkDirectionalParticles ?? 0;
12444
+ const start2 = performance.now();
12445
+ this.config.linkDirectionalParticles = particles;
12446
+ if (this.isInitialized && this.forceGraph) {
12447
+ this.getGraphInstance().linkDirectionalParticles(particles);
12448
+ }
12449
+ const callDuration = performance.now() - start2;
12450
+ if (this.config.enablePerformanceMonitoring) {
12451
+ console.log(`\u2705 linkDirectionalParticles() completed in ${callDuration.toFixed(3)}ms`);
12452
+ }
12453
+ return this;
12454
+ }
12455
+ linkDirectionalArrowColor(color2) {
12456
+ if (color2 === void 0) return this.config.linkDirectionalArrowColor ?? "#999999";
12457
+ const start2 = performance.now();
12458
+ this.config.linkDirectionalArrowColor = color2;
12459
+ if (this.isInitialized && this.forceGraph) {
12460
+ this.getGraphInstance().linkDirectionalArrowColor(color2);
12461
+ }
12462
+ const callDuration = performance.now() - start2;
12463
+ if (this.config.enablePerformanceMonitoring) {
12464
+ console.log(`\u2705 linkDirectionalArrowColor() completed in ${callDuration.toFixed(3)}ms`);
12465
+ }
12466
+ return this;
12467
+ }
12468
+ linkDirectionalArrowRelPos(position) {
12469
+ if (position === void 0) return this.config.linkDirectionalArrowRelPos ?? 0.5;
12470
+ const start2 = performance.now();
12471
+ this.config.linkDirectionalArrowRelPos = position;
12472
+ if (this.isInitialized && this.forceGraph) {
12473
+ this.getGraphInstance().linkDirectionalArrowRelPos(position);
12474
+ }
12475
+ const callDuration = performance.now() - start2;
12476
+ if (this.config.enablePerformanceMonitoring) {
12477
+ console.log(`\u2705 linkDirectionalArrowRelPos(${position}) completed in ${callDuration.toFixed(3)}ms`);
12478
+ }
12479
+ return this;
12480
+ }
12481
+ linkDirectionalParticleSpeed(speed) {
12482
+ if (speed === void 0) return this.config.linkDirectionalParticleSpeed ?? 1;
12483
+ const start2 = performance.now();
12484
+ this.config.linkDirectionalParticleSpeed = speed;
12485
+ if (this.isInitialized && this.forceGraph) {
12486
+ this.getGraphInstance().linkDirectionalParticleSpeed(speed);
12487
+ }
12488
+ const callDuration = performance.now() - start2;
12489
+ if (this.config.enablePerformanceMonitoring) {
12490
+ console.log(`\u2705 linkDirectionalParticleSpeed(${speed}) completed in ${callDuration.toFixed(3)}ms`);
12491
+ }
12492
+ return this;
12493
+ }
12494
+ linkDirectionalParticleWidth(width) {
12495
+ if (width === void 0) return this.config.linkDirectionalParticleWidth ?? 4;
12496
+ const start2 = performance.now();
12497
+ this.config.linkDirectionalParticleWidth = width;
12498
+ if (this.isInitialized && this.forceGraph) {
12499
+ this.getGraphInstance().linkDirectionalParticleWidth(width);
12500
+ }
12501
+ const callDuration = performance.now() - start2;
12502
+ if (this.config.enablePerformanceMonitoring) {
12503
+ console.log(`\u2705 linkDirectionalParticleWidth(${width}) completed in ${callDuration.toFixed(3)}ms`);
12504
+ }
12505
+ return this;
12506
+ }
12507
+ linkDirectionalParticleColor(color2) {
12508
+ if (color2 === void 0) return this.config.linkDirectionalParticleColor ?? "#999999";
12509
+ const start2 = performance.now();
12510
+ this.config.linkDirectionalParticleColor = color2;
12511
+ if (this.isInitialized && this.forceGraph) {
12512
+ this.getGraphInstance().linkDirectionalParticleColor(color2);
12513
+ }
12514
+ const callDuration = performance.now() - start2;
12515
+ if (this.config.enablePerformanceMonitoring) {
12516
+ console.log(`\u2705 linkDirectionalParticleColor() completed in ${callDuration.toFixed(3)}ms`);
12517
+ }
12518
+ return this;
12519
+ }
12520
+ linkCurvature(curvature) {
12521
+ if (curvature === void 0) return this.config.linkCurvature ?? 0;
12522
+ const start2 = performance.now();
12523
+ this.config.linkCurvature = curvature;
12524
+ if (this.isInitialized && this.forceGraph) {
12525
+ this.getGraphInstance().linkCurvature(curvature);
12526
+ }
12527
+ const callDuration = performance.now() - start2;
12528
+ if (this.config.enablePerformanceMonitoring) {
12529
+ console.log(`\u2705 linkCurvature(${curvature}) completed in ${callDuration.toFixed(3)}ms`);
12530
+ }
12531
+ return this;
12532
+ }
12533
+ linkCanvasObjectMode(mode) {
12534
+ if (mode === void 0) return this.config.linkCanvasObjectMode ?? "replace";
12535
+ const start2 = performance.now();
12536
+ this.config.linkCanvasObjectMode = mode;
12537
+ if (this.isInitialized && this.forceGraph) {
12538
+ this.getGraphInstance().linkCanvasObjectMode(mode);
12539
+ }
12540
+ const callDuration = performance.now() - start2;
12541
+ if (this.config.enablePerformanceMonitoring) {
12542
+ console.log(`\u2705 linkCanvasObjectMode() completed in ${callDuration.toFixed(3)}ms`);
12543
+ }
12544
+ return this;
12545
+ }
12546
+ onNodeClick(handler) {
12547
+ if (handler === void 0) return this.config.onNodeClick ?? null;
12548
+ const start2 = performance.now();
12549
+ this.config.onNodeClick = handler || void 0;
12550
+ if (this.isInitialized && this.forceGraph) {
12551
+ this.getGraphInstance().onNodeClick(handler);
12552
+ }
12553
+ const callDuration = performance.now() - start2;
12554
+ if (this.config.enablePerformanceMonitoring) {
12555
+ console.log(`\u2705 onNodeClick() completed in ${callDuration.toFixed(3)}ms`);
12556
+ }
12557
+ return this;
12558
+ }
12559
+ onNodeDoubleClick(handler) {
12560
+ if (handler === void 0) return this.config.onNodeDoubleClick ?? null;
12561
+ const start2 = performance.now();
12562
+ this.config.onNodeDoubleClick = handler || void 0;
12563
+ const callDuration = performance.now() - start2;
12564
+ if (this.config.enablePerformanceMonitoring) {
12565
+ console.log(`\u2705 onNodeDoubleClick() completed in ${callDuration.toFixed(3)}ms`);
12566
+ }
12567
+ return this;
12568
+ }
12569
+ onNodeHover(handler) {
12570
+ if (handler === void 0) return this.config.onNodeHover ?? null;
12571
+ const start2 = performance.now();
12572
+ this.config.onNodeHover = handler || void 0;
12573
+ if (this.isInitialized && this.forceGraph) {
12574
+ this.getGraphInstance().onNodeHover(handler);
12575
+ }
12576
+ const callDuration = performance.now() - start2;
12577
+ if (this.config.enablePerformanceMonitoring) {
12578
+ console.log(`\u2705 onNodeHover() completed in ${callDuration.toFixed(3)}ms`);
12579
+ }
12580
+ return this;
12581
+ }
12582
+ onLinkClick(handler) {
12583
+ if (handler === void 0) return this.config.onLinkClick ?? null;
12584
+ const start2 = performance.now();
12585
+ this.config.onLinkClick = handler || void 0;
12586
+ if (this.isInitialized && this.forceGraph) {
12587
+ this.getGraphInstance().onLinkClick(handler);
12588
+ }
12589
+ const callDuration = performance.now() - start2;
12590
+ if (this.config.enablePerformanceMonitoring) {
12591
+ console.log(`\u2705 onLinkClick() completed in ${callDuration.toFixed(3)}ms`);
12592
+ }
12593
+ return this;
12594
+ }
12595
+ onLinkHover(handler) {
12596
+ if (handler === void 0) return this.config.onLinkHover ?? null;
12597
+ const start2 = performance.now();
12598
+ this.config.onLinkHover = handler || void 0;
12599
+ if (this.isInitialized && this.forceGraph) {
12600
+ this.getGraphInstance().onLinkHover(handler);
12601
+ }
12602
+ const callDuration = performance.now() - start2;
12603
+ if (this.config.enablePerformanceMonitoring) {
12604
+ console.log(`\u2705 onLinkHover() completed in ${callDuration.toFixed(3)}ms`);
12605
+ }
12606
+ return this;
12607
+ }
12608
+ onRenderFramePre(handler) {
12609
+ if (handler === void 0) return this.config.onRenderFramePre ?? null;
12610
+ const start2 = performance.now();
12611
+ this.config.onRenderFramePre = handler || void 0;
12612
+ if (this.isInitialized && this.forceGraph) {
12613
+ this.getGraphInstance().onRenderFramePre(handler);
12614
+ }
12615
+ const callDuration = performance.now() - start2;
12616
+ if (this.config.enablePerformanceMonitoring) {
12617
+ console.log(`\u2705 onRenderFramePre() completed in ${callDuration.toFixed(3)}ms`);
12618
+ }
12619
+ return this;
12620
+ }
12621
+ onRenderFramePost(handler) {
12622
+ if (handler === void 0) return this.config.onRenderFramePost ?? null;
12623
+ const start2 = performance.now();
12624
+ this.config.onRenderFramePost = handler || void 0;
12625
+ if (this.isInitialized && this.forceGraph) {
12626
+ this.getGraphInstance().onRenderFramePost(handler);
12627
+ }
12628
+ const callDuration = performance.now() - start2;
12629
+ if (this.config.enablePerformanceMonitoring) {
12630
+ console.log(`\u2705 onRenderFramePost() completed in ${callDuration.toFixed(3)}ms`);
12631
+ }
12632
+ return this;
12633
+ }
12634
+ cooldownTime(time) {
12635
+ if (time === void 0) return this.config.cooldownTime ?? 15e3;
12636
+ const start2 = performance.now();
12637
+ this.config.cooldownTime = time;
12638
+ if (this.isInitialized && this.forceGraph) {
12639
+ this.getGraphInstance().cooldownTime(time);
12640
+ }
12641
+ const callDuration = performance.now() - start2;
12642
+ if (this.config.enablePerformanceMonitoring) {
12643
+ console.log(`\u2705 cooldownTime(${time}) completed in ${callDuration.toFixed(3)}ms`);
12644
+ }
12645
+ return this;
12646
+ }
12647
+ d3AlphaDecay(decay) {
12648
+ if (decay === void 0) return this.config.d3AlphaDecay ?? 0.0228;
12649
+ const start2 = performance.now();
12650
+ this.config.d3AlphaDecay = decay;
12651
+ if (this.isInitialized && this.forceGraph) {
12652
+ this.getGraphInstance().d3AlphaDecay(decay);
12653
+ }
12654
+ const callDuration = performance.now() - start2;
12655
+ if (this.config.enablePerformanceMonitoring) {
12656
+ console.log(`\u2705 d3AlphaDecay(${decay}) completed in ${callDuration.toFixed(3)}ms`);
12657
+ }
12658
+ return this;
12659
+ }
12660
+ d3VelocityDecay(decay) {
12661
+ if (decay === void 0) return this.config.d3VelocityDecay ?? 0.4;
12662
+ const start2 = performance.now();
12663
+ this.config.d3VelocityDecay = decay;
12664
+ if (this.isInitialized && this.forceGraph) {
12665
+ this.getGraphInstance().d3VelocityDecay(decay);
12666
+ }
12667
+ const callDuration = performance.now() - start2;
12668
+ if (this.config.enablePerformanceMonitoring) {
12669
+ console.log(`\u2705 d3VelocityDecay(${decay}) completed in ${callDuration.toFixed(3)}ms`);
12670
+ }
12671
+ return this;
12672
+ }
12673
+ onEngineStop(handler) {
12674
+ if (handler === void 0) return this.config.onEngineStop;
12675
+ const start2 = performance.now();
12676
+ this.config.onEngineStop = handler;
12677
+ if (this.isInitialized && this.forceGraph) {
12678
+ this.getGraphInstance().onEngineStop(handler);
12679
+ }
12680
+ const callDuration = performance.now() - start2;
12681
+ if (this.config.enablePerformanceMonitoring) {
12682
+ console.log(`\u2705 onEngineStop() completed in ${callDuration.toFixed(3)}ms`);
12683
+ }
12684
+ return this;
12685
+ }
12686
+ onEngineTick(handler) {
12687
+ if (handler === void 0) return this.config.onEngineTick;
12688
+ const start2 = performance.now();
12689
+ this.config.onEngineTick = handler;
12690
+ if (this.isInitialized && this.forceGraph) {
12691
+ this.getGraphInstance().onEngineTick(handler);
12692
+ }
12693
+ const callDuration = performance.now() - start2;
12694
+ if (this.config.enablePerformanceMonitoring) {
12695
+ console.log(`\u2705 onEngineTick() completed in ${callDuration.toFixed(3)}ms`);
12696
+ }
12697
+ return this;
12698
+ }
12699
+ // =============================================================================
12700
+ // PUBLIC API - ForceGraphPerformanceMethods
12701
+ // =============================================================================
12702
+ getPerformanceMetrics() {
12703
+ return this.performanceMonitor.getMetrics();
12704
+ }
12705
+ resetPerformanceMetrics() {
12706
+ this.performanceMonitor.reset();
12707
+ }
12708
+ logPerformanceSummary() {
12709
+ this.performanceMonitor.logSummary();
12710
+ }
12711
+ validatePerformance() {
12712
+ const metrics = this.performanceMonitor.getMetrics();
12713
+ const targets = this.config.performanceTargets ?? {};
12714
+ const warnings = [];
12715
+ const recommendations = [];
12716
+ if (targets.creation && metrics.creation > targets.creation) {
12717
+ warnings.push(`Creation time ${metrics.creation.toFixed(2)}ms exceeds target ${targets.creation}ms`);
12718
+ recommendations.push("Consider reducing initialization complexity");
12719
+ }
12720
+ if (targets.dataLoad && metrics.dataLoad > targets.dataLoad) {
12721
+ warnings.push(`Data load time ${metrics.dataLoad.toFixed(2)}ms exceeds target ${targets.dataLoad}ms`);
12722
+ recommendations.push("Consider data preprocessing or pagination for large datasets");
12723
+ }
12724
+ return {
12725
+ passed: warnings.length === 0,
12726
+ warnings,
12727
+ recommendations
12728
+ };
12729
+ }
12730
+ // =============================================================================
12731
+ // STEP 4: RENDERING PERFORMANCE OPTIMIZATION
12732
+ // =============================================================================
12733
+ /**
12734
+ * Setup advanced rendering performance monitoring
12735
+ * Target: 60fps @ 1000 nodes with optimizations
12736
+ */
12737
+ setupRenderingMonitoring() {
12738
+ if (!this.forceGraph || !this.renderingMonitor || !this.canvasOptimizer) return;
12739
+ const canvas = this.container.querySelector("canvas");
12740
+ if (canvas) {
12741
+ this.canvasOptimizer.initialize(canvas);
12742
+ }
12743
+ if (this.config.enablePerformanceMonitoring && this.config.performanceTargets?.render) {
12744
+ let frameCount = 0;
12745
+ this.getGraphInstance().onRenderFramePost(() => {
12746
+ frameCount++;
12747
+ if (frameCount % 10 === 0) {
12748
+ this.renderingMonitor?.recordRenderCall();
12749
+ }
12750
+ });
12751
+ this.startRenderingMonitoring();
12752
+ }
12753
+ }
12754
+ /**
12755
+ * Start advanced rendering performance monitoring
12756
+ */
12757
+ startRenderingMonitoring() {
12758
+ if (!this.renderingMonitor) return;
12759
+ this.renderingMonitor.startMonitoring();
12760
+ this.isRenderingOptimized = true;
12761
+ if (this.enableVerboseLogging) {
12762
+ console.log("\u{1F3AC} Started rendering performance monitoring");
12763
+ }
12764
+ }
12765
+ /**
12766
+ * Stop rendering performance monitoring
12767
+ */
12768
+ stopRenderingMonitoring() {
12769
+ if (!this.renderingMonitor) return;
12770
+ this.renderingMonitor.stopMonitoring();
12771
+ this.isRenderingOptimized = false;
12772
+ if (this.enableVerboseLogging) {
12773
+ const metrics = this.renderingMonitor.getMetrics();
12774
+ console.log(`\u{1F3AC} Rendering performance: ${metrics.averageFps.toFixed(1)}fps, efficiency: ${(metrics.renderingEfficiency * 100).toFixed(1)}%`);
12775
+ }
12776
+ }
12777
+ /**
12778
+ * Get current rendering performance metrics
12779
+ */
12780
+ getRenderingMetrics() {
12781
+ if (!this.isRenderingOptimized || !this.renderingMonitor) {
12782
+ return null;
12783
+ }
12784
+ const currentData = this.forceGraph?.graphData?.();
12785
+ if (currentData) {
12786
+ this.renderingMonitor.updateCounts(
12787
+ currentData.nodes?.length ?? 0,
12788
+ currentData.links?.length ?? 0
12789
+ );
12790
+ }
12791
+ return this.renderingMonitor.getMetrics();
12792
+ }
12793
+ /**
12794
+ * Validate rendering performance against Step 4 targets
12795
+ */
12796
+ validateRenderingPerformance() {
12797
+ const metrics = this.getRenderingMetrics();
12798
+ if (!metrics) {
12799
+ return {
12800
+ passed: false,
12801
+ metrics: {},
12802
+ validation: {
12803
+ passed: false,
12804
+ results: {
12805
+ fpsTarget: { expected: 60, actual: 0, passed: false },
12806
+ frameTimeTarget: { expected: 16.67, actual: 0, passed: false },
12807
+ droppedFramesTarget: { expected: 0, actual: 0, passed: false },
12808
+ efficiencyTarget: { expected: 0.9, actual: 0, passed: false }
12809
+ },
12810
+ overallScore: 0
12811
+ },
12812
+ recommendations: ["Rendering monitoring not started"]
12813
+ };
12814
+ }
12815
+ const validation = this.renderingMonitor?.validatePerformance() ?? {
12816
+ passed: false,
12817
+ results: {
12818
+ fpsTarget: { expected: 60, actual: 0, passed: false },
12819
+ frameTimeTarget: { expected: 16.67, actual: 0, passed: false },
12820
+ droppedFramesTarget: { expected: 0, actual: 0, passed: false },
12821
+ efficiencyTarget: { expected: 0.9, actual: 0, passed: false }
12822
+ },
12823
+ overallScore: 0
12824
+ };
12825
+ const recommendations = this.renderingMonitor?.getOptimizationRecommendations() ?? ["Rendering monitoring not available"];
12826
+ return {
12827
+ passed: validation.passed,
12828
+ metrics,
12829
+ validation,
12830
+ recommendations
12831
+ };
12832
+ }
12833
+ /**
12834
+ * Optimize rendering for large datasets
12835
+ * Implements performance optimizations based on node count
12836
+ */
12837
+ optimizeForDataset(nodeCount) {
12838
+ if (!this.forceGraph) {
12839
+ console.warn("Cannot optimize: graph not initialized");
12840
+ return;
12841
+ }
12842
+ if (nodeCount > 5e3) {
12843
+ this.forceGraph.nodeCanvasObject(null).linkCanvasObject(null).nodeLabel("").linkLabel("").cooldownTicks(50).d3AlphaDecay(0.05);
12844
+ } else if (nodeCount > 1e3) {
12845
+ this.forceGraph.nodeCanvasObject(null).cooldownTicks(100).d3AlphaDecay(0.04);
12846
+ } else if (nodeCount > 500) {
12847
+ this.getGraphInstance().cooldownTicks(200);
12848
+ }
12849
+ this.performanceMonitor.setMetric("optimizedForNodeCount", nodeCount);
12850
+ }
12851
+ /**
12852
+ * Force a rendering performance test
12853
+ * Useful for validation during data loading
12854
+ */
12855
+ async testRenderingPerformance(durationMs = 5e3) {
12856
+ return new Promise((resolve) => {
12857
+ const fpsReadings = [];
12858
+ const target = this.config.performanceTargets?.render ?? 60;
12859
+ const tempTracker = {
12860
+ startTime: performance.now(),
12861
+ frames: 0,
12862
+ lastTime: performance.now()
12863
+ };
12864
+ if (this.performanceTestInterval) {
12865
+ clearInterval(this.performanceTestInterval);
12866
+ }
12867
+ this.performanceTestInterval = setInterval(() => {
12868
+ const now2 = performance.now();
12869
+ tempTracker.frames++;
12870
+ if (now2 - tempTracker.lastTime >= 1e3) {
12871
+ const fps = tempTracker.frames * 1e3 / (now2 - tempTracker.lastTime);
12872
+ fpsReadings.push(fps);
12873
+ tempTracker.frames = 0;
12874
+ tempTracker.lastTime = now2;
12875
+ }
12876
+ if (now2 - tempTracker.startTime >= durationMs) {
12877
+ if (this.performanceTestInterval) {
12878
+ clearInterval(this.performanceTestInterval);
12879
+ this.performanceTestInterval = null;
12880
+ }
12881
+ const averageFPS = fpsReadings.reduce((a2, b) => a2 + b, 0) / fpsReadings.length;
12882
+ const minFPS = Math.min(...fpsReadings);
12883
+ const maxFPS = Math.max(...fpsReadings);
12884
+ const passed = averageFPS >= target * 0.8;
12885
+ resolve({
12886
+ averageFPS,
12887
+ minFPS,
12888
+ maxFPS,
12889
+ passed,
12890
+ targetFPS: target
12891
+ });
12892
+ }
12893
+ }, 16);
12894
+ });
12895
+ }
12896
+ // =============================================================================
12897
+ // PUBLIC API - Core Methods
12898
+ // =============================================================================
12899
+ render() {
12900
+ if (!this.isInitialized) {
12901
+ this.initializeForceGraph();
12902
+ }
12903
+ const renderStart = performance.now();
12904
+ if (this.forceGraph) {
12905
+ const graphInstance = this.getGraphInstance();
12906
+ if (graphInstance.refresh) {
12907
+ graphInstance.refresh();
12908
+ }
12909
+ }
12910
+ const renderTime = performance.now() - renderStart;
12911
+ this.performanceMonitor.setMetric("firstRender", renderTime);
12912
+ this.initializeControls();
12913
+ this.initializeLegends();
12914
+ this.setupDoubleClickHandling();
12915
+ if (this.config.enablePerformanceMonitoring) {
12916
+ console.log(`\u2705 First render completed in ${renderTime.toFixed(2)}ms`);
12917
+ }
12918
+ }
12919
+ cooldownTicks(ticks) {
12920
+ if (ticks === void 0) return this.config.cooldownTicks ?? 100;
12921
+ const start2 = performance.now();
12922
+ this.config.cooldownTicks = ticks;
12923
+ if (this.isInitialized && this.forceGraph) {
12924
+ this.getGraphInstance().cooldownTicks(ticks);
12925
+ }
12926
+ const callDuration = performance.now() - start2;
12927
+ if (this.config.enablePerformanceMonitoring) {
12928
+ console.log(`\u2705 cooldownTicks(${ticks}) completed in ${callDuration.toFixed(3)}ms`);
12929
+ }
12930
+ return this;
12931
+ }
12932
+ d3AlphaMin(min) {
12933
+ if (min === void 0) return this.config.d3AlphaMin ?? 1e-3;
12934
+ const start2 = performance.now();
12935
+ this.config.d3AlphaMin = min;
12936
+ if (this.isInitialized && this.forceGraph) {
12937
+ this.getGraphInstance().d3AlphaMin(min);
12938
+ }
12939
+ const callDuration = performance.now() - start2;
12940
+ if (this.config.enablePerformanceMonitoring) {
12941
+ console.log(`\u2705 d3AlphaMin(${min}) completed in ${callDuration.toFixed(3)}ms`);
12942
+ }
12943
+ return this;
12944
+ }
12945
+ enableNodeDrag(enable) {
12946
+ if (enable === void 0) return this.config.enableNodeDrag ?? true;
12947
+ const start2 = performance.now();
12948
+ this.config.enableNodeDrag = enable;
12949
+ if (this.isInitialized && this.forceGraph) {
12950
+ this.getGraphInstance().enableNodeDrag(enable);
12951
+ }
12952
+ const callDuration = performance.now() - start2;
12953
+ if (this.config.enablePerformanceMonitoring) {
12954
+ console.log(`\u2705 enableNodeDrag(${enable}) completed in ${callDuration.toFixed(3)}ms`);
12955
+ }
12956
+ return this;
12957
+ }
12958
+ nodeCanvasObject(paintFunction) {
12959
+ if (paintFunction === void 0) return this.config.nodeCanvasObject ?? null;
12960
+ const start2 = performance.now();
12961
+ this.config.nodeCanvasObject = paintFunction || void 0;
12962
+ if (this.isInitialized && this.forceGraph) {
12963
+ this.getGraphInstance().nodeCanvasObject(paintFunction);
12964
+ }
12965
+ const callDuration = performance.now() - start2;
12966
+ if (this.config.enablePerformanceMonitoring) {
12967
+ console.log(`\u2705 nodeCanvasObject() completed in ${callDuration.toFixed(3)}ms`);
12968
+ }
12969
+ return this;
12970
+ }
12971
+ linkCanvasObject(paintFunction) {
12972
+ if (paintFunction === void 0) return this.config.linkCanvasObject ?? null;
12973
+ const start2 = performance.now();
12974
+ this.config.linkCanvasObject = paintFunction || void 0;
12975
+ if (this.isInitialized && this.forceGraph) {
12976
+ this.getGraphInstance().linkCanvasObject(paintFunction);
12977
+ }
12978
+ const callDuration = performance.now() - start2;
12979
+ if (this.config.enablePerformanceMonitoring) {
12980
+ console.log(`\u2705 linkCanvasObject() completed in ${callDuration.toFixed(3)}ms`);
12981
+ }
12982
+ return this;
12983
+ }
12984
+ autoPauseRedraw(enable) {
12985
+ if (enable === void 0) return this.config.autoPauseRedraw ?? true;
12986
+ const start2 = performance.now();
12987
+ this.config.autoPauseRedraw = enable;
12988
+ if (this.isInitialized && this.forceGraph) {
12989
+ this.getGraphInstance().autoPauseRedraw(enable);
12990
+ }
12991
+ const callDuration = performance.now() - start2;
12992
+ if (this.config.enablePerformanceMonitoring) {
12993
+ console.log(`\u2705 autoPauseRedraw(${enable}) completed in ${callDuration.toFixed(3)}ms`);
12994
+ }
12995
+ return this;
12996
+ }
12997
+ enableZoomInteraction(enable) {
12998
+ if (enable === void 0) {
12999
+ const configValue = this.config.enableZoomInteraction ?? true;
13000
+ return typeof configValue === "function" ? true : configValue;
13001
+ }
13002
+ const start2 = performance.now();
13003
+ this.config.enableZoomInteraction = enable;
13004
+ if (this.isInitialized && this.forceGraph) {
13005
+ this.getGraphInstance().enableZoomInteraction(enable);
13006
+ }
13007
+ const callDuration = performance.now() - start2;
13008
+ if (this.config.enablePerformanceMonitoring) {
13009
+ console.log(`\u2705 enableZoomInteraction(${enable}) completed in ${callDuration.toFixed(3)}ms`);
13010
+ }
13011
+ return this;
13012
+ }
13013
+ enablePanInteraction(enable) {
13014
+ if (enable === void 0) {
13015
+ const configValue = this.config.enablePanInteraction ?? true;
13016
+ return typeof configValue === "function" ? true : configValue;
13017
+ }
13018
+ const start2 = performance.now();
13019
+ this.config.enablePanInteraction = enable;
13020
+ if (this.isInitialized && this.forceGraph) {
13021
+ this.getGraphInstance().enablePanInteraction(enable);
13022
+ }
13023
+ const callDuration = performance.now() - start2;
13024
+ if (this.config.enablePerformanceMonitoring) {
13025
+ console.log(`\u2705 enablePanInteraction(${enable}) completed in ${callDuration.toFixed(3)}ms`);
13026
+ }
13027
+ return this;
13028
+ }
13029
+ // =============================================================================
13030
+ // GRAPH CONTROLS METHODS
13031
+ // =============================================================================
13032
+ /**
13033
+ * Initialize graph controls if enabled
13034
+ */
13035
+ initializeControls() {
13036
+ if (!this.config.controls?.enabled) return;
13037
+ const controlsConfig = {
13038
+ ...this.config.controls,
13039
+ enabled: true
13040
+ };
13041
+ if (!controlsConfig.position) {
13042
+ controlsConfig.position = "bottom-left";
13043
+ }
13044
+ const controlActions = {
13045
+ zoomIn: () => this.zoomIn(),
13046
+ zoomOut: () => this.zoomOut(),
13047
+ fitView: () => this.fitView(),
13048
+ resetView: () => this.resetView()
13049
+ };
13050
+ try {
13051
+ this.controlsInstance = createGraphControls(this.container, controlActions, controlsConfig);
13052
+ this.controlsInstance.mount();
13053
+ if (this.config.enablePerformanceMonitoring) {
13054
+ console.log("\u2705 Graph controls initialized");
13055
+ }
13056
+ } catch {
13057
+ }
13058
+ }
13059
+ /**
13060
+ * Zoom in by a factor of 1.5
13061
+ */
13062
+ zoomIn() {
13063
+ if (!this.isInitialized) return;
13064
+ const currentZoom = this.zoom();
13065
+ this.zoom(currentZoom * 1.5, 200);
13066
+ }
13067
+ /**
13068
+ * Zoom out by a factor of 0.67
13069
+ */
13070
+ zoomOut() {
13071
+ if (!this.isInitialized) return;
13072
+ const currentZoom = this.zoom();
13073
+ this.zoom(currentZoom * 0.67, 200);
13074
+ }
13075
+ /**
13076
+ * Fit the graph to the viewport
13077
+ */
13078
+ fitView() {
13079
+ this.zoomToFit(20, 300);
13080
+ }
13081
+ /**
13082
+ * Reset the view to initial state
13083
+ */
13084
+ resetView() {
13085
+ this.centerAt(0, 0, 300);
13086
+ this.zoom(1, 300);
13087
+ }
13088
+ /**
13089
+ * Cleanup graph controls
13090
+ */
13091
+ cleanupControls() {
13092
+ if (this.controlsInstance) {
13093
+ this.controlsInstance.destroy();
13094
+ this.controlsInstance = null;
13095
+ }
13096
+ }
13097
+ /**
13098
+ * Initialize graph legends if enabled
13099
+ */
13100
+ initializeLegends() {
13101
+ if (!this.config.legends?.enabled) return;
13102
+ const legendsConfig = {
13103
+ ...this.config.legends,
13104
+ enabled: true
13105
+ };
13106
+ if (!legendsConfig.position) {
13107
+ legendsConfig.position = "top-right";
13108
+ }
13109
+ try {
13110
+ this.legendsInstance = createGraphLegends(this.container, legendsConfig);
13111
+ this.legendsInstance.mount();
13112
+ this.updateLegends();
13113
+ if (this.config.enablePerformanceMonitoring) {
13114
+ console.log("\u2705 Graph legends initialized");
13115
+ }
13116
+ } catch {
13117
+ }
13118
+ }
13119
+ /**
13120
+ * Update legends with current graph data
13121
+ */
13122
+ updateLegends() {
13123
+ if (!this.legendsInstance || !this.config.legends?.enabled) return;
13124
+ const graphData = this.config.graphData;
13125
+ if (!graphData || !graphData.nodes || graphData.nodes.length === 0) return;
13126
+ const nodeTypes = Array.from(
13127
+ new Set(
13128
+ graphData.nodes.map((node) => node.data?.type).filter((type) => Boolean(type && typeof type === "string"))
13129
+ )
13130
+ );
13131
+ const colorMap = {};
13132
+ const nodeColorAccessor = this.config.nodeColor;
13133
+ if (nodeColorAccessor && typeof nodeColorAccessor === "function") {
13134
+ graphData.nodes.forEach((node) => {
13135
+ const type = node.data?.type;
13136
+ if (type) {
13137
+ const color2 = nodeColorAccessor(node);
13138
+ if (color2) {
13139
+ colorMap[type] = color2;
13140
+ }
13141
+ }
13142
+ });
13143
+ } else if (nodeColorAccessor && typeof nodeColorAccessor === "string") {
13144
+ nodeTypes.forEach((type) => {
13145
+ if (type) {
13146
+ colorMap[type] = nodeColorAccessor;
13147
+ }
13148
+ });
13149
+ } else {
13150
+ const defaultColors = [
13151
+ "#3b82f6",
13152
+ "#ef4444",
13153
+ "#10b981",
13154
+ "#f59e0b",
13155
+ "#8b5cf6",
13156
+ "#06b6d4",
13157
+ "#84cc16",
13158
+ "#f97316",
13159
+ "#ec4899",
13160
+ "#6b7280"
13161
+ ];
13162
+ nodeTypes.forEach((type, index2) => {
13163
+ const color2 = defaultColors[index2 % defaultColors.length];
13164
+ if (type && color2) {
13165
+ colorMap[type] = color2;
13166
+ }
13167
+ });
13168
+ }
13169
+ this.legendsInstance.update(nodeTypes, colorMap);
13170
+ }
13171
+ /**
13172
+ * Cleanup graph legends
13173
+ */
13174
+ cleanupLegends() {
13175
+ if (this.legendsInstance) {
13176
+ this.legendsInstance.destroy();
13177
+ this.legendsInstance = null;
13178
+ }
13179
+ }
13180
+ /**
13181
+ * Draw legends on the export canvas (similar to React implementation)
13182
+ */
13183
+ drawLegendsOnExportCanvas(ctx, canvasWidth, canvasHeight) {
13184
+ if (!this.config.legends?.enabled || !this.legendsInstance) return;
13185
+ const graphData = this.config.graphData;
13186
+ if (!graphData || !graphData.nodes || graphData.nodes.length === 0) return;
13187
+ const nodeTypes = Array.from(
13188
+ new Set(
13189
+ graphData.nodes.map((node) => node.data?.type).filter((type) => Boolean(type && typeof type === "string"))
13190
+ )
13191
+ ).sort();
13192
+ if (nodeTypes.length === 0) return;
13193
+ const colorMap = {};
13194
+ const nodeColorAccessor = this.config.nodeColor;
13195
+ if (nodeColorAccessor && typeof nodeColorAccessor === "function") {
13196
+ graphData.nodes.forEach((node) => {
13197
+ const type = node.data?.type;
13198
+ if (type) {
13199
+ const color2 = nodeColorAccessor(node);
13200
+ if (color2) {
13201
+ colorMap[type] = color2;
13202
+ }
13203
+ }
13204
+ });
13205
+ } else {
13206
+ const defaultColors = [
13207
+ "#3b82f6",
13208
+ "#ef4444",
13209
+ "#10b981",
13210
+ "#f59e0b",
13211
+ "#8b5cf6",
13212
+ "#06b6d4",
13213
+ "#84cc16",
13214
+ "#f97316",
13215
+ "#ec4899",
13216
+ "#6b7280"
13217
+ ];
13218
+ nodeTypes.forEach((type, index2) => {
13219
+ const color2 = defaultColors[index2 % defaultColors.length];
13220
+ if (type && color2) {
13221
+ colorMap[type] = color2;
13222
+ }
13223
+ });
13224
+ }
13225
+ const LEGEND_CONFIG = {
13226
+ padding: 20,
13227
+ circleRadius: 10,
13228
+ lineHeight: 40,
13229
+ circleTextGap: 12,
13230
+ containerPadding: 16,
13231
+ borderRadius: 16
13232
+ };
13233
+ ctx.save();
13234
+ ctx.font = "20px sans-serif";
13235
+ ctx.textBaseline = "middle";
13236
+ let maxTextWidth = 0;
13237
+ nodeTypes.forEach((type) => {
13238
+ if (type) {
13239
+ const textWidth = ctx.measureText(type).width;
13240
+ maxTextWidth = Math.max(maxTextWidth, textWidth);
13241
+ }
13242
+ });
13243
+ const legendContentWidth = LEGEND_CONFIG.circleRadius * 2 + LEGEND_CONFIG.circleTextGap + maxTextWidth;
13244
+ const legendContentHeight = nodeTypes.length * LEGEND_CONFIG.lineHeight - (LEGEND_CONFIG.lineHeight - LEGEND_CONFIG.circleRadius * 2);
13245
+ const containerWidth = legendContentWidth + LEGEND_CONFIG.containerPadding * 2;
13246
+ const containerHeight = legendContentHeight + LEGEND_CONFIG.containerPadding * 2;
13247
+ const position = this.config.legends.position || "top-right";
13248
+ let containerX, containerY;
13249
+ switch (position) {
13250
+ case "top-left":
13251
+ containerX = LEGEND_CONFIG.padding;
13252
+ containerY = LEGEND_CONFIG.padding;
13253
+ break;
13254
+ case "top-right":
13255
+ default:
13256
+ containerX = canvasWidth - containerWidth - LEGEND_CONFIG.padding;
13257
+ containerY = LEGEND_CONFIG.padding;
13258
+ break;
13259
+ case "bottom-left":
13260
+ containerX = LEGEND_CONFIG.padding;
13261
+ containerY = canvasHeight - containerHeight - LEGEND_CONFIG.padding;
13262
+ break;
13263
+ case "bottom-right":
13264
+ containerX = canvasWidth - containerWidth - LEGEND_CONFIG.padding;
13265
+ containerY = canvasHeight - containerHeight - LEGEND_CONFIG.padding;
13266
+ break;
13267
+ }
13268
+ ctx.shadowColor = "rgba(0, 0, 0, 0.1)";
13269
+ ctx.shadowBlur = 10;
13270
+ ctx.shadowOffsetX = 0;
13271
+ ctx.shadowOffsetY = 2;
13272
+ ctx.fillStyle = "#ffffff";
13273
+ this.drawRoundedRect(ctx, containerX, containerY, containerWidth, containerHeight, LEGEND_CONFIG.borderRadius);
13274
+ ctx.fill();
13275
+ ctx.restore();
13276
+ const startX = containerX + LEGEND_CONFIG.containerPadding;
13277
+ const startY = containerY + LEGEND_CONFIG.containerPadding;
13278
+ nodeTypes.forEach((type, index2) => {
13279
+ if (!type) return;
13280
+ const y3 = startY + index2 * LEGEND_CONFIG.lineHeight;
13281
+ const color2 = colorMap[type] || "#ccc";
13282
+ ctx.beginPath();
13283
+ ctx.arc(startX + LEGEND_CONFIG.circleRadius, y3 + LEGEND_CONFIG.circleRadius, LEGEND_CONFIG.circleRadius, 0, 2 * Math.PI);
13284
+ ctx.fillStyle = color2;
13285
+ ctx.fill();
13286
+ ctx.fillStyle = "#374151";
13287
+ ctx.fillText(type, startX + LEGEND_CONFIG.circleRadius * 2 + LEGEND_CONFIG.circleTextGap, y3 + LEGEND_CONFIG.circleRadius);
13288
+ });
13289
+ }
13290
+ /**
13291
+ * Draw rounded rectangle helper method
13292
+ */
13293
+ drawRoundedRect(ctx, x3, y3, width, height, radius) {
13294
+ ctx.beginPath();
13295
+ ctx.moveTo(x3 + radius, y3);
13296
+ ctx.lineTo(x3 + width - radius, y3);
13297
+ ctx.quadraticCurveTo(x3 + width, y3, x3 + width, y3 + radius);
13298
+ ctx.lineTo(x3 + width, y3 + height - radius);
13299
+ ctx.quadraticCurveTo(x3 + width, y3 + height, x3 + width - radius, y3 + height);
13300
+ ctx.lineTo(x3 + radius, y3 + height);
13301
+ ctx.quadraticCurveTo(x3, y3 + height, x3, y3 + height - radius);
13302
+ ctx.lineTo(x3, y3 + radius);
13303
+ ctx.quadraticCurveTo(x3, y3, x3 + radius, y3);
13304
+ ctx.closePath();
13305
+ }
13306
+ /**
13307
+ * Export graph as PNG image
13308
+ */
13309
+ async exportGraph(fileName) {
13310
+ if (!this.isInitialized) {
13311
+ throw new Error("Graph not initialized");
13312
+ }
13313
+ const start2 = performance.now();
13314
+ try {
13315
+ const defaultFileName = `polly-graph-export-${Date.now()}.png`;
13316
+ const finalFileName = fileName || defaultFileName;
13317
+ this.zoomToFit(40, 300);
13318
+ await new Promise((resolve) => {
13319
+ this.exportTimeoutId = setTimeout(() => {
13320
+ this.exportTimeoutId = null;
13321
+ resolve(void 0);
13322
+ }, 350);
13323
+ });
13324
+ const canvas = this.container.querySelector("canvas");
13325
+ if (!canvas) {
13326
+ throw new Error("Canvas not found");
13327
+ }
13328
+ const elementsToHide = [];
13329
+ const controls = this.container.querySelectorAll(".fg-controls");
13330
+ controls.forEach((control) => {
13331
+ const element = control;
13332
+ elementsToHide.push({ element, originalDisplay: element.style.display });
13333
+ element.style.display = "none";
13334
+ });
13335
+ const legends = this.container.querySelectorAll(".fg-legends");
13336
+ legends.forEach((legend) => {
13337
+ const element = legend;
13338
+ elementsToHide.push({ element, originalDisplay: element.style.display });
13339
+ element.style.display = "none";
13340
+ });
13341
+ await new Promise((resolve) => requestAnimationFrame(resolve));
13342
+ const exportCanvas = document.createElement("canvas");
13343
+ const ctx = exportCanvas.getContext("2d");
13344
+ if (!ctx) {
13345
+ throw new Error("Could not get canvas context");
13346
+ }
13347
+ exportCanvas.width = canvas.width;
13348
+ exportCanvas.height = canvas.height;
13349
+ ctx.fillStyle = this.config.backgroundColor || "#ffffff";
13350
+ ctx.fillRect(0, 0, exportCanvas.width, exportCanvas.height);
13351
+ ctx.drawImage(canvas, 0, 0);
13352
+ this.drawLegendsOnExportCanvas(ctx, exportCanvas.width, exportCanvas.height);
13353
+ exportCanvas.toBlob((blob) => {
13354
+ if (!blob) {
13355
+ throw new Error("Failed to create image blob");
13356
+ }
13357
+ const url = URL.createObjectURL(blob);
13358
+ const link = document.createElement("a");
13359
+ link.href = url;
13360
+ link.download = finalFileName;
13361
+ document.body.appendChild(link);
13362
+ link.click();
13363
+ document.body.removeChild(link);
13364
+ URL.revokeObjectURL(url);
13365
+ }, "image/png");
13366
+ elementsToHide.forEach(({ element, originalDisplay }) => {
13367
+ element.style.display = originalDisplay;
13368
+ });
13369
+ const duration = performance.now() - start2;
13370
+ if (this.config.enablePerformanceMonitoring) {
13371
+ console.log(`\u2705 exportGraph completed in ${duration.toFixed(3)}ms`);
13372
+ }
13373
+ } catch (error) {
13374
+ const controls = this.container.querySelectorAll(".fg-controls");
13375
+ controls.forEach((control) => {
13376
+ const element = control;
13377
+ element.style.display = "";
13378
+ });
13379
+ const legends = this.container.querySelectorAll(".fg-legends");
13380
+ legends.forEach((legend) => {
13381
+ const element = legend;
13382
+ element.style.display = "";
13383
+ });
13384
+ const duration = performance.now() - start2;
13385
+ if (this.config.enablePerformanceMonitoring) {
13386
+ console.log(`\u274C exportGraph failed in ${duration.toFixed(3)}ms`);
13387
+ }
13388
+ throw error;
13389
+ }
13390
+ }
13391
+ /**
13392
+ * Setup double-click functionality
13393
+ * - Double-click on node: center and zoom to node
13394
+ * - Double-click on canvas: fit view
13395
+ */
13396
+ setupDoubleClickHandling() {
13397
+ if (!this.isInitialized) return;
13398
+ const canvas = this.container.querySelector("canvas");
13399
+ if (!canvas) return;
13400
+ let clickTimeout = null;
13401
+ let clickCount = 0;
13402
+ let lastClickTime = 0;
13403
+ const DOUBLE_CLICK_DELAY = 300;
13404
+ const originalOnNodeClick = this.config.onNodeClick;
13405
+ if (this.canvasClickHandler) {
13406
+ canvas.removeEventListener("click", this.canvasClickHandler);
13407
+ }
13408
+ this.canvasClickHandler = (event) => {
13409
+ const currentTime = Date.now();
13410
+ clickCount++;
13411
+ if (clickCount === 1) {
13412
+ clickTimeout = window.setTimeout(() => {
13413
+ if (clickCount === 1) {
13414
+ const rect = canvas.getBoundingClientRect();
13415
+ const x3 = event.clientX - rect.left;
13416
+ const y3 = event.clientY - rect.top;
13417
+ const graphCoords = this.getGraphInstance().screen2GraphCoords(x3, y3);
13418
+ const clickedNode = this.findNodeAtPosition(graphCoords.x, graphCoords.y);
13419
+ if (clickedNode && originalOnNodeClick) {
13420
+ originalOnNodeClick(clickedNode, event);
13421
+ }
13422
+ }
13423
+ clickCount = 0;
13424
+ }, DOUBLE_CLICK_DELAY);
13425
+ } else if (clickCount === 2 && currentTime - lastClickTime < DOUBLE_CLICK_DELAY) {
13426
+ if (clickTimeout) {
13427
+ window.clearTimeout(clickTimeout);
13428
+ clickTimeout = null;
13429
+ }
13430
+ const rect = canvas.getBoundingClientRect();
13431
+ const x3 = event.clientX - rect.left;
13432
+ const y3 = event.clientY - rect.top;
13433
+ const graphCoords = this.getGraphInstance().screen2GraphCoords(x3, y3);
13434
+ const clickedNode = this.findNodeAtPosition(graphCoords.x, graphCoords.y);
13435
+ if (clickedNode) {
13436
+ if (this.config.onNodeDoubleClick) {
13437
+ this.config.onNodeDoubleClick(clickedNode, event);
13438
+ } else {
13439
+ this.centerAt(clickedNode.x || 0, clickedNode.y || 0, 400);
13440
+ this.zoom(8, 400);
13441
+ }
13442
+ } else {
13443
+ this.smoothZoomToFit(500);
13444
+ }
13445
+ clickCount = 0;
13446
+ } else {
13447
+ clickCount = 1;
13448
+ if (clickTimeout) {
13449
+ window.clearTimeout(clickTimeout);
13450
+ }
13451
+ clickTimeout = window.setTimeout(() => {
13452
+ clickCount = 0;
13453
+ }, DOUBLE_CLICK_DELAY);
13454
+ }
13455
+ lastClickTime = currentTime;
13456
+ };
13457
+ canvas.addEventListener("click", this.canvasClickHandler);
13458
+ if (this.forceGraph && originalOnNodeClick) {
13459
+ this.getGraphInstance().onNodeClick(null);
13460
+ }
13461
+ }
13462
+ /**
13463
+ * Smooth zoom to fit that animates from current position
13464
+ */
13465
+ smoothZoomToFit(duration = 500) {
13466
+ if (!this.isInitialized) this.initializeForceGraph();
13467
+ if (this.forceGraph && this.container) {
13468
+ const bbox = this.getGraphInstance().getGraphBbox();
13469
+ const width = bbox.x[1] - bbox.x[0];
13470
+ const height = bbox.y[1] - bbox.y[0];
13471
+ const centerX = (bbox.x[0] + bbox.x[1]) / 2;
13472
+ const centerY = (bbox.y[0] + bbox.y[1]) / 2;
13473
+ const paddingValue = 50;
13474
+ const viewportWidth = this.container.clientWidth - paddingValue;
13475
+ const viewportHeight = this.container.clientHeight - paddingValue;
13476
+ const targetZoom = Math.min(viewportWidth / width, viewportHeight / height);
13477
+ this.getGraphInstance().centerAt(centerX, centerY, duration / 2);
13478
+ setTimeout(() => {
13479
+ this.zoom(targetZoom, duration / 2);
13480
+ }, duration / 2);
13481
+ }
13482
+ }
13483
+ /**
13484
+ * Trigger Kapsule update to ensure render callbacks continue working
13485
+ * This is essential for onRenderFramePost callbacks after physics simulation stops
13486
+ */
13487
+ triggerKapsuleUpdate() {
13488
+ if (!this.isInitialized || !this.forceGraph) return;
13489
+ try {
13490
+ const kapsuleInstance = this._getForceGraphInstance();
13491
+ if (kapsuleInstance) {
13492
+ const state = kapsuleInstance["__state"];
13493
+ if (state && typeof state === "object") {
13494
+ state["needsRedraw"] = true;
13495
+ return;
13496
+ }
13497
+ const zoomFn = kapsuleInstance["zoom"];
13498
+ if (typeof zoomFn === "function") {
13499
+ const currentZoom = zoomFn();
13500
+ if (typeof currentZoom === "number") {
13501
+ zoomFn(currentZoom);
13502
+ }
13503
+ }
13504
+ }
13505
+ } catch (error) {
13506
+ if (this.config.enablePerformanceMonitoring) {
13507
+ console.log("Kapsule update fallback used:", error);
13508
+ }
13509
+ }
13510
+ }
13511
+ /**
13512
+ * Find node at given graph coordinates
13513
+ */
13514
+ findNodeAtPosition(graphX, graphY) {
13515
+ if (!this.config.graphData?.nodes) return null;
13516
+ const nodeRadius = 4;
13517
+ const tolerance = nodeRadius + 2;
13518
+ for (const node of this.config.graphData.nodes) {
13519
+ if (typeof node.x === "number" && typeof node.y === "number") {
13520
+ const distance = Math.sqrt(
13521
+ Math.pow(node.x - graphX, 2) + Math.pow(node.y - graphY, 2)
13522
+ );
13523
+ if (distance <= tolerance) {
13524
+ return node;
13525
+ }
13526
+ }
13527
+ }
13528
+ return null;
13529
+ }
13530
+ destroy() {
13531
+ if (this.isDestroyed) return;
13532
+ this.cleanupControls();
13533
+ this.cleanupLegends();
13534
+ this.cleanupPageVisibilityHandling();
13535
+ this.cleanupDeterministicPhysics();
13536
+ this.cleanupDeferredFitView();
13537
+ this.cleanupPerformanceTest();
13538
+ this.cleanupExportTimeout();
13539
+ this.cleanupCanvasEventListeners();
13540
+ physicsWorkerManager.terminate();
13541
+ this.stopRenderingMonitoring();
13542
+ if (this.canvasOptimizer) {
13543
+ this.canvasOptimizer.destroy?.();
13544
+ }
13545
+ if (this.forceGraph) {
13546
+ this.getGraphInstance().onRenderFramePre(void 0);
13547
+ this.getGraphInstance().onRenderFramePost(void 0);
13548
+ this.getGraphInstance().onNodeClick(void 0);
13549
+ this.getGraphInstance().onNodeHover(void 0);
13550
+ this.getGraphInstance().onLinkClick(void 0);
13551
+ this.getGraphInstance().onLinkHover(void 0);
13552
+ this.getGraphInstance().onEngineTick(void 0);
13553
+ this.getGraphInstance().onEngineStop(void 0);
13554
+ const graphInstance = this.getGraphInstance();
13555
+ if (typeof graphInstance.destroy === "function") {
13556
+ graphInstance.destroy();
13557
+ }
13558
+ }
13559
+ if (this.container) {
13560
+ this.container.innerHTML = "";
13561
+ }
13562
+ this.performanceMonitor.logSummary();
13563
+ this.forceGraph = null;
13564
+ this.renderingMonitor = null;
13565
+ this.canvasOptimizer = null;
13566
+ this.isDestroyed = true;
13567
+ this.isInitialized = false;
13568
+ }
13569
+ _getForceGraphInstance() {
13570
+ return this.forceGraph;
13571
+ }
13572
+ };
13573
+ function createForceGraph(container, config) {
13574
+ return new ForceGraphWrapper(container, config);
13575
+ }
13576
+
13577
+ // src/force-graph-wrapper/types/config.types.ts
13578
+ var ConfigPresets = {
13579
+ /**
13580
+ * High-performance preset for large graphs (5000+ nodes)
13581
+ */
13582
+ highPerformance: () => ({
13583
+ autoPauseRedraw: true,
13584
+ warmupTicks: 100,
13585
+ cooldownTime: 1e3,
13586
+ d3AlphaDecay: 0.05,
13587
+ d3VelocityDecay: 0.4,
13588
+ enablePerformanceMonitoring: true,
13589
+ performanceTargets: {
13590
+ creation: 5,
13591
+ // 5ms
13592
+ dataLoad: 100,
13593
+ // 100ms
13594
+ firstRender: 500,
13595
+ // 500ms
13596
+ methodCall: 1,
13597
+ // 1ms
13598
+ memoryGrowth: 10
13599
+ // 10MB per 1000 nodes
13600
+ }
13601
+ }),
13602
+ /**
13603
+ * Interactive preset for medium graphs (50-1000 nodes)
13604
+ */
13605
+ interactive: () => ({
13606
+ enablePointerInteraction: true,
13607
+ enableNodeDrag: true,
13608
+ enableZoomInteraction: true,
13609
+ enablePanInteraction: true,
13610
+ linkHoverPrecision: 2,
13611
+ cooldownTime: 2e3,
13612
+ controls: {
13613
+ enabled: true,
13614
+ position: "bottom-left",
13615
+ orientation: "vertical"
13616
+ },
13617
+ legends: {
13618
+ enabled: true,
13619
+ position: "top-right",
13620
+ maxItems: 10
13621
+ },
13622
+ performanceTargets: {
13623
+ creation: 1,
13624
+ dataLoad: 20,
13625
+ firstRender: 50,
13626
+ methodCall: 0.5,
13627
+ memoryGrowth: 5
13628
+ }
13629
+ }),
13630
+ /**
13631
+ * Minimal preset for small graphs (5-50 nodes)
13632
+ */
13633
+ minimal: () => ({
13634
+ width: 400,
13635
+ height: 300,
13636
+ backgroundColor: "#ffffff",
13637
+ cooldownTime: 1e3,
13638
+ enablePerformanceMonitoring: false
13639
+ })
13640
+ };
13641
+ var ForceGraphConfigBuilder = class {
13642
+ config = {};
13643
+ constructor(container) {
13644
+ this.config.container = container;
13645
+ }
13646
+ data(graphData) {
13647
+ this.config.graphData = graphData;
13648
+ return this;
13649
+ }
13650
+ size(width, height) {
13651
+ this.config.width = width;
13652
+ this.config.height = height;
13653
+ return this;
13654
+ }
13655
+ performance(preset) {
13656
+ Object.assign(this.config, ConfigPresets[preset]());
13657
+ return this;
13658
+ }
13659
+ nodeColor(accessor) {
13660
+ this.config.nodeColor = accessor;
13661
+ return this;
13662
+ }
13663
+ onNodeClick(handler) {
13664
+ this.config.onNodeClick = handler;
13665
+ return this;
13666
+ }
13667
+ build() {
13668
+ if (!this.config.container || !this.config.graphData) {
13669
+ throw new Error("Container and graphData are required");
13670
+ }
13671
+ return this.config;
13672
+ }
13673
+ };
13674
+
13675
+ // src/force-graph-wrapper/index.ts
13676
+ var VERSION = "1.0.0-alpha.1";
13677
+ var LIBRARY_INFO = {
13678
+ name: "force-graph-wrapper",
13679
+ version: VERSION,
13680
+ description: "Framework-independent TypeScript wrapper for force-graph library",
13681
+ performance: "Built-in performance monitoring and optimization",
13682
+ compatibility: "Vanilla JS, React, Angular, Vue.js"
13683
+ };
10135
13684
  // Annotate the CommonJS export names for ESM import in node:
10136
13685
  0 && (module.exports = {
10137
13686
  CanvasManager,
13687
+ ConfigPresets,
10138
13688
  DEFAULT_COLORS,
10139
13689
  DEFAULT_HOVER_STYLES,
10140
13690
  DEFAULT_LINK_LABEL_STYLE,
10141
13691
  DEFAULT_LINK_STYLE,
10142
13692
  DragManager,
10143
13693
  ErrorHandler,
13694
+ ForceGraphConfigBuilder,
13695
+ ForceGraphWrapper,
10144
13696
  HoverManager,
13697
+ LIBRARY_INFO,
10145
13698
  NeutralColor,
13699
+ PerformanceMonitor,
10146
13700
  PhysicsManager,
10147
13701
  PointerManager,
10148
13702
  PrimaryColor,
@@ -10151,8 +13705,10 @@ function createV2Graph(config) {
10151
13705
  SelectionManager,
10152
13706
  StandardColor,
10153
13707
  V2Graph,
13708
+ VERSION,
10154
13709
  ValidationError,
10155
13710
  ZoomManager,
13711
+ createForceGraph,
10156
13712
  createV2Graph,
10157
13713
  getIcon,
10158
13714
  getIconSvg,