@shumoku/core 0.2.0 → 0.2.1

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.
Files changed (56) hide show
  1. package/dist/icons/build-icons.js +3 -3
  2. package/dist/icons/build-icons.js.map +1 -1
  3. package/dist/icons/generated-icons.js +10 -10
  4. package/dist/icons/generated-icons.js.map +1 -1
  5. package/dist/index.d.ts +3 -4
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +6 -8
  8. package/dist/index.js.map +1 -1
  9. package/dist/layout/hierarchical.d.ts +1 -1
  10. package/dist/layout/hierarchical.d.ts.map +1 -1
  11. package/dist/layout/hierarchical.js +82 -66
  12. package/dist/layout/hierarchical.js.map +1 -1
  13. package/dist/layout/index.d.ts +1 -1
  14. package/dist/layout/index.d.ts.map +1 -1
  15. package/dist/layout/index.js.map +1 -1
  16. package/dist/models/types.d.ts.map +1 -1
  17. package/dist/models/types.js +13 -13
  18. package/dist/models/types.js.map +1 -1
  19. package/dist/themes/dark.d.ts.map +1 -1
  20. package/dist/themes/dark.js +1 -1
  21. package/dist/themes/dark.js.map +1 -1
  22. package/dist/themes/index.d.ts +3 -3
  23. package/dist/themes/index.d.ts.map +1 -1
  24. package/dist/themes/index.js +4 -4
  25. package/dist/themes/index.js.map +1 -1
  26. package/dist/themes/modern.d.ts.map +1 -1
  27. package/dist/themes/modern.js.map +1 -1
  28. package/dist/themes/types.d.ts.map +1 -1
  29. package/dist/themes/utils.d.ts +1 -1
  30. package/dist/themes/utils.d.ts.map +1 -1
  31. package/dist/themes/utils.js +5 -4
  32. package/dist/themes/utils.js.map +1 -1
  33. package/package.json +88 -92
  34. package/src/constants.ts +35 -35
  35. package/src/icons/build-icons.ts +12 -6
  36. package/src/icons/generated-icons.ts +12 -12
  37. package/src/index.test.ts +66 -0
  38. package/src/index.ts +6 -13
  39. package/src/layout/hierarchical.ts +1251 -1221
  40. package/src/layout/index.ts +1 -1
  41. package/src/models/types.ts +47 -37
  42. package/src/themes/dark.ts +15 -15
  43. package/src/themes/index.ts +7 -7
  44. package/src/themes/modern.ts +22 -22
  45. package/src/themes/types.ts +26 -26
  46. package/src/themes/utils.ts +25 -24
  47. package/dist/renderer/index.d.ts +0 -6
  48. package/dist/renderer/index.d.ts.map +0 -1
  49. package/dist/renderer/index.js +0 -5
  50. package/dist/renderer/index.js.map +0 -1
  51. package/dist/renderer/svg.d.ts +0 -131
  52. package/dist/renderer/svg.d.ts.map +0 -1
  53. package/dist/renderer/svg.js +0 -1031
  54. package/dist/renderer/svg.js.map +0 -1
  55. package/src/renderer/index.ts +0 -6
  56. package/src/renderer/svg.ts +0 -1277
@@ -1,1031 +0,0 @@
1
- /**
2
- * SVG Renderer
3
- * Renders NetworkGraph to SVG
4
- */
5
- import { getDeviceIcon, getVendorIconEntry } from '../icons/index.js';
6
- import { DEFAULT_ICON_SIZE, ICON_LABEL_GAP, LABEL_LINE_HEIGHT, MAX_ICON_WIDTH_RATIO, } from '../constants.js';
7
- const LIGHT_THEME = {
8
- backgroundColor: '#ffffff',
9
- defaultNodeFill: '#e2e8f0',
10
- defaultNodeStroke: '#64748b',
11
- defaultLinkStroke: '#94a3b8',
12
- labelColor: '#1e293b',
13
- labelSecondaryColor: '#64748b',
14
- subgraphFill: '#f8fafc',
15
- subgraphStroke: '#cbd5e1',
16
- subgraphLabelColor: '#374151',
17
- portFill: '#475569',
18
- portStroke: '#1e293b',
19
- portLabelBg: '#1e293b',
20
- portLabelColor: '#ffffff',
21
- endpointLabelBg: '#ffffff',
22
- endpointLabelStroke: '#cbd5e1',
23
- };
24
- const DARK_THEME = {
25
- backgroundColor: '#1e293b',
26
- defaultNodeFill: '#334155',
27
- defaultNodeStroke: '#64748b',
28
- defaultLinkStroke: '#64748b',
29
- labelColor: '#f1f5f9',
30
- labelSecondaryColor: '#94a3b8',
31
- subgraphFill: '#0f172a',
32
- subgraphStroke: '#475569',
33
- subgraphLabelColor: '#e2e8f0',
34
- portFill: '#64748b',
35
- portStroke: '#94a3b8',
36
- portLabelBg: '#0f172a',
37
- portLabelColor: '#f1f5f9',
38
- endpointLabelBg: '#1e293b',
39
- endpointLabelStroke: '#475569',
40
- };
41
- const DEFAULT_OPTIONS = {
42
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
43
- interactive: true,
44
- };
45
- // ============================================
46
- // SVG Renderer
47
- // ============================================
48
- export class SVGRenderer {
49
- options;
50
- themeColors = LIGHT_THEME;
51
- iconTheme = 'default';
52
- constructor(options) {
53
- this.options = { ...DEFAULT_OPTIONS, ...options };
54
- }
55
- /**
56
- * Get theme colors based on theme type
57
- */
58
- getThemeColors(theme) {
59
- return theme === 'dark' ? DARK_THEME : LIGHT_THEME;
60
- }
61
- /**
62
- * Get icon theme variant based on theme type
63
- */
64
- getIconTheme(theme) {
65
- return theme === 'dark' ? 'dark' : 'light';
66
- }
67
- render(graph, layout) {
68
- const { bounds } = layout;
69
- // Set theme colors based on graph settings
70
- const theme = graph.settings?.theme;
71
- this.themeColors = this.getThemeColors(theme);
72
- this.iconTheme = this.getIconTheme(theme);
73
- // Calculate legend dimensions if enabled
74
- const legendSettings = this.getLegendSettings(graph.settings?.legend);
75
- let legendWidth = 0;
76
- let legendHeight = 0;
77
- if (legendSettings.enabled) {
78
- const legendDims = this.calculateLegendDimensions(graph, legendSettings);
79
- legendWidth = legendDims.width;
80
- legendHeight = legendDims.height;
81
- }
82
- // Expand bounds to include legend with padding
83
- const legendPadding = 20;
84
- const expandedBounds = {
85
- x: bounds.x,
86
- y: bounds.y,
87
- width: bounds.width + (legendSettings.enabled && legendWidth > 0 ? legendPadding : 0),
88
- height: bounds.height + (legendSettings.enabled && legendHeight > 0 ? legendPadding : 0),
89
- };
90
- const parts = [];
91
- // SVG header using expanded bounds
92
- const viewBox = `${expandedBounds.x} ${expandedBounds.y} ${expandedBounds.width} ${expandedBounds.height}`;
93
- parts.push(this.renderHeader(expandedBounds.width, expandedBounds.height, viewBox));
94
- // Defs (markers, gradients)
95
- parts.push(this.renderDefs());
96
- // Styles
97
- parts.push(this.renderStyles());
98
- // Layer 1: Subgraphs (background)
99
- layout.subgraphs.forEach((sg) => {
100
- parts.push(this.renderSubgraph(sg));
101
- });
102
- // Layer 2: Node backgrounds (shapes)
103
- layout.nodes.forEach((node) => {
104
- parts.push(this.renderNodeBackground(node));
105
- });
106
- // Layer 3: Links (on top of node backgrounds)
107
- layout.links.forEach((link) => {
108
- parts.push(this.renderLink(link, layout.nodes));
109
- });
110
- // Layer 4: Node foregrounds (content + ports, on top of links)
111
- layout.nodes.forEach((node) => {
112
- parts.push(this.renderNodeForeground(node));
113
- });
114
- // Legend (if enabled) - use already calculated legendSettings
115
- if (legendSettings.enabled && legendWidth > 0) {
116
- parts.push(this.renderLegend(graph, layout, legendSettings));
117
- }
118
- // Close SVG
119
- parts.push('</svg>');
120
- return parts.join('\n');
121
- }
122
- /**
123
- * Calculate legend dimensions without rendering
124
- */
125
- calculateLegendDimensions(graph, settings) {
126
- const lineHeight = 20;
127
- const padding = 12;
128
- const iconWidth = 30;
129
- const maxLabelWidth = 100;
130
- // Count items
131
- let itemCount = 0;
132
- if (settings.showBandwidth) {
133
- const usedBandwidths = new Set();
134
- graph.links.forEach(link => {
135
- if (link.bandwidth)
136
- usedBandwidths.add(link.bandwidth);
137
- });
138
- itemCount += usedBandwidths.size;
139
- }
140
- if (itemCount === 0) {
141
- return { width: 0, height: 0 };
142
- }
143
- const width = iconWidth + maxLabelWidth + padding * 2;
144
- const height = itemCount * lineHeight + padding * 2 + 20; // +20 for title
145
- return { width, height };
146
- }
147
- /**
148
- * Parse legend settings from various input formats
149
- */
150
- getLegendSettings(legend) {
151
- if (legend === true) {
152
- return {
153
- enabled: true,
154
- position: 'top-right',
155
- showDeviceTypes: true,
156
- showBandwidth: true,
157
- showCableTypes: true,
158
- showVlans: false,
159
- };
160
- }
161
- if (legend && typeof legend === 'object') {
162
- return {
163
- enabled: legend.enabled !== false,
164
- position: legend.position ?? 'top-right',
165
- showDeviceTypes: legend.showDeviceTypes ?? true,
166
- showBandwidth: legend.showBandwidth ?? true,
167
- showCableTypes: legend.showCableTypes ?? true,
168
- showVlans: legend.showVlans ?? false,
169
- };
170
- }
171
- return { enabled: false, position: 'top-right' };
172
- }
173
- /**
174
- * Render legend showing visual elements used in the diagram
175
- */
176
- renderLegend(graph, layout, settings) {
177
- const items = [];
178
- const lineHeight = 20;
179
- const padding = 12;
180
- const iconWidth = 30;
181
- const maxLabelWidth = 100;
182
- // Collect used bandwidths
183
- const usedBandwidths = new Set();
184
- graph.links.forEach(link => {
185
- if (link.bandwidth)
186
- usedBandwidths.add(link.bandwidth);
187
- });
188
- // Collect used device types
189
- const usedDeviceTypes = new Set();
190
- graph.nodes.forEach(node => {
191
- if (node.type)
192
- usedDeviceTypes.add(node.type);
193
- });
194
- // Build legend items
195
- if (settings.showBandwidth && usedBandwidths.size > 0) {
196
- const sortedBandwidths = ['1G', '10G', '25G', '40G', '100G'].filter(b => usedBandwidths.has(b));
197
- for (const bw of sortedBandwidths) {
198
- const config = this.getBandwidthConfig(bw);
199
- items.push({
200
- icon: this.renderBandwidthLegendIcon(config.lineCount),
201
- label: bw,
202
- });
203
- }
204
- }
205
- if (items.length === 0)
206
- return '';
207
- // Calculate legend dimensions
208
- const legendWidth = iconWidth + maxLabelWidth + padding * 2;
209
- const legendHeight = items.length * lineHeight + padding * 2 + 20; // +20 for title
210
- // Position based on settings
211
- const { bounds } = layout;
212
- let legendX = bounds.x + bounds.width - legendWidth - 10;
213
- let legendY = bounds.y + bounds.height - legendHeight - 10;
214
- switch (settings.position) {
215
- case 'top-left':
216
- legendX = bounds.x + 10;
217
- legendY = bounds.y + 10;
218
- break;
219
- case 'top-right':
220
- legendX = bounds.x + bounds.width - legendWidth - 10;
221
- legendY = bounds.y + 10;
222
- break;
223
- case 'bottom-left':
224
- legendX = bounds.x + 10;
225
- legendY = bounds.y + bounds.height - legendHeight - 10;
226
- break;
227
- }
228
- // Render legend box
229
- let svg = `<g class="legend" transform="translate(${legendX}, ${legendY})">
230
- <rect x="0" y="0" width="${legendWidth}" height="${legendHeight}" rx="4"
231
- fill="${this.themeColors.backgroundColor}" stroke="${this.themeColors.subgraphStroke}" stroke-width="1" opacity="0.95" />
232
- <text x="${padding}" y="${padding + 12}" class="subgraph-label" font-size="11">Legend</text>`;
233
- // Render items
234
- items.forEach((item, index) => {
235
- const y = padding + 28 + index * lineHeight;
236
- svg += `\n <g transform="translate(${padding}, ${y})">`;
237
- svg += `\n ${item.icon}`;
238
- svg += `\n <text x="${iconWidth + 4}" y="4" class="node-label" font-size="10">${this.escapeXml(item.label)}</text>`;
239
- svg += `\n </g>`;
240
- });
241
- svg += '\n</g>';
242
- return svg;
243
- }
244
- /**
245
- * Render bandwidth indicator for legend
246
- */
247
- renderBandwidthLegendIcon(lineCount) {
248
- const lineSpacing = 3;
249
- const lineWidth = 24;
250
- const strokeWidth = 2;
251
- const offsets = this.calculateLineOffsets(lineCount, lineSpacing);
252
- const lines = offsets.map(offset => {
253
- const y = offset;
254
- return `<line x1="0" y1="${y}" x2="${lineWidth}" y2="${y}" stroke="${this.themeColors.defaultLinkStroke}" stroke-width="${strokeWidth}" />`;
255
- });
256
- return `<g transform="translate(0, 0)">${lines.join('')}</g>`;
257
- }
258
- renderHeader(width, height, viewBox) {
259
- return `<svg xmlns="http://www.w3.org/2000/svg"
260
- viewBox="${viewBox}"
261
- width="${width}"
262
- height="${height}"
263
- style="background: ${this.themeColors.backgroundColor}">`;
264
- }
265
- renderDefs() {
266
- return `<defs>
267
- <!-- Arrow marker -->
268
- <marker id="arrow" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
269
- <polygon points="0 0, 10 3.5, 0 7" fill="${this.themeColors.defaultLinkStroke}" />
270
- </marker>
271
- <marker id="arrow-red" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
272
- <polygon points="0 0, 10 3.5, 0 7" fill="#dc2626" />
273
- </marker>
274
-
275
- <!-- Filters -->
276
- <filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
277
- <feDropShadow dx="2" dy="2" stdDeviation="3" flood-opacity="0.15"/>
278
- </filter>
279
- </defs>`;
280
- }
281
- renderStyles() {
282
- return `<style>
283
- .node { cursor: pointer; }
284
- .node:hover rect, .node:hover circle, .node:hover polygon { filter: brightness(0.95); }
285
- .node-label { font-family: ${this.options.fontFamily}; font-size: 12px; fill: ${this.themeColors.labelColor}; }
286
- .node-label-bold { font-weight: bold; }
287
- .node-icon { color: ${this.themeColors.labelSecondaryColor}; }
288
- .subgraph-icon { opacity: 0.9; }
289
- .subgraph-label { font-family: ${this.options.fontFamily}; font-size: 14px; font-weight: 600; fill: ${this.themeColors.subgraphLabelColor}; }
290
- .link-label { font-family: ${this.options.fontFamily}; font-size: 11px; fill: ${this.themeColors.labelSecondaryColor}; }
291
- .endpoint-label { font-family: ${this.options.fontFamily}; font-size: 9px; fill: ${this.themeColors.labelColor}; }
292
- </style>`;
293
- }
294
- renderSubgraph(sg) {
295
- const { bounds, subgraph } = sg;
296
- const style = subgraph.style || {};
297
- const fill = style.fill || this.themeColors.subgraphFill;
298
- const stroke = style.stroke || this.themeColors.subgraphStroke;
299
- const strokeWidth = style.strokeWidth || 1;
300
- const strokeDasharray = style.strokeDasharray || '';
301
- const labelPos = style.labelPosition || 'top';
302
- const rx = 8; // Border radius
303
- // Check if subgraph has vendor icon (service for cloud, model for hardware)
304
- const iconKey = subgraph.service || subgraph.model;
305
- const hasIcon = subgraph.vendor && iconKey;
306
- const iconSize = 24;
307
- const iconPadding = 8;
308
- // Calculate icon position (top-left corner)
309
- const iconX = bounds.x + iconPadding;
310
- const iconY = bounds.y + iconPadding;
311
- // Label position - shift right if there's an icon
312
- let labelX = hasIcon ? bounds.x + iconSize + iconPadding * 2 : bounds.x + 10;
313
- let labelY = bounds.y + 20;
314
- const textAnchor = 'start';
315
- if (labelPos === 'top') {
316
- labelX = hasIcon ? bounds.x + iconSize + iconPadding * 2 : bounds.x + 10;
317
- labelY = bounds.y + 20;
318
- }
319
- // Render vendor icon if available
320
- let iconSvg = '';
321
- if (hasIcon) {
322
- const iconEntry = getVendorIconEntry(subgraph.vendor, iconKey, subgraph.resource);
323
- if (iconEntry) {
324
- const iconContent = iconEntry[this.iconTheme] || iconEntry.default;
325
- const viewBox = iconEntry.viewBox || '0 0 48 48';
326
- // Check if icon is a nested SVG (PNG-based with custom viewBox in content)
327
- if (iconContent.startsWith('<svg')) {
328
- const viewBoxMatch = iconContent.match(/viewBox="0 0 (\d+) (\d+)"/);
329
- if (viewBoxMatch) {
330
- const vbWidth = parseInt(viewBoxMatch[1]);
331
- const vbHeight = parseInt(viewBoxMatch[2]);
332
- const aspectRatio = vbWidth / vbHeight;
333
- const iconWidth = Math.round(iconSize * aspectRatio);
334
- iconSvg = `<g class="subgraph-icon" transform="translate(${iconX}, ${iconY})">
335
- <svg width="${iconWidth}" height="${iconSize}" viewBox="0 0 ${vbWidth} ${vbHeight}">
336
- ${iconContent.replace(/<svg[^>]*>/, '').replace(/<\/svg>$/, '')}
337
- </svg>
338
- </g>`;
339
- }
340
- }
341
- else {
342
- // Use viewBox from entry
343
- iconSvg = `<g class="subgraph-icon" transform="translate(${iconX}, ${iconY})">
344
- <svg width="${iconSize}" height="${iconSize}" viewBox="${viewBox}">
345
- ${iconContent}
346
- </svg>
347
- </g>`;
348
- }
349
- }
350
- }
351
- return `<g class="subgraph" data-id="${sg.id}">
352
- <rect x="${bounds.x}" y="${bounds.y}" width="${bounds.width}" height="${bounds.height}"
353
- rx="${rx}" ry="${rx}"
354
- fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}"
355
- ${strokeDasharray ? `stroke-dasharray="${strokeDasharray}"` : ''} />
356
- ${iconSvg}
357
- <text x="${labelX}" y="${labelY}" class="subgraph-label" text-anchor="${textAnchor}">${this.escapeXml(subgraph.label)}</text>
358
- </g>`;
359
- }
360
- /** Render node background (shape only) */
361
- renderNodeBackground(layoutNode) {
362
- const { id, position, size, node } = layoutNode;
363
- const x = position.x;
364
- const y = position.y;
365
- const w = size.width;
366
- const h = size.height;
367
- const style = node.style || {};
368
- const fill = style.fill || this.themeColors.defaultNodeFill;
369
- const stroke = style.stroke || this.themeColors.defaultNodeStroke;
370
- const strokeWidth = style.strokeWidth || 1;
371
- const strokeDasharray = style.strokeDasharray || '';
372
- const shape = this.renderNodeShape(node.shape, x, y, w, h, fill, stroke, strokeWidth, strokeDasharray);
373
- return `<g class="node-bg" data-id="${id}">${shape}</g>`;
374
- }
375
- /** Render node foreground (content + ports) */
376
- renderNodeForeground(layoutNode) {
377
- const { id, position, size, node, ports } = layoutNode;
378
- const x = position.x;
379
- const y = position.y;
380
- const w = size.width;
381
- const content = this.renderNodeContent(node, x, y, w);
382
- const portsRendered = this.renderPorts(x, y, ports);
383
- return `<g class="node-fg" data-id="${id}">
384
- ${content}
385
- ${portsRendered}
386
- </g>`;
387
- }
388
- /**
389
- * Render ports on a node
390
- */
391
- renderPorts(nodeX, nodeY, ports) {
392
- if (!ports || ports.size === 0)
393
- return '';
394
- const parts = [];
395
- ports.forEach((port) => {
396
- const px = nodeX + port.position.x;
397
- const py = nodeY + port.position.y;
398
- const pw = port.size.width;
399
- const ph = port.size.height;
400
- // Port box
401
- parts.push(`<rect class="port" data-port="${port.id}"
402
- x="${px - pw / 2}" y="${py - ph / 2}" width="${pw}" height="${ph}"
403
- fill="${this.themeColors.portFill}" stroke="${this.themeColors.portStroke}" stroke-width="1" rx="2" />`);
404
- // Port label - position based on side
405
- let labelX = px;
406
- let labelY = py;
407
- let textAnchor = 'middle';
408
- const labelOffset = 12;
409
- switch (port.side) {
410
- case 'top':
411
- labelY = py - labelOffset;
412
- break;
413
- case 'bottom':
414
- labelY = py + labelOffset + 4;
415
- break;
416
- case 'left':
417
- labelX = px - labelOffset;
418
- textAnchor = 'end';
419
- break;
420
- case 'right':
421
- labelX = px + labelOffset;
422
- textAnchor = 'start';
423
- break;
424
- }
425
- // Port label with black background
426
- const labelText = this.escapeXml(port.label);
427
- const charWidth = 5.5;
428
- const labelWidth = labelText.length * charWidth + 4;
429
- const labelHeight = 12;
430
- // Calculate background rect position based on text anchor
431
- let bgX = labelX - 2;
432
- if (textAnchor === 'middle') {
433
- bgX = labelX - labelWidth / 2;
434
- }
435
- else if (textAnchor === 'end') {
436
- bgX = labelX - labelWidth + 2;
437
- }
438
- const bgY = labelY - labelHeight + 3;
439
- parts.push(`<rect class="port-label-bg" x="${bgX}" y="${bgY}" width="${labelWidth}" height="${labelHeight}" rx="2" fill="${this.themeColors.portLabelBg}" />`);
440
- parts.push(`<text class="port-label" x="${labelX}" y="${labelY}" text-anchor="${textAnchor}" font-size="9" fill="${this.themeColors.portLabelColor}">${labelText}</text>`);
441
- });
442
- return parts.join('\n ');
443
- }
444
- renderNodeShape(shape, x, y, w, h, fill, stroke, strokeWidth, strokeDasharray) {
445
- const dashAttr = strokeDasharray ? `stroke-dasharray="${strokeDasharray}"` : '';
446
- const halfW = w / 2;
447
- const halfH = h / 2;
448
- switch (shape) {
449
- case 'rect':
450
- return `<rect x="${x - halfW}" y="${y - halfH}" width="${w}" height="${h}"
451
- fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${dashAttr} filter="url(#shadow)" />`;
452
- case 'rounded':
453
- return `<rect x="${x - halfW}" y="${y - halfH}" width="${w}" height="${h}" rx="8" ry="8"
454
- fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${dashAttr} filter="url(#shadow)" />`;
455
- case 'circle':
456
- const r = Math.min(halfW, halfH);
457
- return `<circle cx="${x}" cy="${y}" r="${r}"
458
- fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${dashAttr} filter="url(#shadow)" />`;
459
- case 'diamond':
460
- return `<polygon points="${x},${y - halfH} ${x + halfW},${y} ${x},${y + halfH} ${x - halfW},${y}"
461
- fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${dashAttr} filter="url(#shadow)" />`;
462
- case 'hexagon':
463
- const hx = halfW * 0.866;
464
- return `<polygon points="${x - halfW},${y} ${x - hx},${y - halfH} ${x + hx},${y - halfH} ${x + halfW},${y} ${x + hx},${y + halfH} ${x - hx},${y + halfH}"
465
- fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${dashAttr} filter="url(#shadow)" />`;
466
- case 'cylinder':
467
- const ellipseH = h * 0.15;
468
- return `<g>
469
- <ellipse cx="${x}" cy="${y + halfH - ellipseH}" rx="${halfW}" ry="${ellipseH}" fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${dashAttr} />
470
- <rect x="${x - halfW}" y="${y - halfH + ellipseH}" width="${w}" height="${h - ellipseH * 2}" fill="${fill}" stroke="none" />
471
- <line x1="${x - halfW}" y1="${y - halfH + ellipseH}" x2="${x - halfW}" y2="${y + halfH - ellipseH}" stroke="${stroke}" stroke-width="${strokeWidth}" />
472
- <line x1="${x + halfW}" y1="${y - halfH + ellipseH}" x2="${x + halfW}" y2="${y + halfH - ellipseH}" stroke="${stroke}" stroke-width="${strokeWidth}" />
473
- <ellipse cx="${x}" cy="${y - halfH + ellipseH}" rx="${halfW}" ry="${ellipseH}" fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${dashAttr} filter="url(#shadow)" />
474
- </g>`;
475
- case 'stadium':
476
- return `<rect x="${x - halfW}" y="${y - halfH}" width="${w}" height="${h}" rx="${halfH}" ry="${halfH}"
477
- fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${dashAttr} filter="url(#shadow)" />`;
478
- case 'trapezoid':
479
- const indent = w * 0.15;
480
- return `<polygon points="${x - halfW + indent},${y - halfH} ${x + halfW - indent},${y - halfH} ${x + halfW},${y + halfH} ${x - halfW},${y + halfH}"
481
- fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${dashAttr} filter="url(#shadow)" />`;
482
- default:
483
- return `<rect x="${x - halfW}" y="${y - halfH}" width="${w}" height="${h}" rx="4" ry="4"
484
- fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${dashAttr} filter="url(#shadow)" />`;
485
- }
486
- }
487
- /**
488
- * Calculate icon dimensions for a node
489
- */
490
- calculateIconInfo(node, w) {
491
- // Cap icon width at MAX_ICON_WIDTH_RATIO of node width to leave room for ports
492
- const maxIconWidth = Math.round(w * MAX_ICON_WIDTH_RATIO);
493
- // Try vendor-specific icon first (service for cloud, model for hardware)
494
- const iconKey = node.service || node.model;
495
- if (node.vendor && iconKey) {
496
- const iconEntry = getVendorIconEntry(node.vendor, iconKey, node.resource);
497
- if (iconEntry) {
498
- const vendorIcon = iconEntry[this.iconTheme] || iconEntry.default;
499
- const viewBox = iconEntry.viewBox || '0 0 48 48';
500
- // Check if icon is a nested SVG (PNG-based with custom viewBox in content)
501
- if (vendorIcon.startsWith('<svg')) {
502
- const viewBoxMatch = vendorIcon.match(/viewBox="0 0 (\d+) (\d+)"/);
503
- if (viewBoxMatch) {
504
- const vbWidth = parseInt(viewBoxMatch[1]);
505
- const vbHeight = parseInt(viewBoxMatch[2]);
506
- const aspectRatio = vbWidth / vbHeight;
507
- let iconWidth = Math.round(DEFAULT_ICON_SIZE * aspectRatio);
508
- let iconHeight = DEFAULT_ICON_SIZE;
509
- if (iconWidth > maxIconWidth) {
510
- iconWidth = maxIconWidth;
511
- iconHeight = Math.round(maxIconWidth / aspectRatio);
512
- }
513
- const innerSvg = vendorIcon.replace(/<svg[^>]*>/, '').replace(/<\/svg>$/, '');
514
- return {
515
- width: iconWidth,
516
- height: iconHeight,
517
- svg: `<svg width="${iconWidth}" height="${iconHeight}" viewBox="0 0 ${vbWidth} ${vbHeight}">${innerSvg}</svg>`,
518
- };
519
- }
520
- }
521
- // Parse viewBox for aspect ratio calculation
522
- const vbMatch = viewBox.match(/(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/);
523
- if (vbMatch) {
524
- const vbWidth = parseInt(vbMatch[3]);
525
- const vbHeight = parseInt(vbMatch[4]);
526
- const aspectRatio = vbWidth / vbHeight;
527
- let iconWidth = Math.abs(aspectRatio - 1) < 0.01 ? DEFAULT_ICON_SIZE : Math.round(DEFAULT_ICON_SIZE * aspectRatio);
528
- let iconHeight = DEFAULT_ICON_SIZE;
529
- if (iconWidth > maxIconWidth) {
530
- iconWidth = maxIconWidth;
531
- iconHeight = Math.round(maxIconWidth / aspectRatio);
532
- }
533
- return {
534
- width: iconWidth,
535
- height: iconHeight,
536
- svg: `<svg width="${iconWidth}" height="${iconHeight}" viewBox="${viewBox}">${vendorIcon}</svg>`,
537
- };
538
- }
539
- // Fallback: use viewBox directly
540
- return {
541
- width: DEFAULT_ICON_SIZE,
542
- height: DEFAULT_ICON_SIZE,
543
- svg: `<svg width="${DEFAULT_ICON_SIZE}" height="${DEFAULT_ICON_SIZE}" viewBox="${viewBox}">${vendorIcon}</svg>`,
544
- };
545
- }
546
- }
547
- // Fall back to device type icon
548
- const iconPath = getDeviceIcon(node.type);
549
- if (!iconPath)
550
- return null;
551
- return {
552
- width: DEFAULT_ICON_SIZE,
553
- height: DEFAULT_ICON_SIZE,
554
- svg: `<svg width="${DEFAULT_ICON_SIZE}" height="${DEFAULT_ICON_SIZE}" viewBox="0 0 24 24" fill="currentColor">${iconPath}</svg>`,
555
- };
556
- }
557
- /**
558
- * Render node content (icon + label) with dynamic vertical centering
559
- */
560
- renderNodeContent(node, x, y, w) {
561
- const iconInfo = this.calculateIconInfo(node, w);
562
- const labels = Array.isArray(node.label) ? node.label : [node.label];
563
- const labelHeight = labels.length * LABEL_LINE_HEIGHT;
564
- // Calculate total content height
565
- const iconHeight = iconInfo?.height || 0;
566
- const gap = iconHeight > 0 ? ICON_LABEL_GAP : 0;
567
- const totalContentHeight = iconHeight + gap + labelHeight;
568
- // Center the content block vertically in the node
569
- const contentTop = y - totalContentHeight / 2;
570
- const parts = [];
571
- // Render icon at top of content block
572
- if (iconInfo) {
573
- const iconY = contentTop;
574
- parts.push(`<g class="node-icon" transform="translate(${x - iconInfo.width / 2}, ${iconY})">
575
- ${iconInfo.svg}
576
- </g>`);
577
- }
578
- // Render labels below icon
579
- const labelStartY = contentTop + iconHeight + gap + LABEL_LINE_HEIGHT * 0.7; // 0.7 for text baseline adjustment
580
- labels.forEach((line, i) => {
581
- const isBold = line.includes('<b>') || line.includes('<strong>');
582
- const cleanLine = line.replace(/<\/?b>|<\/?strong>|<br\s*\/?>/gi, '');
583
- const className = isBold ? 'node-label node-label-bold' : 'node-label';
584
- parts.push(`<text x="${x}" y="${labelStartY + i * LABEL_LINE_HEIGHT}" class="${className}" text-anchor="middle">${this.escapeXml(cleanLine)}</text>`);
585
- });
586
- return parts.join('\n ');
587
- }
588
- renderLink(layoutLink, nodes) {
589
- const { id, points, link, fromEndpoint, toEndpoint } = layoutLink;
590
- const label = link.label;
591
- // Auto-apply styles based on redundancy type
592
- const type = link.type || this.getDefaultLinkType(link.redundancy);
593
- const arrow = link.arrow ?? this.getDefaultArrowType(link.redundancy);
594
- const stroke = link.style?.stroke || this.getVlanStroke(link.vlan) || this.themeColors.defaultLinkStroke;
595
- const dasharray = link.style?.strokeDasharray || this.getLinkDasharray(type);
596
- const markerEnd = arrow !== 'none' ? 'url(#arrow)' : '';
597
- // Get bandwidth rendering config
598
- const bandwidthConfig = this.getBandwidthConfig(link.bandwidth);
599
- const strokeWidth = link.style?.strokeWidth || bandwidthConfig.strokeWidth || this.getLinkStrokeWidth(type);
600
- // Render link lines based on bandwidth (single or multiple parallel lines)
601
- let result = this.renderBandwidthLines(id, points, stroke, strokeWidth, dasharray, markerEnd, bandwidthConfig, type);
602
- // Center label and VLANs
603
- const midPoint = this.getMidPoint(points);
604
- let labelYOffset = -8;
605
- if (label) {
606
- const labelText = Array.isArray(label) ? label.join(' / ') : label;
607
- result += `\n<text x="${midPoint.x}" y="${midPoint.y + labelYOffset}" class="link-label" text-anchor="middle">${this.escapeXml(labelText)}</text>`;
608
- labelYOffset += 12;
609
- }
610
- // VLANs (link-level, applies to both endpoints)
611
- if (link.vlan && link.vlan.length > 0) {
612
- const vlanText = link.vlan.length === 1
613
- ? `VLAN ${link.vlan[0]}`
614
- : `VLAN ${link.vlan.join(', ')}`;
615
- result += `\n<text x="${midPoint.x}" y="${midPoint.y + labelYOffset}" class="link-label" text-anchor="middle">${this.escapeXml(vlanText)}</text>`;
616
- }
617
- // Get node center positions for label placement
618
- const fromNode = nodes.get(fromEndpoint.node);
619
- const toNode = nodes.get(toEndpoint.node);
620
- const fromNodeCenterX = fromNode ? fromNode.position.x : points[0].x;
621
- const toNodeCenterX = toNode ? toNode.position.x : points[points.length - 1].x;
622
- // Endpoint labels (port/ip at both ends) - positioned along the line
623
- const fromLabels = this.formatEndpointLabels(fromEndpoint);
624
- const toLabels = this.formatEndpointLabels(toEndpoint);
625
- if (fromLabels.length > 0 && points.length > 1) {
626
- const portName = fromEndpoint.port || '';
627
- const labelPos = this.getEndpointLabelPosition(points, 'start', fromNodeCenterX, portName);
628
- result += this.renderEndpointLabels(fromLabels, labelPos.x, labelPos.y, labelPos.anchor);
629
- }
630
- if (toLabels.length > 0 && points.length > 1) {
631
- const portName = toEndpoint.port || '';
632
- const labelPos = this.getEndpointLabelPosition(points, 'end', toNodeCenterX, portName);
633
- result += this.renderEndpointLabels(toLabels, labelPos.x, labelPos.y, labelPos.anchor);
634
- }
635
- return `<g class="link-group">\n${result}\n</g>`;
636
- }
637
- formatEndpointLabels(endpoint) {
638
- const parts = [];
639
- // Port is now rendered on the node itself, so don't include it here
640
- if (endpoint.ip)
641
- parts.push(endpoint.ip);
642
- return parts;
643
- }
644
- /**
645
- * Calculate position for endpoint label near the port (not along the line)
646
- * This avoids label clustering at the center of links
647
- * Labels are placed based on port position relative to node center
648
- */
649
- getEndpointLabelPosition(points, which, nodeCenterX, portName) {
650
- // Get the endpoint position (port position)
651
- const endpointIdx = which === 'start' ? 0 : points.length - 1;
652
- const endpoint = points[endpointIdx];
653
- // Get the next/prev point to determine line direction
654
- const nextIdx = which === 'start' ? 1 : points.length - 2;
655
- const nextPoint = points[nextIdx];
656
- // Calculate direction from endpoint toward the line
657
- const dx = nextPoint.x - endpoint.x;
658
- const dy = nextPoint.y - endpoint.y;
659
- const len = Math.sqrt(dx * dx + dy * dy);
660
- // Normalize direction
661
- const nx = len > 0 ? dx / len : 0;
662
- const ny = len > 0 ? dy / len : 1;
663
- const isVertical = Math.abs(dy) > Math.abs(dx);
664
- // Hash port name as fallback
665
- const portHash = this.hashString(portName);
666
- const hashDirection = portHash % 2 === 0 ? 1 : -1;
667
- // Port position relative to node center determines label side
668
- const portOffsetFromCenter = endpoint.x - nodeCenterX;
669
- let sideMultiplier;
670
- if (isVertical) {
671
- if (Math.abs(portOffsetFromCenter) > 5) {
672
- // Port is on one side of node - place label outward
673
- sideMultiplier = portOffsetFromCenter > 0 ? 1 : -1;
674
- }
675
- else {
676
- // Center port - use small hash-based offset to avoid overlap
677
- sideMultiplier = hashDirection * 0.2;
678
- }
679
- }
680
- else {
681
- // Horizontal link: place label above/below based on which end
682
- const isStart = which === 'start';
683
- sideMultiplier = isStart ? -1 : 1;
684
- }
685
- const offsetDist = 30; // Distance along line direction
686
- const perpDist = 20; // Perpendicular offset (fixed)
687
- // Position: offset along line direction + fixed horizontal offset for vertical links
688
- let x;
689
- let y;
690
- let anchor;
691
- if (isVertical) {
692
- // For vertical links, use fixed horizontal offset (simpler and consistent)
693
- x = endpoint.x + perpDist * sideMultiplier;
694
- y = endpoint.y + ny * offsetDist;
695
- // Text anchor based on final position relative to endpoint
696
- anchor = 'middle';
697
- const labelDx = x - endpoint.x;
698
- if (Math.abs(labelDx) > 8) {
699
- anchor = labelDx > 0 ? 'start' : 'end';
700
- }
701
- }
702
- else {
703
- // For horizontal links, position label near the port (not toward center)
704
- // Keep x near the endpoint, offset y below the line
705
- x = endpoint.x;
706
- y = endpoint.y + perpDist; // Always below the line
707
- // Text anchor: extend toward the center of the link
708
- // Start endpoint extends right (start), end endpoint extends left (end)
709
- // Check direction: if nextPoint is to the left, we're on the right side
710
- anchor = nx < 0 ? 'end' : 'start';
711
- }
712
- return { x, y, anchor };
713
- }
714
- /**
715
- * Render endpoint labels (IP) with white background
716
- */
717
- renderEndpointLabels(lines, x, y, anchor) {
718
- if (lines.length === 0)
719
- return '';
720
- const lineHeight = 11;
721
- const paddingX = 2;
722
- const paddingY = 2;
723
- const charWidth = 4.8; // Approximate character width for 9px font
724
- // Calculate dimensions
725
- const maxLen = Math.max(...lines.map(l => l.length));
726
- const rectWidth = maxLen * charWidth + paddingX * 2;
727
- const rectHeight = lines.length * lineHeight + paddingY * 2;
728
- // Adjust rect position based on text anchor
729
- let rectX = x - paddingX;
730
- if (anchor === 'middle') {
731
- rectX = x - rectWidth / 2;
732
- }
733
- else if (anchor === 'end') {
734
- rectX = x - rectWidth + paddingX;
735
- }
736
- const rectY = y - lineHeight + paddingY;
737
- let result = `\n<rect x="${rectX}" y="${rectY}" width="${rectWidth}" height="${rectHeight}" rx="2" fill="${this.themeColors.endpointLabelBg}" stroke="${this.themeColors.endpointLabelStroke}" stroke-width="0.5" />`;
738
- lines.forEach((line, i) => {
739
- const textY = y + i * lineHeight;
740
- result += `\n<text x="${x}" y="${textY}" class="endpoint-label" text-anchor="${anchor}">${this.escapeXml(line)}</text>`;
741
- });
742
- return result;
743
- }
744
- getLinkStrokeWidth(type) {
745
- switch (type) {
746
- case 'thick': return 3;
747
- case 'double': return 2;
748
- default: return 2;
749
- }
750
- }
751
- /**
752
- * Bandwidth rendering configuration - line count represents speed
753
- * 1G → 1 line
754
- * 10G → 2 lines
755
- * 25G → 3 lines
756
- * 40G → 4 lines
757
- * 100G → 5 lines
758
- */
759
- getBandwidthConfig(bandwidth) {
760
- const strokeWidth = 2;
761
- switch (bandwidth) {
762
- case '1G':
763
- return { lineCount: 1, strokeWidth };
764
- case '10G':
765
- return { lineCount: 2, strokeWidth };
766
- case '25G':
767
- return { lineCount: 3, strokeWidth };
768
- case '40G':
769
- return { lineCount: 4, strokeWidth };
770
- case '100G':
771
- return { lineCount: 5, strokeWidth };
772
- default:
773
- return { lineCount: 1, strokeWidth };
774
- }
775
- }
776
- /**
777
- * Render bandwidth lines (single or multiple parallel lines)
778
- */
779
- renderBandwidthLines(id, points, stroke, strokeWidth, dasharray, markerEnd, config, type) {
780
- const { lineCount } = config;
781
- const lineSpacing = 3; // Space between parallel lines
782
- if (lineCount === 1) {
783
- // Single line
784
- const path = this.generatePath(points);
785
- let result = `<path class="link" data-id="${id}" d="${path}"
786
- fill="none" stroke="${stroke}" stroke-width="${strokeWidth}"
787
- ${dasharray ? `stroke-dasharray="${dasharray}"` : ''}
788
- ${markerEnd ? `marker-end="${markerEnd}"` : ''} />`;
789
- // Double line effect for redundancy types
790
- if (type === 'double') {
791
- result = `<path class="link-double-outer" d="${path}" fill="none" stroke="${stroke}" stroke-width="${strokeWidth + 2}" />
792
- <path class="link-double-inner" d="${path}" fill="none" stroke="white" stroke-width="${strokeWidth - 1}" />
793
- ${result}`;
794
- }
795
- return result;
796
- }
797
- // Multiple parallel lines
798
- const paths = [];
799
- const offsets = this.calculateLineOffsets(lineCount, lineSpacing);
800
- for (const offset of offsets) {
801
- const offsetPoints = this.offsetPoints(points, offset);
802
- const path = this.generatePath(offsetPoints);
803
- paths.push(`<path class="link" data-id="${id}" d="${path}"
804
- fill="none" stroke="${stroke}" stroke-width="${strokeWidth}"
805
- ${dasharray ? `stroke-dasharray="${dasharray}"` : ''} />`);
806
- }
807
- return paths.join('\n');
808
- }
809
- /**
810
- * Generate SVG path string from points with rounded corners
811
- */
812
- generatePath(points, cornerRadius = 8) {
813
- if (points.length < 2)
814
- return '';
815
- if (points.length === 2) {
816
- return `M ${points[0].x} ${points[0].y} L ${points[1].x} ${points[1].y}`;
817
- }
818
- const parts = [`M ${points[0].x} ${points[0].y}`];
819
- for (let i = 1; i < points.length - 1; i++) {
820
- const prev = points[i - 1];
821
- const curr = points[i];
822
- const next = points[i + 1];
823
- // Calculate distances to prev and next points
824
- const distPrev = Math.hypot(curr.x - prev.x, curr.y - prev.y);
825
- const distNext = Math.hypot(next.x - curr.x, next.y - curr.y);
826
- // Limit radius to half the shortest segment
827
- const maxRadius = Math.min(distPrev, distNext) / 2;
828
- const radius = Math.min(cornerRadius, maxRadius);
829
- if (radius < 1) {
830
- // Too small for rounding, just use straight line
831
- parts.push(`L ${curr.x} ${curr.y}`);
832
- continue;
833
- }
834
- // Calculate direction vectors
835
- const dirPrev = { x: (curr.x - prev.x) / distPrev, y: (curr.y - prev.y) / distPrev };
836
- const dirNext = { x: (next.x - curr.x) / distNext, y: (next.y - curr.y) / distNext };
837
- // Points where curve starts and ends
838
- const startCurve = { x: curr.x - dirPrev.x * radius, y: curr.y - dirPrev.y * radius };
839
- const endCurve = { x: curr.x + dirNext.x * radius, y: curr.y + dirNext.y * radius };
840
- // Line to start of curve, then quadratic bezier through corner
841
- parts.push(`L ${startCurve.x} ${startCurve.y}`);
842
- parts.push(`Q ${curr.x} ${curr.y} ${endCurve.x} ${endCurve.y}`);
843
- }
844
- // Line to final point
845
- const last = points[points.length - 1];
846
- parts.push(`L ${last.x} ${last.y}`);
847
- return parts.join(' ');
848
- }
849
- /**
850
- * Calculate offsets for parallel lines (centered around 0)
851
- */
852
- calculateLineOffsets(lineCount, spacing) {
853
- const offsets = [];
854
- const totalWidth = (lineCount - 1) * spacing;
855
- const startOffset = -totalWidth / 2;
856
- for (let i = 0; i < lineCount; i++) {
857
- offsets.push(startOffset + i * spacing);
858
- }
859
- return offsets;
860
- }
861
- /**
862
- * Offset points perpendicular to line direction, handling each segment properly
863
- * For orthogonal paths, this maintains parallel lines through bends
864
- */
865
- offsetPoints(points, offset) {
866
- if (points.length < 2)
867
- return points;
868
- const result = [];
869
- for (let i = 0; i < points.length; i++) {
870
- const p = points[i];
871
- if (i === 0) {
872
- // First point: use direction to next point
873
- const next = points[i + 1];
874
- const perp = this.getPerpendicular(p, next);
875
- result.push({ x: p.x + perp.x * offset, y: p.y + perp.y * offset });
876
- }
877
- else if (i === points.length - 1) {
878
- // Last point: use direction from previous point
879
- const prev = points[i - 1];
880
- const perp = this.getPerpendicular(prev, p);
881
- result.push({ x: p.x + perp.x * offset, y: p.y + perp.y * offset });
882
- }
883
- else {
884
- // Middle point (bend): offset based on incoming segment direction
885
- const prev = points[i - 1];
886
- const perp = this.getPerpendicular(prev, p);
887
- result.push({ x: p.x + perp.x * offset, y: p.y + perp.y * offset });
888
- // Also add a point for the outgoing segment if direction changes
889
- const next = points[i + 1];
890
- const perpNext = this.getPerpendicular(p, next);
891
- // Check if direction changed (bend point)
892
- if (Math.abs(perp.x - perpNext.x) > 0.01 || Math.abs(perp.y - perpNext.y) > 0.01) {
893
- result.push({ x: p.x + perpNext.x * offset, y: p.y + perpNext.y * offset });
894
- }
895
- }
896
- }
897
- return result;
898
- }
899
- /**
900
- * Get perpendicular unit vector for a line segment
901
- */
902
- getPerpendicular(from, to) {
903
- const dx = to.x - from.x;
904
- const dy = to.y - from.y;
905
- const len = Math.sqrt(dx * dx + dy * dy);
906
- if (len === 0)
907
- return { x: 0, y: 0 };
908
- // Perpendicular unit vector (rotate 90 degrees)
909
- return { x: -dy / len, y: dx / len };
910
- }
911
- /**
912
- * Get default link type based on redundancy
913
- */
914
- getDefaultLinkType(redundancy) {
915
- switch (redundancy) {
916
- case 'ha':
917
- case 'vc':
918
- case 'vss':
919
- case 'vpc':
920
- case 'mlag':
921
- return 'double';
922
- case 'stack':
923
- return 'thick';
924
- default:
925
- return 'solid';
926
- }
927
- }
928
- /**
929
- * Get default arrow type based on redundancy
930
- */
931
- getDefaultArrowType(_redundancy) {
932
- // Network diagrams typically show bidirectional connections, so no arrow by default
933
- return 'none';
934
- }
935
- /**
936
- * VLAN color palette - distinct colors for different VLANs
937
- */
938
- static VLAN_COLORS = [
939
- '#dc2626', // Red
940
- '#ea580c', // Orange
941
- '#ca8a04', // Yellow
942
- '#16a34a', // Green
943
- '#0891b2', // Cyan
944
- '#2563eb', // Blue
945
- '#7c3aed', // Violet
946
- '#c026d3', // Magenta
947
- '#db2777', // Pink
948
- '#059669', // Emerald
949
- '#0284c7', // Light Blue
950
- '#4f46e5', // Indigo
951
- ];
952
- /**
953
- * Get stroke color based on VLANs
954
- */
955
- getVlanStroke(vlan) {
956
- if (!vlan || vlan.length === 0) {
957
- return undefined;
958
- }
959
- if (vlan.length === 1) {
960
- // Single VLAN: use color based on VLAN ID
961
- const colorIndex = vlan[0] % SVGRenderer.VLAN_COLORS.length;
962
- return SVGRenderer.VLAN_COLORS[colorIndex];
963
- }
964
- // Multiple VLANs (trunk): use a combined hash color
965
- const hash = vlan.reduce((acc, v) => acc + v, 0);
966
- const colorIndex = hash % SVGRenderer.VLAN_COLORS.length;
967
- return SVGRenderer.VLAN_COLORS[colorIndex];
968
- }
969
- getLinkDasharray(type) {
970
- switch (type) {
971
- case 'dashed': return '5 3';
972
- case 'invisible': return '0';
973
- default: return '';
974
- }
975
- }
976
- getMidPoint(points) {
977
- if (points.length === 4) {
978
- // Cubic bezier curve midpoint at t=0.5
979
- const t = 0.5;
980
- const mt = 1 - t;
981
- const x = mt * mt * mt * points[0].x +
982
- 3 * mt * mt * t * points[1].x +
983
- 3 * mt * t * t * points[2].x +
984
- t * t * t * points[3].x;
985
- const y = mt * mt * mt * points[0].y +
986
- 3 * mt * mt * t * points[1].y +
987
- 3 * mt * t * t * points[2].y +
988
- t * t * t * points[3].y;
989
- return { x, y };
990
- }
991
- if (points.length === 2) {
992
- // Simple midpoint between two points
993
- return {
994
- x: (points[0].x + points[1].x) / 2,
995
- y: (points[0].y + points[1].y) / 2,
996
- };
997
- }
998
- // For polylines, find the middle segment and get its midpoint
999
- const midIndex = Math.floor(points.length / 2);
1000
- if (midIndex > 0 && midIndex < points.length) {
1001
- return {
1002
- x: (points[midIndex - 1].x + points[midIndex].x) / 2,
1003
- y: (points[midIndex - 1].y + points[midIndex].y) / 2,
1004
- };
1005
- }
1006
- return points[midIndex] || points[0];
1007
- }
1008
- escapeXml(str) {
1009
- return str
1010
- .replace(/&/g, '&amp;')
1011
- .replace(/</g, '&lt;')
1012
- .replace(/>/g, '&gt;')
1013
- .replace(/"/g, '&quot;')
1014
- .replace(/'/g, '&#39;');
1015
- }
1016
- /**
1017
- * Simple string hash for consistent but varied label placement
1018
- */
1019
- hashString(str) {
1020
- let hash = 0;
1021
- for (let i = 0; i < str.length; i++) {
1022
- const char = str.charCodeAt(i);
1023
- hash = ((hash << 5) - hash) + char;
1024
- hash = hash & hash; // Convert to 32-bit integer
1025
- }
1026
- return Math.abs(hash);
1027
- }
1028
- }
1029
- // Default instance
1030
- export const svgRenderer = new SVGRenderer();
1031
- //# sourceMappingURL=svg.js.map