vue3-network-graph 0.2.2 → 0.2.3

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/README.en.md CHANGED
@@ -1,728 +1,733 @@
1
- # vue3-network-graph Usage Guide
2
-
3
- A lightweight network topology component based on **Vue 3 + SVG** with no third-party chart library dependencies. Supports node dragging, infinite canvas panning, zoom wheel, connection flow animations, three connection modes, multi-line overlap prevention for the same node pairs, and upright connection text along paths.
4
-
5
- ---
6
-
7
- ## Table of Contents
8
-
9
- - [Name](#name)
10
- - [Description](#description)
11
- - [Usage](#usage)
12
- - [Examples](#examples)
13
- - [Global Configuration Properties](#global-configuration-properties)
14
- - [Node Properties](#node-properties)
15
- - [Connection Properties](#connection-properties)
16
- - [API Methods](#api-methods)
17
- - [Events](#events)
18
- - [Interactions](#interactions)
19
-
20
- ---
21
-
22
- ## Name
23
-
24
- **vue3-network-graph** - Vue3 Network Topology Component
25
-
26
- ---
27
-
28
- ## Description
29
-
30
- A lightweight network topology component implemented with pure SVG, providing the following core capabilities:
31
-
32
- ### Core Features
33
-
34
- - **Multiple Connection Modes**: Straight (straight) / Polyline (polyline) / Curve (curve)
35
- - **Smart Multi-line Handling**: Multiple connections between the same pair of nodes automatically prevent overlap, staying parallel in any mode
36
- - **Upright Connection Text**: `fromText` / `centerText` / `toText` rotate along the path tangentially, automatically flipping when exceeding ±90° to maintain readability
37
- - **Rich Node Types**: 8 icon nodes + text nodes + border-only nodes
38
- - **Image Nodes**: photo / avatar / bitmap nodes, fitted at their real aspect ratio (fully contained or cover-cropped, never stretched)
39
- - **2D/3D Views**: Supports both 2D plane and 2.5D card styles
40
- - **Flow Animations**: Dashed流光 + particle effects, with per-connection animation control
41
- - **Edges never get swallowed**: nodes are painted in two passes (plate below, icon / label above), so a line crossing a node — or two overlapping nodes — stays visible; the selected path is promoted to the very top
42
-
43
- ### Interaction Capabilities
44
-
45
- - **Node Operations**: Drag to move, drag to resize, multi-select overall drag
46
- - **Canvas Operations**: Infinite panning (blank left-click/middle-click), zoom wheel (0.2x–5x)
47
- - **Selection Modes**: Single-click select, Ctrl+click multi-select, Ctrl+left-drag box select
48
- - **Connection Creation**: Auto-connect by dragging from node handle to target node
49
- - **Layer Management**: Z-axis sorting, right-click menu, keyboard shortcuts (requires `enableZOrder`)
50
-
51
- ### Performance Optimization
52
-
53
- - **Automatic Degradation**: Decorative animations automatically disabled based on scale (connections>200 disable流光,>500 disable glow, nodes>300 disable breathing)
54
- - **Large-scale Performance**: Thousands of nodes can pan/drag smoothly, nodes always responsive to clicks in dense graphics
55
-
56
- ---
57
-
58
- ## Usage
59
-
60
- ### 1. Installation
61
-
62
- ```bash
63
- npm install vue3-network-graph
64
- # or: pnpm add vue3-network-graph | yarn add vue3-network-graph
65
- ```
66
-
67
- ### 2. Import Component
68
-
69
- ```js
70
- // main.js
71
- import { createApp } from "vue";
72
- import { Topology } from "vue3-network-graph";
73
- import "vue3-network-graph/style.css";
74
-
75
- const app = createApp(App);
76
- app.component("Topology", Topology);
77
- app.mount("#app");
78
- ```
79
-
80
- Or local import:
81
-
82
- ```vue
83
- <script setup>
84
- import { Topology } from "vue3-network-graph";
85
- import "vue3-network-graph/style.css";
86
- </script>
87
- ```
88
-
89
- ### 3. Basic Usage
90
-
91
- ```vue
92
- <template>
93
- <Topology
94
- ref="topoRef"
95
- :editable="true"
96
- v-model:nodes="myNodes"
97
- v-model:edges="myEdges"
98
- :config="config"
99
- @node-click="handleNodeClick"
100
- @selection-change="handleSelectionChange"
101
- />
102
- </template>
103
-
104
- <script setup>
105
- import { ref } from "vue";
106
- import { Topology } from "vue3-network-graph";
107
-
108
- const myNodes = ref([
109
- { id: "node1", label: "Node 1", type: "core", state: "normal", x: 0, y: 0 },
110
- {
111
- id: "node2",
112
- label: "Node 2",
113
- type: "server",
114
- state: "normal",
115
- x: 200,
116
- y: 100,
117
- },
118
- ]);
119
-
120
- const myEdges = ref([
121
- { id: "edge1", from: "node1", to: "node2", centerText: "Connection" },
122
- ]);
123
-
124
- const config = ref({
125
- showGrid: true,
126
- nodeDraggable: true,
127
- nodeResizable: true,
128
- });
129
- </script>
130
- ```
131
-
132
- ---
133
-
134
- ## Examples
135
-
136
- ### Complete Example
137
-
138
- ```vue
139
- <template>
140
- <div class="topology-container">
141
- <Topology
142
- ref="topoRef"
143
- :editable="true"
144
- v-model:nodes="nodes"
145
- v-model:edges="edges"
146
- v-model:line-mode="lineMode"
147
- v-model:view-mode="viewMode"
148
- :groups="groups"
149
- :config="config"
150
- @node-click="onNodeClick"
151
- @edge-select="onEdgeSelect"
152
- @selection-change="onSelectionChange"
153
- @data-change="onDataChange"
154
- @edge-create="onEdgeCreate"
155
- >
156
- <!-- Custom node icon slot -->
157
- <template #node-icon="{ node, color, viewMode }">
158
- <circle r="16" :fill="color" opacity="0.9" />
159
- </template>
160
- </Topology>
161
- </div>
162
- </template>
163
-
164
- <script setup>
165
- import { ref, onMounted } from "vue";
166
- import { Topology } from "vue3-network-graph";
167
- import "vue3-network-graph/style.css";
168
-
169
- // Node data
170
- const nodes = ref([
171
- {
172
- id: "core",
173
- label: "Core Switch",
174
- nodeType: "core",
175
- state: "normal",
176
- x: 0,
177
- y: 0,
178
- width: 80,
179
- height: 80,
180
- },
181
- {
182
- id: "server1",
183
- label: "Web Server",
184
- nodeType: "server",
185
- state: "normal",
186
- x: 300,
187
- y: -150,
188
- },
189
- {
190
- id: "db1",
191
- label: "Database",
192
- nodeType: "database",
193
- state: "idle",
194
- x: 300,
195
- y: 150,
196
- },
197
- // Border-only node example
198
- {
199
- id: "border-box",
200
- label: "",
201
- nodeType: "border-only",
202
- state: "none",
203
- x: -400,
204
- y: -200,
205
- width: 250,
206
- height: 150,
207
- borderWidth: 2,
208
- borderColor: "#00f0ff",
209
- },
210
- ]);
211
-
212
- // Connection data
213
- const edges = ref([
214
- { id: "e1", from: "core", to: "server1", speed: 1.5, endMarker: "arrow" },
215
- {
216
- id: "e2",
217
- from: "core",
218
- to: "db1",
219
- speed: 2,
220
- centerText: "Query Traffic",
221
- endMarker: "arrow",
222
- },
223
- ]);
224
-
225
- // Group example
226
- const groups = ref([
227
- {
228
- id: "g1",
229
- label: "Application Zone",
230
- color: "#409eff",
231
- nodeIds: ["server1", "db1"],
232
- padding: 20,
233
- },
234
- ]);
235
-
236
- // Connection mode and view mode
237
- const lineMode = ref("curve"); // straight | polyline | curve
238
- const viewMode = ref("2d"); // 2d | 3d
239
-
240
- // Configuration
241
- const config = ref({
242
- selectedBorderColor: "#ffd400",
243
- selectedLineColor: "#ffd400",
244
- nodeDraggable: true,
245
- nodeResizable: true,
246
- enableZoom: true,
247
- enablePan: true,
248
- enableMarquee: true,
249
- showGrid: true,
250
- gridColor: "#1a2240",
251
- gridStep: 40,
252
- gridOpacity: 0.5,
253
- radialGradient: {
254
- startColor: "#0f1729",
255
- endColor: "#060a14",
256
- },
257
- showStatusDot: true,
258
- motionFx: true,
259
- maxSelectNodes: "unlimited",
260
- maxSelectEdges: "unlimited",
261
- enableZOrder: false,
262
- });
263
-
264
- // Component instance reference
265
- const topoRef = ref(null);
266
-
267
- // Event handlers
268
- const onNodeClick = (node) => {
269
- console.log("Node clicked:", node);
270
- };
271
-
272
- const onEdgeSelect = (edge) => {
273
- console.log("Connection selected:", edge);
274
- };
275
-
276
- const onSelectionChange = (selection) => {
277
- console.log("Selection changed:", selection);
278
- console.log("Selected nodes:", selection.nodes);
279
- console.log("Selected connections:", selection.edges);
280
- };
281
-
282
- const onDataChange = (payload) => {
283
- console.log("Data changed:", payload);
284
- console.log("Change summary:", payload.summary);
285
- };
286
-
287
- const onEdgeCreate = (edge) => {
288
- console.log("New connection:", edge);
289
- // Persist newly created connection
290
- edges.value = [...edges.value, edge];
291
- };
292
-
293
- // Method call examples
294
- const handleMethods = () => {
295
- // Get current data
296
- const data = topoRef.value.getData();
297
-
298
- // Add nodes
299
- topoRef.value.addNodes([
300
- { label: "New Node", nodeType: "server", x: 500, y: 0 },
301
- ]);
302
-
303
- // Add connections
304
- topoRef.value.addEdges([{ from: "core", to: "new-node-id" }]);
305
-
306
- // Update nodes
307
- topoRef.value.updateNodes([{ id: "core", label: "Updated Name" }]);
308
-
309
- // Delete selected elements
310
- topoRef.value.removeSelected();
311
-
312
- // Coordinate conversion
313
- const svgPos = topoRef.value.clientToSvg(event);
314
- const clientPos = topoRef.value.svgToClient(node.x, node.y);
315
-
316
- // Layer management (requires enableZOrder)
317
- topoRef.value.moveToFront("node-id");
318
- topoRef.value.moveToBack("node-id");
319
- topoRef.value.moveLayerUp("node-id");
320
- topoRef.value.moveLayerDown("node-id");
321
- };
322
- </script>
323
-
324
- <style scoped>
325
- .topology-container {
326
- width: 100%;
327
- height: 600px;
328
- background: radial-gradient(ellipse at center, #0f1729 0%, #060a14 100%);
329
- }
330
- </style>
331
- ```
332
-
333
- ---
334
-
335
- ## Global Configuration Properties
336
-
337
- | Config Item | Type | Default | Description |
338
- | --------------------- | ----------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
339
- | `selectedBorderColor` | `String` | `#fbbf24` | Selected node border color |
340
- | `selectedLineColor` | `String` | `#fbbf24` | Selected connection color |
341
- | `nodeDraggable` | `Boolean` | `true` | Node drag switch (requires `editable`) |
342
- | `nodeResizable` | `Boolean` | `true` | Node resize switch (requires `editable`) |
343
- | `enableZoom` | `Boolean` | `true` | Zoom wheel switch |
344
- | `enablePan` | `Boolean` | `true` | Canvas pan switch |
345
- | `enableMarquee` | `Boolean` | `true` | Ctrl + left-drag box select switch |
346
- | `maxSelectNodes` | `Number \| "unlimited"` | Unlimited | Max selectable nodes: `0` (disabled) / `1` / `2` or any non-negative integer; unset or `"unlimited"` no limit |
347
- | `maxSelectEdges` | `Number \| "unlimited"` | Unlimited | Max selectable connections (merged bundles count all connections in group) |
348
- | `showGrid` | `Boolean` | `true` | Grid background (set `false` to disable) |
349
- | `gridColor` | `String` | `#1a2240` | Grid line color |
350
- | `gridStep` | `Number` | `40` | Grid spacing (px at 1x zoom, scales with zoom) |
351
- | `gridOpacity` | `Number` | `0.5` | Grid overlay opacity (0–1) |
352
- | `radialGradient` | `Object` | See notes | Canvas background radial gradient |
353
- | `showCenterPoint` | `Boolean` | `false` | Canvas center cross marker |
354
- | `showEdgeTextBg` | `Boolean` | `false` | Connection text background |
355
- | `edgeTextBgColor` | `String` | `#0a0e1a` | Connection text background color |
356
- | `edgeCenterTextFollowLine` | `Boolean` | `true` | Whether the center label rotates along the line: `true` follows the line tangent (current), `false` always stays horizontal |
357
- | `showNodeHandles` | `Boolean` | `false` | Node handles (four small circles appear at top/bottom/left/right of nodes, auto-connect when dragged to another node) |
358
- | `showStatusDot` | `Boolean` | `true` | Status dot at top-right corner of each node |
359
- | `labelGap` | `Number` | `18` | Fixed gap between node box edge and its label (px at 1x zoom) |
360
- | `watchDataChanges` | `Boolean` | `false` | Component internal data change detection (debounce 300ms then trigger `data-change`) |
361
- | `fx` | `Boolean` | Auto | Master decorative animation switch: `false` all off / `true` all on / unset = auto |
362
- | `motionFx` | `Boolean` | Auto | Per-feature override - connection line animation (flow + particles) |
363
- | `glowFx` | `Boolean` | Auto | Per-feature override - connection glow |
364
- | `breatheFx` | `Boolean` | Auto | Per-feature override - breathing ring |
365
- | `fxMotionMaxEdges` | `Number` | `200` | Edge count above which flow + particle animation auto-disables |
366
- | `fxGlowMaxEdges` | `Number` | `500` | Edge count above which edge glow auto-disables |
367
- | `fxBreatheMaxNodes` | `Number` | `300` | Node count above which breathing rings auto-disable |
368
- | `enableZOrder` | `Boolean` | `false` | **Enable Z-axis layer sorting**: After enabling, nodes render according to `zIndex` property, supporting layer operation API, right-click menu and keyboard shortcuts |
369
- | `enableDeleteKey` | `Boolean` | `true` | Delete / Backspace removes the current selection (requires `editable`); when the parent listens to `delete-request` the component only emits the event |
370
- | `imageFit` | `"contain" \| "cover"` | `"contain"` | How image nodes fill their box: `contain` keeps the whole picture inside the box (centred, letterboxed, never cropped); `cover` fills the box and crops the overflow. Both scale uniformly — the picture is never stretched |
371
- | `imageNodeBySource` | `Boolean` | `false` | **Global image-node rule**: when `true`, any node carrying a picture source is rendered as an image node (its `nodeType` is ignored); text and border-only nodes are unaffected |
372
- | `edgeLayer` | `"split" \| "below"` | `"split"` | Paint order of nodes vs edges: `split` paints each node in two passes — plate + border below, icon / image / label above, with edges in between (a line crossing a node stays visible); `below` is the classic "all edges under all nodes" |
373
- | `highlightEdgeOnTop` | `Boolean` | `true` | Selected edges are re-painted above the node layer so the highlighted path is never hidden by a node plate or icon (decoration only — it never captures clicks) |
374
-
375
- ### radialGradient Configuration
376
-
377
- ```javascript
378
- // Simple mode
379
- radialGradient: {
380
- startColor: "#0f1729",
381
- endColor: "#060a14"
382
- }
383
-
384
- // Advanced mode (custom gradient center and color stops)
385
- radialGradient: {
386
- cx: "50%",
387
- cy: "50%",
388
- r: "50%",
389
- stops: [
390
- { offset: "0%", color: "#0f1729", opacity: 1 },
391
- { offset: "60%", color: "#1e293b", opacity: 0.8 },
392
- { offset: "100%", color: "#060a14", opacity: 1 }
393
- ]
394
- }
395
- ```
396
-
397
- ---
398
-
399
- ## Node Properties
400
-
401
- | Property | Type | Required | Default | Description |
402
- | --------------- | ------------------------------- | -------- | ----------- | ---------------------------------------------------------------------------------- |
403
- | `id` | `String` | ✅ | - | Unique node identifier |
404
- | `label` | `String \| null` | ❌ | `null` | Node display text (supports `\n` newline), border-only and text nodes can be empty |
405
- | `nodeType` | `String` | ❌ | `"server"` | Node type (see types list below) |
406
- | `image` | `String` | ❌ | - | Picture URL; aliases `src` / `img` / `imageUrl` (see "Image Nodes" below) |
407
- | `state` | `String` | ❌ | `"none"` | Node status (see status list below) |
408
- | `x` | `Number` | ✅ | - | Node X coordinate (SVG coordinate system) |
409
- | `y` | `Number` | ✅ | - | Node Y coordinate (SVG coordinate system) |
410
- | `width` | `Number` | ❌ | `60` | Node width (required for border-only nodes) |
411
- | `height` | `Number` | ❌ | `60` | Node height (required for border-only nodes) |
412
- | `rotation` | `Number` | ❌ | `0` | Node rotation angle (degrees) |
413
- | `fontColor` | `String` | ❌ | `"#ffffff"` | Text color |
414
- | `fontSize` | `Number` | ❌ | `11` | Font size |
415
- | `fontWeight` | `Number \| String` | ❌ | `500` | Font weight (100–900) |
416
- | `borderColor` | `String` | ❌ | `"#94a3b8"` | Border color |
417
- | `borderWidth` | `Number` | ❌ | `0` | Border width (0 means no border) |
418
- | `borderStyle` | `"full" \| "dashed" \| "none"` | ❌ | `"full"` | Border style: `"full"` solid, `"dashed"` dashed, `"none"` no border |
419
- | `background` | `String` | ❌ | `"#0f1729"` | Background color |
420
- | `borderRadius` | `Number` | ❌ | `6` | Corner radius (px) |
421
- | `labelPosition` | `"top" \| "center" \| "bottom"` | ❌ | `"bottom"` | Label position |
422
- | `zIndex` | `Number` | ❌ | `0` | Z-axis layer index (requires `enableZOrder`) |
423
-
424
- ### Node Types (nodeType)
425
-
426
- | Type | Icon | Description |
427
- | ---------------- | ----------------------------- | ------------------------------------------------ |
428
- | `"core"` | Hexagon | Core device |
429
- | `"server"` | Stacked rectangles | Server |
430
- | `"firewall"` | Rectangle with lines | Firewall |
431
- | `"loadbalancer"` | Circle + polyline | Load balancer |
432
- | `"database"` | Cylinder | Database |
433
- | `"cdn"` | Concentric circles | CDN node |
434
- | `"cache"` | Hexagon + center circle | Cache |
435
- | `"queue"` | Rectangle with vertical lines | Queue |
436
- | `"text"` | Text lines | Pure text node |
437
- | `"border-only"` | Hollow rectangle | Border-only node (only border outline displayed) |
438
-
439
- ### Image Nodes
440
-
441
- A node can be rendered with a picture (photo / avatar / bitmap icon). The component always scales it uniformly — it is never stretched.
442
-
443
- **Detection rules** (any one makes it an image node):
444
-
445
- | Condition | Example |
446
- | --------- | ------- |
447
- | `nodeType` is `"image"` / `"img"` / `"picture"` (case-insensitive) | `{ nodeType: "image", image: "/a.png" }` |
448
- | No `nodeType` at all, and a picture source is present | `{ image: "/a.png" }` |
449
- | `config.imageNodeBySource` is on and a picture source is present (`nodeType` ignored) | `{ nodeType: "server", image: "/a.png" }` |
450
-
451
- - The source is taken from the first non-empty field of **`image` → `src` → `img` → `imageUrl`**; it must be a non-empty (trimmed) string.
452
- - Text (`"text"`) and border-only (`"border-only"`) nodes always keep their own rendering.
453
- - A node with a `nodeType` is **not** an image node by default (its icon follows `nodeType`). For a fully photo-based graph, switch `imageNodeBySource: true`.
454
-
455
- **Filling**: `config.imageFit`
456
-
457
- | Value | Effect |
458
- | ----- | ------ |
459
- | `"contain"` (default) | The whole picture fits inside the node box, centred and letterboxed — never cropped |
460
- | `"cover"` | Fills the box along its shortest edge; the overflow on the long edge is cropped |
461
-
462
- **Slot props**: `#node-icon` receives
463
-
464
- | prop | Description |
465
- | ---- | ----------- |
466
- | `isImage` | Whether this node is treated as an image node |
467
- | `image` | Picture source (may be an empty string) |
468
- | `fit` | `"contain"` / `"cover"` |
469
- | `imageWidth` / `imageHeight` | Aspect-correct draw size for the picture (centre it on the node box) |
470
- | `width` / `height` | Node box size |
471
-
472
- ```vue
473
- <Topology :nodes="nodes" :edges="edges" :config="{ imageFit: 'contain' }">
474
- <template #node-icon="{ isImage, image, imageWidth, imageHeight }">
475
- <image
476
- v-if="isImage"
477
- :href="image"
478
- :x="-imageWidth / 2"
479
- :y="-imageHeight / 2"
480
- :width="imageWidth"
481
- :height="imageHeight"
482
- />
483
- </template>
484
- </Topology>
485
- ```
486
-
487
- ### Node Status (state)
488
-
489
- | Status | Color | Description |
490
- | ------------ | ------------ | ------------------- |
491
- | `"none"` | Hidden | No status indicator |
492
- | `"normal"` | Green | Normal |
493
- | `"warning"` | Yellow | Warning |
494
- | `"error"` | Red | Error |
495
- | `"info"` | Blue | Info |
496
- | `"active"` | Cyan | Active |
497
- | `"disabled"` | Gray | Disabled |
498
- | `"locked"` | Purple | Locked |
499
- | `"master"` | Dark red | Master node |
500
- | `"expert"` | Pink | Expert node |
501
- | `"advanced"` | Orange | Advanced node |
502
- | `"adept"` | Light orange | Adept node |
503
- | `"awakened"` | Blue | Awakened node |
504
- | `"dormant"` | Gray-purple | Dormant node |
505
-
506
- ---
507
-
508
- ## Connection Properties
509
-
510
- | Property | Type | Required | Default | Description |
511
- | ------------ | ---------------------------- | -------- | ----------- | ------------------------------------------------------------------------------------ |
512
- | `id` | `String` | ✅ | - | Unique connection identifier (auto-generated uuid) |
513
- | `from` | `String` | ✅ | - | Source node id |
514
- | `to` | `String` | ✅ | - | Target node id |
515
- | `speed` | `Number` | ❌ | `1` | Flow speed multiplier (animation speed) |
516
- | `animated` | `Boolean` | ❌ | `true` | Per-connection animation switch (`false` disables流光/particles for this connection) |
517
- | `fromAnchor` | `"center" \| "edge"` | ❌ | `"edge"` | Start anchor: `"center"` center / `"edge"` boundary intersection |
518
- | `toAnchor` | `"center" \| "edge"` | ❌ | `"edge"` | End anchor: `"center"` center / `"edge"` boundary intersection |
519
- | `fromText` | `String \| Object` | ❌ | `""` | Start text (see text format below) |
520
- | `centerText` | `String \| Object` | ❌ | `""` | Center text (see text format below) |
521
- | `toText` | `String \| Object` | ❌ | `""` | End text (see text format below) |
522
- | `endMarker` | `"none" \| "arrow" \| "dot"` | ❌ | `"none"` | End marker: `"none"` none / `"arrow"` arrow / `"dot"` dot |
523
- | `fontSize` | `Number` | ❌ | `8` | Connection text size |
524
- | `fontColor` | `String` | ❌ | `"#00f0ff"` | Connection text color |
525
-
526
- ### Connection Text Format
527
-
528
- ```javascript
529
- // String shorthand form
530
- fromText: "Start Text"
531
-
532
- // Object full form
533
- fromText: {
534
- text: "Start Text", // Text content
535
- rotation: 0, // Additional rotation angle (degrees)
536
- fontSize: 10, // Font size
537
- color: "#ffffff" // Color
538
- }
539
- ```
540
-
541
- ---
542
-
543
- ## API Methods
544
-
545
- Call methods exposed by the component via template ref:
546
-
547
- ```vue
548
- <template>
549
- <Topology ref="topoRef" />
550
- </template>
551
-
552
- <script setup>
553
- import { ref } from "vue";
554
-
555
- const topoRef = ref(null);
556
-
557
- // All method call examples
558
- const methods = () => {
559
- // === Data Methods ===
560
-
561
- // Get current latest data (deep copy)
562
- const { nodes, edges } = topoRef.value.getData();
563
-
564
- // Reset data change detection baseline
565
- topoRef.value.resetDataBaseline();
566
-
567
- // Replace entire dataset from outside
568
- topoRef.value.setData({ nodes: nextNodes });
569
-
570
- // Delete currently selected nodes and connections (deleting nodes cascades to delete all connected connections)
571
- const removed = topoRef.value.removeSelected();
572
-
573
- // Add nodes (array or single)
574
- topoRef.value.addNodes([{ label: "New Node", x: 0, y: 0 }]);
575
-
576
- // Add connections (array or single)
577
- topoRef.value.addEdges([{ from: "a", to: "b" }]);
578
-
579
- // Partially update nodes by id (shallow merge, undefined ignored, unknown ids skipped)
580
- topoRef.value.updateNodes([{ id: "node-1", label: "Renamed", width: 120 }]);
581
-
582
- // Partially update connections by id
583
- topoRef.value.updateEdges([{ id: "edge-1", speed: 2 }]);
584
-
585
- // === Layer Management (requires enableZOrder: true) ===
586
-
587
- // Move up one layer
588
- topoRef.value.moveLayerUp("node-id");
589
-
590
- // Move down one layer
591
- topoRef.value.moveLayerDown("node-id");
592
-
593
- // Move to front (highest zIndex)
594
- topoRef.value.moveToFront("node-id");
595
-
596
- // Move to back (lowest zIndex)
597
- topoRef.value.moveToBack("node-id");
598
-
599
- // === Coordinate Conversion ===
600
-
601
- // Scenario 1: Mouse coordinates → SVG coordinates (parameters can be event object or coordinate pair)
602
- const p1 = topoRef.value.clientToSvg(e); // Pass event object directly
603
- const p2 = topoRef.value.clientToSvg(clientX, y); // Pass coordinate pair
604
-
605
- // Scenario 2: SVG coordinates → Screen coordinates (input node.x / node.y, output clientX/clientY)
606
- const node = topoRef.value.getData().nodes[0];
607
- const { x, y } = topoRef.value.svgToClient(node.x, node.y);
608
- menu.style.left = `${x}px`;
609
- menu.style.top = `${y}px`;
610
- };
611
- </script>
612
- ```
613
-
614
- ---
615
-
616
- ## Events
617
-
618
- | Event Name | Parameters | Description |
619
- | ------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------- |
620
- | `update:nodes` | `nodes` | Node data update (`v-model:nodes`); continuously triggered during drag/resize |
621
- | `update:lineMode` | `string` | Connection mode change (`v-model:line-mode`) |
622
- | `update:viewMode` | `string` | View mode change (`v-model:view-mode`) |
623
- | `node-click` | `node` | Node clicked |
624
- | `node-select` | `node \| null` | Single node selection change (use `selection-change` for multi-select scenarios) |
625
- | `edge-select` | `edge \| null` | Connection selection change (merged connections include `bundleEdges` array) |
626
- | `selection-change` | `{ nodes, edges }` | Triggered when selection set changes; `nodes`/`edges` are arrays of selected node and connection objects |
627
- | `data-change` | `{ nodes, edges, summary }` | When `watchDataChanges` is enabled, triggered after data change debounce (300ms) |
628
- | `edge-create` | `edge` | Triggered after node handle drag connects two nodes |
629
- | `edge-remove` | `edges` | Triggered after deleting connections (includes cascaded deletions due to node deletion) |
630
- | `edge-update` | `edges` | Triggered after `updateEdges()` modifies connections |
631
- | `node-drag-start` | `node` | Node drag starts; also triggered when dragging multi-select set, payload is the node being held |
632
- | `node-drag-end` | — | Node drag ends |
633
- | `node-resize-start` | `node` | Resize starts |
634
- | `node-resize-end` | `node \| null` | Resize ends |
635
-
636
- ### selection-change Event Details
637
-
638
- ```javascript
639
- // Supports multiple selection methods
640
- // 1. Ctrl+click multi-select
641
- // 2. Ctrl+left-drag box select
642
- // 3. Normal click single select
643
- // 4. Click blank to clear
644
-
645
- @selection-change="(sel) => {
646
- console.log('Selected nodes:', sel.nodes.map(n => n.id));
647
- console.log('Selected connections:', sel.edges.map(e => e.id));
648
- }"
649
- ```
650
-
651
- ---
652
-
653
- ## Interactions
654
-
655
- | Operation | Gesture | Description |
656
- | ---------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
657
- | Select node/connection | Left-click | Repeated clicking unselects; clicking blank clears all |
658
- | Multi-select (point) | Ctrl (macOS ⌘) + click | Add/remove nodes/connections from selection set, supports mixed node and connection multi-select |
659
- | Multi-select (box) | Ctrl (macOS ⌘) + left-drag | Draw rectangular selection box on blank canvas, **nodes intersecting the box** are added to current selection (union semantics; only nodes participate in box select) |
660
- | Drag single node | Hold and drag anywhere on node area | Requires `editable` enabled and `config.nodeDraggable !== false`; dragging unselected node will first select it |
661
- | Drag multiple nodes | Drag any **selected** node | Selection set moves together, all nodes displace equally; selection state retained after release |
662
- | Canvas pan (infinite) | Hold left-drag on blank; or hold **middle-click** anywhere | Panning has no boundaries; content and grid move together; does not change selection state |
663
- | Zoom | Scroll wheel | Zoom centered on mouse position (0.2x–5x) |
664
- | Resize node | After selecting **single** node, drag 8 control points | Requires `editable` and `config.nodeResizable !== false` |
665
- | Create connection | Drag from node handle to target node | Requires `config.showNodeHandles: true` |
666
-
667
- ### Layer Management Keyboard Shortcuts (requires `enableZOrder`)
668
-
669
- | Shortcut | Operation |
670
- | ---------------------- | ------------------- |
671
- | `Ctrl/Cmd + Shift + ↑` | Move up one layer |
672
- | `Ctrl/Cmd + Shift + ↓` | Move down one layer |
673
- | `Ctrl/Cmd + Shift + ←` | Move to back |
674
- | `Ctrl/Cmd + Shift + →` | Move to front |
675
-
676
- ### Interaction Priority Notes
677
-
678
- - **Node and connection overlap**: Click/drag acts on **node**; connections normally clickable where not occluded—nodes always selectable and draggable in dense graphics
679
- - **Border-only node exception**: such a node is an empty frame — only its **border stroke** and **label text** are clickable, so the empty interior passes clicks through to the connections / canvas underneath (a line running through the frame stays selectable). Drag it by its border or label
680
- - **The promoted-edge layer never captures clicks**: `highlightEdgeOnTop` re-paints selected edges above the nodes for visual clarity only; it does not steal clicks from nodes or anything else
681
- - **Click vs drag distinction**: Left-click on blank distinguishes by small threshold (pan 4px / box select 3px / node drag 3px): below threshold treated as click (clear or toggle selection), above threshold enters drag mode
682
-
683
- ---
684
-
685
- ## Supplementary Notes
686
-
687
- ### Data Synchronization Mechanism
688
-
689
- `props.nodes` / `props.edges` use deep synchronization—parent replacing entire array or modifying fields in-place will update component internally; component's drag/resize/add/delete/update will also emit via `update:nodes`, `edge-create`, `edge-update`, `edge-remove` in real-time. Parent writing component-emitted data back without modification won't cause loops or duplicate reconstruction.
690
-
691
- When loading a complete new dataset, first update your `nodes` / `edges`, then call `setData()` to clean up component internal residual state.
692
-
693
- ### Node / Edge Paint Order
694
-
695
- With the default `config.edgeLayer: "split"` the paint order is:
696
-
697
- ```
698
- group boxes → node plate (background + border) → edges (base / glow / particles / text) → node content (icon / image / label / status dot)
699
- ```
700
-
701
- An edge crossing a node — or a node overlapping another node — therefore keeps running **across the node plate**, and is only partly covered by the icon itself instead of disappearing. Set `edgeLayer: "below"` for the classic "all edges under all nodes" order.
702
-
703
- With `config.highlightEdgeOnTop` (default `true`) selected edges are additionally painted above the node content, so the path under inspection is never hidden.
704
-
705
- ### TypeScript Support
706
-
707
- ```typescript
708
- import type { TopologyInstance } from "vue3-network-graph";
709
-
710
- const topoRef = ref<TopologyInstance | null>(null);
711
-
712
- // Type-safe method calls
713
- topoRef.value?.getData();
714
- topoRef.value?.clientToSvg(event);
715
- ```
716
-
717
- ### Coordinate System Notes
718
-
719
- - Component node coordinates (`node.x` / `node.y`) are in **SVG user coordinate system**
720
- - Canvas zoom and pan are implemented via `viewBox`, so conversion between this coordinate system and screen pixels varies with view state
721
- - `clientToSvg` uses matrix transformation, **automatically accounting for current zoom and pan**, returning coordinates identical to `node.x` / `node.y`
722
- - `svgToClient` is its inverse: input node coordinates, output screen `clientX` / `clientY`, suitable for DOM floating layers
723
-
724
- ---
725
-
726
- ## License
727
-
728
- [MIT](./LICENSE) © 2026 vnodegit
1
+ # vue3-network-graph Usage Guide
2
+
3
+ A lightweight network topology component based on **Vue 3 + SVG** with no third-party chart library dependencies. Supports node dragging, infinite canvas panning, zoom wheel, connection flow animations, three connection modes, multi-line overlap prevention for the same node pairs, and upright connection text along paths.
4
+
5
+ ---
6
+
7
+ ## Table of Contents
8
+
9
+ - [Name](#name)
10
+ - [Description](#description)
11
+ - [Usage](#usage)
12
+ - [Examples](#examples)
13
+ - [Global Configuration Properties](#global-configuration-properties)
14
+ - [Node Properties](#node-properties)
15
+ - [Connection Properties](#connection-properties)
16
+ - [API Methods](#api-methods)
17
+ - [Events](#events)
18
+ - [Interactions](#interactions)
19
+
20
+ ---
21
+
22
+ ## Name
23
+
24
+ **vue3-network-graph** - Vue3 Network Topology Component
25
+
26
+ ---
27
+
28
+ ## Description
29
+
30
+ A lightweight network topology component implemented with pure SVG, providing the following core capabilities:
31
+
32
+ ### Core Features
33
+
34
+ - **Multiple Connection Modes**: Straight (straight) / Polyline (polyline) / Curve (curve)
35
+ - **Smart Multi-line Handling**: Multiple connections between the same pair of nodes automatically prevent overlap, staying parallel in any mode
36
+ - **Upright Connection Text**: `fromText` / `centerText` / `toText` rotate along the path tangentially, automatically flipping when exceeding ±90° to maintain readability
37
+ - **Rich Node Types**: 8 icon nodes + text nodes + border-only nodes
38
+ - **Image Nodes**: photo / avatar / bitmap nodes, fitted at their real aspect ratio (fully contained or cover-cropped, never stretched)
39
+ - **2D/3D Views**: Supports both 2D plane and 2.5D card styles
40
+ - **Flow Animations**: Dashed流光 + particle effects, with per-connection animation control
41
+ - **Edges never get swallowed**: nodes are painted in two passes (plate below, icon / label above), so a line crossing a node — or two overlapping nodes — stays visible; the selected path is promoted to the very top
42
+
43
+ ### Interaction Capabilities
44
+
45
+ - **Node Operations**: Drag to move, drag to resize, multi-select overall drag
46
+ - **Canvas Operations**: Infinite panning (blank left-click/middle-click), zoom wheel (0.2x–5x)
47
+ - **Selection Modes**: Single-click select, Ctrl+click multi-select, Ctrl+left-drag box select
48
+ - **Connection Creation**: Auto-connect by dragging from node handle to target node
49
+ - **Layer Management**: Z-axis sorting, right-click menu, keyboard shortcuts (requires `enableZOrder`)
50
+
51
+ ### Performance Optimization
52
+
53
+ - **Automatic Degradation**: Decorative animations automatically disabled based on scale (connections>200 disable流光,>500 disable glow, nodes>300 disable breathing)
54
+ - **Large-scale Performance**: Thousands of nodes can pan/drag smoothly, nodes always responsive to clicks in dense graphics
55
+
56
+ ---
57
+
58
+ ## Usage
59
+
60
+ ### 1. Installation
61
+
62
+ ```bash
63
+ npm install vue3-network-graph
64
+ # or: pnpm add vue3-network-graph | yarn add vue3-network-graph
65
+ ```
66
+
67
+ ### 2. Import Component
68
+
69
+ ```js
70
+ // main.js
71
+ import { createApp } from "vue";
72
+ import { Topology } from "vue3-network-graph";
73
+ import "vue3-network-graph/style.css";
74
+
75
+ const app = createApp(App);
76
+ app.component("Topology", Topology);
77
+ app.mount("#app");
78
+ ```
79
+
80
+ Or local import:
81
+
82
+ ```vue
83
+ <script setup>
84
+ import { Topology } from "vue3-network-graph";
85
+ import "vue3-network-graph/style.css";
86
+ </script>
87
+ ```
88
+
89
+ ### 3. Basic Usage
90
+
91
+ ```vue
92
+ <template>
93
+ <Topology
94
+ ref="topoRef"
95
+ :editable="true"
96
+ v-model:nodes="myNodes"
97
+ v-model:edges="myEdges"
98
+ :config="config"
99
+ @node-click="handleNodeClick"
100
+ @selection-change="handleSelectionChange"
101
+ />
102
+ </template>
103
+
104
+ <script setup>
105
+ import { ref } from "vue";
106
+ import { Topology } from "vue3-network-graph";
107
+
108
+ const myNodes = ref([
109
+ { id: "node1", label: "Node 1", type: "core", state: "normal", x: 0, y: 0 },
110
+ {
111
+ id: "node2",
112
+ label: "Node 2",
113
+ type: "server",
114
+ state: "normal",
115
+ x: 200,
116
+ y: 100,
117
+ },
118
+ ]);
119
+
120
+ const myEdges = ref([
121
+ { id: "edge1", from: "node1", to: "node2", centerText: "Connection" },
122
+ ]);
123
+
124
+ const config = ref({
125
+ showGrid: true,
126
+ nodeDraggable: true,
127
+ nodeResizable: true,
128
+ });
129
+ </script>
130
+ ```
131
+
132
+ ---
133
+
134
+ ## Examples
135
+
136
+ ### Complete Example
137
+
138
+ ```vue
139
+ <template>
140
+ <div class="topology-container">
141
+ <Topology
142
+ ref="topoRef"
143
+ :editable="true"
144
+ v-model:nodes="nodes"
145
+ v-model:edges="edges"
146
+ v-model:line-mode="lineMode"
147
+ v-model:view-mode="viewMode"
148
+ :groups="groups"
149
+ :config="config"
150
+ @node-click="onNodeClick"
151
+ @edge-select="onEdgeSelect"
152
+ @selection-change="onSelectionChange"
153
+ @data-change="onDataChange"
154
+ @edge-create="onEdgeCreate"
155
+ >
156
+ <!-- Custom node icon slot -->
157
+ <template #node-icon="{ node, color, viewMode }">
158
+ <circle r="16" :fill="color" opacity="0.9" />
159
+ </template>
160
+ </Topology>
161
+ </div>
162
+ </template>
163
+
164
+ <script setup>
165
+ import { ref, onMounted } from "vue";
166
+ import { Topology } from "vue3-network-graph";
167
+ import "vue3-network-graph/style.css";
168
+
169
+ // Node data
170
+ const nodes = ref([
171
+ {
172
+ id: "core",
173
+ label: "Core Switch",
174
+ nodeType: "core",
175
+ state: "normal",
176
+ x: 0,
177
+ y: 0,
178
+ width: 80,
179
+ height: 80,
180
+ },
181
+ {
182
+ id: "server1",
183
+ label: "Web Server",
184
+ nodeType: "server",
185
+ state: "normal",
186
+ x: 300,
187
+ y: -150,
188
+ },
189
+ {
190
+ id: "db1",
191
+ label: "Database",
192
+ nodeType: "database",
193
+ state: "idle",
194
+ x: 300,
195
+ y: 150,
196
+ },
197
+ // Border-only node example
198
+ {
199
+ id: "border-box",
200
+ label: "",
201
+ nodeType: "border-only",
202
+ state: "none",
203
+ x: -400,
204
+ y: -200,
205
+ width: 250,
206
+ height: 150,
207
+ borderWidth: 2,
208
+ borderColor: "#00f0ff",
209
+ },
210
+ ]);
211
+
212
+ // Connection data
213
+ const edges = ref([
214
+ { id: "e1", from: "core", to: "server1", speed: 1.5, endMarker: "arrow" },
215
+ {
216
+ id: "e2",
217
+ from: "core",
218
+ to: "db1",
219
+ speed: 2,
220
+ centerText: "Query Traffic",
221
+ endMarker: "arrow",
222
+ },
223
+ ]);
224
+
225
+ // Group example
226
+ const groups = ref([
227
+ {
228
+ id: "g1",
229
+ label: "Application Zone",
230
+ color: "#409eff",
231
+ nodeIds: ["server1", "db1"],
232
+ padding: 20,
233
+ },
234
+ ]);
235
+
236
+ // Connection mode and view mode
237
+ const lineMode = ref("curve"); // straight | polyline | curve
238
+ const viewMode = ref("2d"); // 2d | 3d
239
+
240
+ // Configuration
241
+ const config = ref({
242
+ selectedBorderColor: "#ffd400",
243
+ selectedLineColor: "#ffd400",
244
+ nodeDraggable: true,
245
+ nodeResizable: true,
246
+ enableZoom: true,
247
+ enablePan: true,
248
+ enableMarquee: true,
249
+ showGrid: true,
250
+ gridColor: "#1a2240",
251
+ gridStep: 40,
252
+ gridOpacity: 0.5,
253
+ radialGradient: {
254
+ startColor: "#0f1729",
255
+ endColor: "#060a14",
256
+ },
257
+ showStatusDot: true,
258
+ motionFx: true,
259
+ maxSelectNodes: "unlimited",
260
+ maxSelectEdges: "unlimited",
261
+ enableZOrder: false,
262
+ });
263
+
264
+ // Component instance reference
265
+ const topoRef = ref(null);
266
+
267
+ // Event handlers
268
+ const onNodeClick = (node) => {
269
+ console.log("Node clicked:", node);
270
+ };
271
+
272
+ const onEdgeSelect = (edge) => {
273
+ console.log("Connection selected:", edge);
274
+ };
275
+
276
+ const onSelectionChange = (selection) => {
277
+ console.log("Selection changed:", selection);
278
+ console.log("Selected nodes:", selection.nodes);
279
+ console.log("Selected connections:", selection.edges);
280
+ };
281
+
282
+ const onDataChange = (payload) => {
283
+ console.log("Data changed:", payload);
284
+ console.log("Change summary:", payload.summary);
285
+ };
286
+
287
+ const onEdgeCreate = (edge) => {
288
+ console.log("New connection:", edge);
289
+ // Persist newly created connection
290
+ edges.value = [...edges.value, edge];
291
+ };
292
+
293
+ // Method call examples
294
+ const handleMethods = () => {
295
+ // Get current data
296
+ const data = topoRef.value.getData();
297
+
298
+ // Add nodes
299
+ topoRef.value.addNodes([
300
+ { label: "New Node", nodeType: "server", x: 500, y: 0 },
301
+ ]);
302
+
303
+ // Add connections
304
+ topoRef.value.addEdges([{ from: "core", to: "new-node-id" }]);
305
+
306
+ // Update nodes
307
+ topoRef.value.updateNodes([{ id: "core", label: "Updated Name" }]);
308
+
309
+ // Delete selected elements
310
+ topoRef.value.removeSelected();
311
+
312
+ // Coordinate conversion
313
+ const svgPos = topoRef.value.clientToSvg(event);
314
+ const clientPos = topoRef.value.svgToClient(node.x, node.y);
315
+
316
+ // Layer management (requires enableZOrder)
317
+ topoRef.value.moveToFront("node-id");
318
+ topoRef.value.moveToBack("node-id");
319
+ topoRef.value.moveLayerUp("node-id");
320
+ topoRef.value.moveLayerDown("node-id");
321
+ };
322
+ </script>
323
+
324
+ <style scoped>
325
+ .topology-container {
326
+ width: 100%;
327
+ height: 600px;
328
+ background: radial-gradient(ellipse at center, #0f1729 0%, #060a14 100%);
329
+ }
330
+ </style>
331
+ ```
332
+
333
+ ---
334
+
335
+ ## Global Configuration Properties
336
+
337
+ | Config Item | Type | Default | Description |
338
+ | --------------------- | ----------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
339
+ | `selectedBorderColor` | `String` | `#fbbf24` | Selected node border color |
340
+ | `selectedLineColor` | `String` | `#fbbf24` | Selected connection color |
341
+ | `nodeDraggable` | `Boolean` | `true` | Node drag switch (requires `editable`) |
342
+ | `nodeResizable` | `Boolean` | `true` | Node resize switch (requires `editable`) |
343
+ | `enableZoom` | `Boolean` | `true` | Zoom wheel switch |
344
+ | `enablePan` | `Boolean` | `true` | Canvas pan switch |
345
+ | `enableMarquee` | `Boolean` | `true` | Ctrl + left-drag box select switch |
346
+ | `maxSelectNodes` | `Number \| "unlimited"` | Unlimited | Max selectable nodes: `0` (disabled) / `1` / `2` or any non-negative integer; unset or `"unlimited"` no limit |
347
+ | `maxSelectEdges` | `Number \| "unlimited"` | Unlimited | Max selectable connections (merged bundles count all connections in group) |
348
+ | `showGrid` | `Boolean` | `true` | Grid background (set `false` to disable) |
349
+ | `gridColor` | `String` | `#1a2240` | Grid line color |
350
+ | `gridStep` | `Number` | `40` | Grid spacing (px at 1x zoom, scales with zoom) |
351
+ | `gridOpacity` | `Number` | `0.5` | Grid overlay opacity (0–1) |
352
+ | `radialGradient` | `Object` | See notes | Canvas background radial gradient |
353
+ | `showCenterPoint` | `Boolean` | `false` | Canvas center cross marker |
354
+ | `showEdgeTextBg` | `Boolean` | `false` | Connection text background |
355
+ | `edgeTextBgColor` | `String` | `#0a0e1a` | Connection text background color |
356
+ | `edgeCenterTextFollowLine` | `Boolean` | `true` | Whether the center label rotates along the line: `true` follows the line tangent (current), `false` always stays horizontal |
357
+ | `showNodeHandles` | `Boolean` | `false` | Node handles (four small circles appear at top/bottom/left/right of nodes, auto-connect when dragged to another node) |
358
+ | `showStatusDot` | `Boolean` | `true` | Status dot at top-right corner of each node |
359
+ | `labelGap` | `Number` | `18` | Fixed gap between node box edge and its label (px at 1x zoom) |
360
+ | `watchDataChanges` | `Boolean` | `false` | Component internal data change detection (debounce 300ms then trigger `data-change`) |
361
+ | `fx` | `Boolean` | Auto | Master decorative animation switch: `false` all off / `true` all on / unset = auto |
362
+ | `motionFx` | `Boolean` | Auto | Per-feature override - connection line animation (flow + particles) |
363
+ | `glowFx` | `Boolean` | Auto | Per-feature override - connection glow |
364
+ | `breatheFx` | `Boolean` | Auto | Per-feature override - alert breathing ring: `false` disables it, `true` forces it on (ignores the size gate) |
365
+ | `alertStates` | `String[]` | See notes | States that trigger the breathing ring; defaults to `["warning","error","master"]`. Every other state only recolors the node, no animation |
366
+ | `alertStyle` | `"ring" \| "fill" \| "ripple" \| "blink"` | `"ring"` | Alert animation style: ring = expanding outline (error/master add an offset second ring) / fill = solid breathing disc / ripple = three staggered waves / blink = hard strobe; per-node override via `node.alertStyle` |
367
+ | `alertGlow` | `Boolean` | `true` | Edge gradient glow of the `fill` solid breathing disc (bright rim + soft outward falloff); set `false` for a plain solid disc |
368
+ | `fxMotionMaxEdges` | `Number` | `200` | Edge count above which flow + particle animation auto-disables |
369
+ | `fxGlowMaxEdges` | `Number` | `500` | Edge count above which edge glow auto-disables |
370
+ | `fxAlertMaxNodes` | `Number` | `300` | Alert node count above which breathing rings auto-disable (counts alert nodes only, so a big graph no longer kills every alert) |
371
+ | `fxBreatheMaxNodes` | `Number` | `300` | Legacy node-count threshold (superseded by `fxAlertMaxNodes`, kept for compatibility) |
372
+ | `enableZOrder` | `Boolean` | `false` | **Enable Z-axis layer sorting**: After enabling, nodes render according to `zIndex` property, supporting layer operation API, right-click menu and keyboard shortcuts |
373
+ | `enableDeleteKey` | `Boolean` | `true` | Delete / Backspace removes the current selection (requires `editable`); when the parent listens to `delete-request` the component only emits the event |
374
+ | `imageFit` | `"contain" \| "cover"` | `"contain"` | How image nodes fill their box: `contain` keeps the whole picture inside the box (centred, letterboxed, never cropped); `cover` fills the box and crops the overflow. Both scale uniformly — the picture is never stretched |
375
+ | `imageNodeBySource` | `Boolean` | `false` | **Global image-node rule**: when `true`, any node carrying a picture source is rendered as an image node (its `nodeType` is ignored); text and border-only nodes are unaffected |
376
+ | `edgeLayer` | `"split" \| "below"` | `"split"` | Paint order of nodes vs edges: `split` paints each node in two passes — plate + border below, icon / image / label above, with edges in between (a line crossing a node stays visible); `below` is the classic "all edges under all nodes" |
377
+ | `highlightEdgeOnTop` | `Boolean` | `true` | Selected edges are re-painted above the node layer so the highlighted path is never hidden by a node plate or icon (decoration only — it never captures clicks) |
378
+
379
+ ### radialGradient Configuration
380
+
381
+ ```javascript
382
+ // Simple mode
383
+ radialGradient: {
384
+ startColor: "#0f1729",
385
+ endColor: "#060a14"
386
+ }
387
+
388
+ // Advanced mode (custom gradient center and color stops)
389
+ radialGradient: {
390
+ cx: "50%",
391
+ cy: "50%",
392
+ r: "50%",
393
+ stops: [
394
+ { offset: "0%", color: "#0f1729", opacity: 1 },
395
+ { offset: "60%", color: "#1e293b", opacity: 0.8 },
396
+ { offset: "100%", color: "#060a14", opacity: 1 }
397
+ ]
398
+ }
399
+ ```
400
+
401
+ ---
402
+
403
+ ## Node Properties
404
+
405
+ | Property | Type | Required | Default | Description |
406
+ | --------------- | ------------------------------- | -------- | ----------- | ---------------------------------------------------------------------------------- |
407
+ | `id` | `String` | ✅ | - | Unique node identifier |
408
+ | `label` | `String \| null` | ❌ | `null` | Node display text (supports `\n` newline), border-only and text nodes can be empty |
409
+ | `nodeType` | `String` | ❌ | `"server"` | Node type (see types list below) |
410
+ | `image` | `String` | ❌ | - | Picture URL; aliases `src` / `img` / `imageUrl` (see "Image Nodes" below) |
411
+ | `state` | `String` | ❌ | `"none"` | Node status (see status list below) |
412
+ | `alertStyle` | `String` | ❌ | - | Per-node alert animation override (`ring` / `fill` / `ripple` / `blink`, see `config.alertStyle`) |
413
+ | `x` | `Number` | ✅ | - | Node X coordinate (SVG coordinate system) |
414
+ | `y` | `Number` | ✅ | - | Node Y coordinate (SVG coordinate system) |
415
+ | `width` | `Number` | ❌ | `60` | Node width (required for border-only nodes) |
416
+ | `height` | `Number` | ❌ | `60` | Node height (required for border-only nodes) |
417
+ | `rotation` | `Number` | ❌ | `0` | Node rotation angle (degrees) |
418
+ | `fontColor` | `String` | ❌ | `"#ffffff"` | Text color |
419
+ | `fontSize` | `Number` | ❌ | `11` | Font size |
420
+ | `fontWeight` | `Number \| String` | ❌ | `500` | Font weight (100–900) |
421
+ | `borderColor` | `String` | ❌ | `"#94a3b8"` | Border color |
422
+ | `borderWidth` | `Number` | ❌ | `0` | Border width (0 means no border) |
423
+ | `borderStyle` | `"full" \| "dashed" \| "none"` | ❌ | `"full"` | Border style: `"full"` solid, `"dashed"` dashed, `"none"` no border |
424
+ | `background` | `String` | ❌ | `"#0f1729"` | Background color |
425
+ | `borderRadius` | `Number` | ❌ | `6` | Corner radius (px) |
426
+ | `labelPosition` | `"top" \| "center" \| "bottom"` | ❌ | `"bottom"` | Label position |
427
+ | `zIndex` | `Number` | ❌ | `0` | Z-axis layer index (requires `enableZOrder`) |
428
+
429
+ ### Node Types (nodeType)
430
+
431
+ | Type | Icon | Description |
432
+ | ---------------- | ----------------------------- | ------------------------------------------------ |
433
+ | `"core"` | Hexagon | Core device |
434
+ | `"server"` | Stacked rectangles | Server |
435
+ | `"firewall"` | Rectangle with lines | Firewall |
436
+ | `"loadbalancer"` | Circle + polyline | Load balancer |
437
+ | `"database"` | Cylinder | Database |
438
+ | `"cdn"` | Concentric circles | CDN node |
439
+ | `"cache"` | Hexagon + center circle | Cache |
440
+ | `"queue"` | Rectangle with vertical lines | Queue |
441
+ | `"text"` | Text lines | Pure text node |
442
+ | `"border-only"` | Hollow rectangle | Border-only node (only border outline displayed) |
443
+
444
+ ### Image Nodes
445
+
446
+ A node can be rendered with a picture (photo / avatar / bitmap icon). The component always scales it uniformly — it is never stretched.
447
+
448
+ **Detection rules** (any one makes it an image node):
449
+
450
+ | Condition | Example |
451
+ | --------- | ------- |
452
+ | `nodeType` is `"image"` / `"img"` / `"picture"` (case-insensitive) | `{ nodeType: "image", image: "/a.png" }` |
453
+ | No `nodeType` at all, and a picture source is present | `{ image: "/a.png" }` |
454
+ | `config.imageNodeBySource` is on and a picture source is present (`nodeType` ignored) | `{ nodeType: "server", image: "/a.png" }` |
455
+
456
+ - The source is taken from the first non-empty field of **`image` → `src` → `img` → `imageUrl`**; it must be a non-empty (trimmed) string.
457
+ - Text (`"text"`) and border-only (`"border-only"`) nodes always keep their own rendering.
458
+ - A node with a `nodeType` is **not** an image node by default (its icon follows `nodeType`). For a fully photo-based graph, switch `imageNodeBySource: true`.
459
+
460
+ **Filling**: `config.imageFit`
461
+
462
+ | Value | Effect |
463
+ | ----- | ------ |
464
+ | `"contain"` (default) | The whole picture fits inside the node box, centred and letterboxed — never cropped |
465
+ | `"cover"` | Fills the box along its shortest edge; the overflow on the long edge is cropped |
466
+
467
+ **Slot props**: `#node-icon` receives
468
+
469
+ | prop | Description |
470
+ | ---- | ----------- |
471
+ | `isImage` | Whether this node is treated as an image node |
472
+ | `image` | Picture source (may be an empty string) |
473
+ | `fit` | `"contain"` / `"cover"` |
474
+ | `imageWidth` / `imageHeight` | Aspect-correct draw size for the picture (centre it on the node box) |
475
+ | `width` / `height` | Node box size |
476
+
477
+ ```vue
478
+ <Topology :nodes="nodes" :edges="edges" :config="{ imageFit: 'contain' }">
479
+ <template #node-icon="{ isImage, image, imageWidth, imageHeight }">
480
+ <image
481
+ v-if="isImage"
482
+ :href="image"
483
+ :x="-imageWidth / 2"
484
+ :y="-imageHeight / 2"
485
+ :width="imageWidth"
486
+ :height="imageHeight"
487
+ />
488
+ </template>
489
+ </Topology>
490
+ ```
491
+
492
+ ### Node Status (state)
493
+
494
+ | Status | Color | Description |
495
+ | ------------ | ------------ | ------------------- |
496
+ | `"none"` | Hidden | No status indicator |
497
+ | `"normal"` | Green | Normal |
498
+ | `"warning"` | Yellow | Warning |
499
+ | `"error"` | Red | Error |
500
+ | `"info"` | Blue | Info |
501
+ | `"active"` | Cyan | Active |
502
+ | `"disabled"` | Gray | Disabled |
503
+ | `"locked"` | Purple | Locked |
504
+ | `"master"` | Dark red | Master node |
505
+ | `"expert"` | Pink | Expert node |
506
+ | `"advanced"` | Orange | Advanced node |
507
+ | `"adept"` | Light orange | Adept node |
508
+ | `"awakened"` | Blue | Awakened node |
509
+ | `"dormant"` | Gray-purple | Dormant node |
510
+
511
+ ---
512
+
513
+ ## Connection Properties
514
+
515
+ | Property | Type | Required | Default | Description |
516
+ | ------------ | ---------------------------- | -------- | ----------- | ------------------------------------------------------------------------------------ |
517
+ | `id` | `String` | ✅ | - | Unique connection identifier (auto-generated uuid) |
518
+ | `from` | `String` | ✅ | - | Source node id |
519
+ | `to` | `String` | ✅ | - | Target node id |
520
+ | `speed` | `Number` | ❌ | `1` | Flow speed multiplier (animation speed) |
521
+ | `animated` | `Boolean` | ❌ | `true` | Per-connection animation switch (`false` disables流光/particles for this connection) |
522
+ | `fromAnchor` | `"center" \| "edge"` | ❌ | `"edge"` | Start anchor: `"center"` center / `"edge"` boundary intersection |
523
+ | `toAnchor` | `"center" \| "edge"` | ❌ | `"edge"` | End anchor: `"center"` center / `"edge"` boundary intersection |
524
+ | `fromText` | `String \| Object` | ❌ | `""` | Start text (see text format below) |
525
+ | `centerText` | `String \| Object` | ❌ | `""` | Center text (see text format below) |
526
+ | `toText` | `String \| Object` | ❌ | `""` | End text (see text format below) |
527
+ | `endMarker` | `"none" \| "arrow" \| "dot"` | ❌ | `"none"` | End marker: `"none"` none / `"arrow"` arrow / `"dot"` dot |
528
+ | `fontSize` | `Number` | ❌ | `8` | Connection text size |
529
+ | `fontColor` | `String` | ❌ | `"#00f0ff"` | Connection text color |
530
+
531
+ ### Connection Text Format
532
+
533
+ ```javascript
534
+ // String shorthand form
535
+ fromText: "Start Text"
536
+
537
+ // Object full form
538
+ fromText: {
539
+ text: "Start Text", // Text content
540
+ rotation: 0, // Additional rotation angle (degrees)
541
+ fontSize: 10, // Font size
542
+ color: "#ffffff" // Color
543
+ }
544
+ ```
545
+
546
+ ---
547
+
548
+ ## API Methods
549
+
550
+ Call methods exposed by the component via template ref:
551
+
552
+ ```vue
553
+ <template>
554
+ <Topology ref="topoRef" />
555
+ </template>
556
+
557
+ <script setup>
558
+ import { ref } from "vue";
559
+
560
+ const topoRef = ref(null);
561
+
562
+ // All method call examples
563
+ const methods = () => {
564
+ // === Data Methods ===
565
+
566
+ // Get current latest data (deep copy)
567
+ const { nodes, edges } = topoRef.value.getData();
568
+
569
+ // Reset data change detection baseline
570
+ topoRef.value.resetDataBaseline();
571
+
572
+ // Replace entire dataset from outside
573
+ topoRef.value.setData({ nodes: nextNodes });
574
+
575
+ // Delete currently selected nodes and connections (deleting nodes cascades to delete all connected connections)
576
+ const removed = topoRef.value.removeSelected();
577
+
578
+ // Add nodes (array or single)
579
+ topoRef.value.addNodes([{ label: "New Node", x: 0, y: 0 }]);
580
+
581
+ // Add connections (array or single)
582
+ topoRef.value.addEdges([{ from: "a", to: "b" }]);
583
+
584
+ // Partially update nodes by id (shallow merge, undefined ignored, unknown ids skipped)
585
+ topoRef.value.updateNodes([{ id: "node-1", label: "Renamed", width: 120 }]);
586
+
587
+ // Partially update connections by id
588
+ topoRef.value.updateEdges([{ id: "edge-1", speed: 2 }]);
589
+
590
+ // === Layer Management (requires enableZOrder: true) ===
591
+
592
+ // Move up one layer
593
+ topoRef.value.moveLayerUp("node-id");
594
+
595
+ // Move down one layer
596
+ topoRef.value.moveLayerDown("node-id");
597
+
598
+ // Move to front (highest zIndex)
599
+ topoRef.value.moveToFront("node-id");
600
+
601
+ // Move to back (lowest zIndex)
602
+ topoRef.value.moveToBack("node-id");
603
+
604
+ // === Coordinate Conversion ===
605
+
606
+ // Scenario 1: Mouse coordinates → SVG coordinates (parameters can be event object or coordinate pair)
607
+ const p1 = topoRef.value.clientToSvg(e); // Pass event object directly
608
+ const p2 = topoRef.value.clientToSvg(clientX, y); // Pass coordinate pair
609
+
610
+ // Scenario 2: SVG coordinates → Screen coordinates (input node.x / node.y, output clientX/clientY)
611
+ const node = topoRef.value.getData().nodes[0];
612
+ const { x, y } = topoRef.value.svgToClient(node.x, node.y);
613
+ menu.style.left = `${x}px`;
614
+ menu.style.top = `${y}px`;
615
+ };
616
+ </script>
617
+ ```
618
+
619
+ ---
620
+
621
+ ## Events
622
+
623
+ | Event Name | Parameters | Description |
624
+ | ------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------- |
625
+ | `update:nodes` | `nodes` | Node data update (`v-model:nodes`); continuously triggered during drag/resize |
626
+ | `update:lineMode` | `string` | Connection mode change (`v-model:line-mode`) |
627
+ | `update:viewMode` | `string` | View mode change (`v-model:view-mode`) |
628
+ | `node-click` | `node` | Node clicked |
629
+ | `node-select` | `node \| null` | Single node selection change (use `selection-change` for multi-select scenarios) |
630
+ | `edge-select` | `edge \| null` | Connection selection change (merged connections include `bundleEdges` array) |
631
+ | `selection-change` | `{ nodes, edges }` | Triggered when selection set changes; `nodes`/`edges` are arrays of selected node and connection objects |
632
+ | `data-change` | `{ nodes, edges, summary }` | When `watchDataChanges` is enabled, triggered after data change debounce (300ms) |
633
+ | `edge-create` | `edge` | Triggered after node handle drag connects two nodes |
634
+ | `edge-remove` | `edges` | Triggered after deleting connections (includes cascaded deletions due to node deletion) |
635
+ | `edge-update` | `edges` | Triggered after `updateEdges()` modifies connections |
636
+ | `node-drag-start` | `node` | Node drag starts; also triggered when dragging multi-select set, payload is the node being held |
637
+ | `node-drag-end` | — | Node drag ends |
638
+ | `node-resize-start` | `node` | Resize starts |
639
+ | `node-resize-end` | `node \| null` | Resize ends |
640
+
641
+ ### selection-change Event Details
642
+
643
+ ```javascript
644
+ // Supports multiple selection methods
645
+ // 1. Ctrl+click multi-select
646
+ // 2. Ctrl+left-drag box select
647
+ // 3. Normal click single select
648
+ // 4. Click blank to clear
649
+
650
+ @selection-change="(sel) => {
651
+ console.log('Selected nodes:', sel.nodes.map(n => n.id));
652
+ console.log('Selected connections:', sel.edges.map(e => e.id));
653
+ }"
654
+ ```
655
+
656
+ ---
657
+
658
+ ## Interactions
659
+
660
+ | Operation | Gesture | Description |
661
+ | ---------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
662
+ | Select node/connection | Left-click | Repeated clicking unselects; clicking blank clears all |
663
+ | Multi-select (point) | Ctrl (macOS ⌘) + click | Add/remove nodes/connections from selection set, supports mixed node and connection multi-select |
664
+ | Multi-select (box) | Ctrl (macOS ⌘) + left-drag | Draw rectangular selection box on blank canvas, **nodes intersecting the box** are added to current selection (union semantics; only nodes participate in box select) |
665
+ | Drag single node | Hold and drag anywhere on node area | Requires `editable` enabled and `config.nodeDraggable !== false`; dragging unselected node will first select it |
666
+ | Drag multiple nodes | Drag any **selected** node | Selection set moves together, all nodes displace equally; selection state retained after release |
667
+ | Canvas pan (infinite) | Hold left-drag on blank; or hold **middle-click** anywhere | Panning has no boundaries; content and grid move together; does not change selection state |
668
+ | Zoom | Scroll wheel | Zoom centered on mouse position (0.2x–5x) |
669
+ | Resize node | After selecting **single** node, drag 8 control points | Requires `editable` and `config.nodeResizable !== false` |
670
+ | Create connection | Drag from node handle to target node | Requires `config.showNodeHandles: true` |
671
+
672
+ ### Layer Management Keyboard Shortcuts (requires `enableZOrder`)
673
+
674
+ | Shortcut | Operation |
675
+ | ---------------------- | ------------------- |
676
+ | `Ctrl/Cmd + Shift + ↑` | Move up one layer |
677
+ | `Ctrl/Cmd + Shift + ↓` | Move down one layer |
678
+ | `Ctrl/Cmd + Shift + ←` | Move to back |
679
+ | `Ctrl/Cmd + Shift + →` | Move to front |
680
+
681
+ ### Interaction Priority Notes
682
+
683
+ - **Node and connection overlap**: Click/drag acts on **node**; connections normally clickable where not occluded—nodes always selectable and draggable in dense graphics
684
+ - **Border-only node exception**: such a node is an empty frame — only its **border stroke** and **label text** are clickable, so the empty interior passes clicks through to the connections / canvas underneath (a line running through the frame stays selectable). Drag it by its border or label
685
+ - **The promoted-edge layer never captures clicks**: `highlightEdgeOnTop` re-paints selected edges above the nodes for visual clarity only; it does not steal clicks from nodes or anything else
686
+ - **Click vs drag distinction**: Left-click on blank distinguishes by small threshold (pan 4px / box select 3px / node drag 3px): below threshold treated as click (clear or toggle selection), above threshold enters drag mode
687
+
688
+ ---
689
+
690
+ ## Supplementary Notes
691
+
692
+ ### Data Synchronization Mechanism
693
+
694
+ `props.nodes` / `props.edges` use deep synchronization—parent replacing entire array or modifying fields in-place will update component internally; component's drag/resize/add/delete/update will also emit via `update:nodes`, `edge-create`, `edge-update`, `edge-remove` in real-time. Parent writing component-emitted data back without modification won't cause loops or duplicate reconstruction.
695
+
696
+ When loading a complete new dataset, first update your `nodes` / `edges`, then call `setData()` to clean up component internal residual state.
697
+
698
+ ### Node / Edge Paint Order
699
+
700
+ With the default `config.edgeLayer: "split"` the paint order is:
701
+
702
+ ```
703
+ group boxes → node plate (background + border) → edges (base / glow / particles / text) → node content (icon / image / label / status dot)
704
+ ```
705
+
706
+ An edge crossing a node — or a node overlapping another node — therefore keeps running **across the node plate**, and is only partly covered by the icon itself instead of disappearing. Set `edgeLayer: "below"` for the classic "all edges under all nodes" order.
707
+
708
+ With `config.highlightEdgeOnTop` (default `true`) selected edges are additionally painted above the node content, so the path under inspection is never hidden.
709
+
710
+ ### TypeScript Support
711
+
712
+ ```typescript
713
+ import type { TopologyInstance } from "vue3-network-graph";
714
+
715
+ const topoRef = ref<TopologyInstance | null>(null);
716
+
717
+ // Type-safe method calls
718
+ topoRef.value?.getData();
719
+ topoRef.value?.clientToSvg(event);
720
+ ```
721
+
722
+ ### Coordinate System Notes
723
+
724
+ - Component node coordinates (`node.x` / `node.y`) are in **SVG user coordinate system**
725
+ - Canvas zoom and pan are implemented via `viewBox`, so conversion between this coordinate system and screen pixels varies with view state
726
+ - `clientToSvg` uses matrix transformation, **automatically accounting for current zoom and pan**, returning coordinates identical to `node.x` / `node.y`
727
+ - `svgToClient` is its inverse: input node coordinates, output screen `clientX` / `clientY`, suitable for DOM floating layers
728
+
729
+ ---
730
+
731
+ ## License
732
+
733
+ [MIT](./LICENSE) © 2026 vnodegit