Compare commits

...
107 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 cce6e21a09 feat(i18n): translate UI to English and German
Use English as source language for all user-visible strings, wrap them for
translation and ship a German catalog. Add a test that keeps the README's
NetBox range in sync with min_version/max_version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 21:25:38 +01:00
MrBlakeandClaude Opus 5.5 133cb1d9fc docs: add screenshots and generalise README
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 20:57:59 +01:00
MrBlakeandClaude Opus 5.5 e4d1383e8c Pass a relative path to static() for device images
A leading slash made static file finders, such as the one used by the debug toolbar with DEBUG = True, raise SuspiciousFileOperation on the Images page. The generated URL is unchanged. Verified on NetBox 4.7.2.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 15:08:50 +02:00
MrBlakeandClaude Opus 5.5 ffe594a5f9 docs: rewrite README in English with standard structure
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-30 13:37:00 +02:00
MrBlakeandClaude Sonnet 5 4a12037ac4 fix: show wireless links between devices only reachable via other cables
WirelessLink lookups only matched devices already in the selected racks
(device_ids), so a link between two purely external devices that were
pulled into the topology only as endpoints of unrelated cables (e.g. two
outdoor radios each cabled to something inside the selected racks) never
showed up, even though both endpoint nodes were already rendered.

Now the wireless query also matches devices discovered via the cable
pass (topology_nodes), so links between already-visible external nodes
are drawn too.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-17 12:01:02 +02:00
MrBlakeandClaude Sonnet 5 f08df4fd52 fix: detect power cables by termination type and move toggle into topology card
Power-cable detection previously relied on cable.type, which is usually
unset for power patch cables (e.g. PDU-to-PDU), so they never got the
distinct color. Power cables are now also detected by termination
component type (PowerPort/PowerOutlet/PowerFeed).

Wireless/power display is now toggled client-side via checkboxes in the
Kabeltopologie card header (before the SVG/PNG/draw.io export buttons)
instead of a server round-trip through the top filter form, so toggling
is instant and affects exports too.

Bump plugin version to 4.5.2.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-17 10:45:27 +02:00
MrBlakeandClaude Sonnet 5 2e43166949 feat: declare NetBox 4.7.x support and add wireless/power toggle to Kabeltopologie
Adds min_version/max_version to the plugin config for NetBox 4.7.x and
extends the rack view's cable topology with optional wireless and power
cable display, rendered with distinct colors and dash patterns from
regular network cables.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-17 10:36:47 +02:00
MrBlake 86a8daf45e Merge branch 'develop' of https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views into develop 2026-08-06 14:38:20 +02:00
MrBlake f706db754c fix: respect rack unit numbering direction and starting unit 2026-08-06 14:38:16 +02:00
MrBlake c49270fab0 x 2026-07-28 15:06:14 +02:00
MrBlake 6ff2b60bb4 fix: enforce flex layout for topology device spacing 2026-07-28 15:00:32 +02:00
MrBlake ef1ad4d607 fix: enforce topology spacing and light-mode cable highlights 2026-07-28 14:58:13 +02:00
MrBlake a1d28e922d fix: improve cable count badge contrast 2026-07-28 14:48:33 +02:00
MrBlake d9d2e4dd59 fix: detect NetBox theme for topology cable highlights 2026-07-28 14:47:39 +02:00
MrBlake cff9282a60 style: use green cable highlights in light mode 2026-07-28 14:43:20 +02:00
MrBlake 1f80ae5099 fix: improve topology spacing zoom scrolling and wireless support 2026-07-28 14:42:41 +02:00
MrBlake 4680209d83 feat: add fullscreen topology and wireless links 2026-07-28 14:36:08 +02:00
MrBlake bb0693bef7 fix: sort topology devices without rendering rack elevations 2026-07-28 14:32:34 +02:00
MrBlake 1de5ed0565 feat: align topology nodes with racks and add theme-aware exports 2026-07-28 14:26:28 +02:00
MrBlake 1ff68d7026 fix: export all rendered devices from rack elevations 2026-07-22 13:33:49 +02:00
MrBlake 944652f66c feat: export editable draw.io rack and topology elements 2026-07-22 13:31:05 +02:00
MrBlake 36343c9e23 feat: add transparent rack and topology exports 2026-07-22 13:24:45 +02:00
MrBlake 77b1f46ea3 docs: rewrite README for MRB fork and rack topology features 2026-07-22 09:56:53 +02:00
MrBlake cbdf217f18 feat: add draggable topology with interactive cable tracing 2026-07-22 09:45:56 +02:00
MrBlake d8069edd73 feat: improve rack readability and add cable topology 2026-07-22 09:41:03 +02:00
MrBlake a967f88401 fix: avoid collision with NetBox Rack.units property 2026-07-22 09:35:55 +02:00
MrBlake fccc54e75e feat: add multi-rack elevation view and switch icons
- add rack elevation view for one or multiple racks
- render front and rear device positions by rack unit
- show physical cabling below selected racks
- add site, location, rack, and empty-rack filters
- add network, leaf, spine, and aggregation switch icons
- add “Weitere Ansichten” navigation category
2026-07-22 09:26:36 +02:00
Mario 8aea42c50b v4.5.1 (#721) 2026-03-29 10:51:01 +02:00
dependabot[bot] f56b8a4aec Bump picomatch from 2.3.1 to 2.3.2 in /netbox_topology_views/static_dev (#719)
Bumps [picomatch](https://github.com/micromatch/picomatch) from 2.3.1 to 2.3.2.
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

---
updated-dependencies:
- dependency-name: picomatch
  dependency-version: 2.3.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-29 09:56:55 +02:00
Mario 3aa2bab141 Add option to show cable labels (#720) 2026-03-29 09:52:10 +02:00
dependabot[bot] 6c4106e428 Bump immutable from 5.1.2 to 5.1.5 in /netbox_topology_views/static_dev (#710)
Bumps [immutable](https://github.com/immutable-js/immutable-js) from 5.1.2 to 5.1.5.
- [Release notes](https://github.com/immutable-js/immutable-js/releases)
- [Changelog](https://github.com/immutable-js/immutable-js/blob/main/CHANGELOG.md)
- [Commits](https://github.com/immutable-js/immutable-js/compare/v5.1.2...v5.1.5)

---
updated-dependencies:
- dependency-name: immutable
  dependency-version: 5.1.5
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-10 11:07:12 +01:00
Mario 3d97f649d9 Add Asset Tag to node label items (#712) 2026-03-10 10:13:04 +01:00
Mario d10ced8157 Fix preselected tags not recognized 2026-03-10 10:07:04 +01:00
Mario 9d4ef31bdd Closes #701: Option to always show cable/interface labels on edges (#707)
* Added draw termination labels
2026-03-10 09:34:45 +01:00
Mario e20f250425 Revert last Show Wireless change (#703) 2026-01-27 19:24:19 +01:00
Mario 89c56c8d1c v4.5.0 2026-01-07 11:08:58 +01:00
Go RayandMario 619e959a8e Fixes #683: Fix crash when rendering WirelessLink without label (#690)
* Fix crash when rendering WirelessLink without label

* removes the unnecessary str()

* Update views.py

---------

Co-authored-by: Mario <[email protected]>
2025-12-30 22:31:14 +01:00
Mario 10f545b509 Reorganize non-device filters (#694) 2025-12-30 17:20:14 +01:00
Mario 3810e9567f Fix error for zero results (#692) 2025-12-30 15:00:01 +01:00
Mario 5981a21830 bump version (#682) 2025-10-15 17:34:20 +02:00
Mario 8100b8146f Remove modal window (#680) 2025-10-09 14:59:35 +02:00
Mario 6c047b1022 Add cable label in hover popup (#679) 2025-10-08 18:51:29 +02:00
valtersg 4afa4f721f Fixes #671 (#677)
* Use CSRF token from window.CSRF_TOKEN

* Removed unused csrftoken.js
2025-10-08 15:26:31 +02:00
Mario e7df2f6772 Update README.md (#670)
Added NetBox v4.4.x to version matrix.
2025-09-25 12:43:32 +02:00
Mario b85e548049 added empty result warning (#658) 2025-07-18 23:09:26 +02:00
Mario 097fe5c685 added some label items (#656) 2025-07-17 15:07:37 +02:00
尤理衡 (Li-Heng Yu) c83479fb1d Added check for cable integrity (#647) 2025-07-14 08:49:32 +02:00
mattieserver 79a234fcc9 v4.3.0 (#642) 2025-05-28 16:19:42 +02:00
larsen0815 db76752a82 Clearly specify file locations (#638) 2025-05-15 11:47:29 +02:00
Mario 47f263f5c2 Update version table in README.md (#637) 2025-05-15 09:21:27 +02:00
larsen0815 6eb20004f9 Improve installation instructions (#635) 2025-05-15 09:16:37 +02:00
Mario 836d9f40d7 Fix group boxes too small for multiline labels (#632) 2025-05-11 11:43:11 +02:00
Mario 607347ff18 Fix unnecessary field User id (#631) 2025-05-09 17:55:50 +02:00
Chris Russell 0f6051731a Fixes #627 - update template_content to models tuple (#628) 2025-05-05 12:59:03 +02:00
Kenneth Hardy 3c9aebfd2f Update README.md (#625)
Bumping version. Works on my machine.
2025-04-30 08:02:01 +02:00
Maurice Kok 60a5fe1eae fix for issue 593 (#626) 2025-04-30 08:01:13 +02:00
mattieserver 3fbeb97810 bump version (#619) 2025-03-19 22:26:39 +01:00
Tobias Genannt f3b822e18d Use new version identifier from Netbox (#608) 2025-03-19 22:08:21 +01:00
dependabot[bot] 555c1fac4c Bump esbuild and esbuild-sass-plugin (#610)
Bumps [esbuild](https://github.com/evanw/esbuild) and [esbuild-sass-plugin](https://github.com/glromeo/esbuild-sass-plugin). These dependencies needed to be updated together.

Updates `esbuild` from 0.12.29 to 0.25.0
- [Release notes](https://github.com/evanw/esbuild/releases)
- [Changelog](https://github.com/evanw/esbuild/blob/main/CHANGELOG-2021.md)
- [Commits](https://github.com/evanw/esbuild/compare/v0.12.29...v0.25.0)

Updates `esbuild-sass-plugin` from 1.8.2 to 3.3.1
- [Release notes](https://github.com/glromeo/esbuild-sass-plugin/releases)
- [Commits](https://github.com/glromeo/esbuild-sass-plugin/commits/v3.3.1)

---
updated-dependencies:
- dependency-name: esbuild
  dependency-type: direct:development
- dependency-name: esbuild-sass-plugin
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-19 22:07:20 +01:00
mattieserver cf8641939a basic support for v4.2 (#592)
* basic support for v4.2

* bump versions

* update readme with versions

* upgrade version for v4.1.X
2025-01-10 15:41:44 +01:00
Mario 2893fff111 Closes #484: Show device information (#573)
* Add model and individual option

* Add forms and views

* minor changes
2024-11-22 21:27:25 +01:00
Mario 25fdcb6cf4 fix saved filter not honoring show_unconnected (#582) 2024-10-18 14:58:33 +02:00
Chris Russell 5d330bc830 Update plugin yaml for topology views v4.0.1 and netbox v4.1.4 (#581) 2024-10-17 17:11:23 +01:00
Nat Morris 03b8c9c76e ENG-3602 initial plugin manifest (#578)
* chore: trigger a central workflow when the manifest is modified.
* chore: import compatibility from the existing registry details
2024-10-14 18:07:58 +01:00
Mario 02a7118a33 Fixes #547: XML Export does not work in modal window (#572)
* Fix XML export in modal windows

* Removed useless concatenation

* Revert removed basePath in JS and added basePath to HTMX template
2024-09-27 21:44:06 +02:00
Mario 44e49495fe Add API functions for coordinates and coordinate groups (#571) 2024-09-27 20:46:58 +02:00
mattieserver f4b1e34826 fix name of devices (#567)
* fix name of devices

* upgrade version
2024-09-11 17:00:15 +02:00
mattieserver f8c6e9e193 bump version (#558) 2024-08-26 12:21:00 +02:00
mattieserver 19adcab4a9 set BaseViewSet (#556) 2024-08-26 12:01:42 +02:00
Mario d2d2106246 Closes #163: Show raster and snap icons (#550)
* proof of concept

* add grid size to forms and individual options
2024-08-20 12:02:45 +02:00
Mario 9072faf7cf Closes #485: Add Ignore Termination Types to "regular" filters (#546)
* add ignore_cable_type filter

* deleted commented command

* corrected saved filter for ignore_cable_type
2024-08-09 15:09:16 +02:00
Mario 6f43b959bd Closes #497: Group by Virtual Chassis (#542)
* add virtual chassis to js

* add virtual chassis to py and migrations
2024-07-29 12:15:04 +02:00
Mario 1048feff52 Fixes #464: Topology not showing properly when using other language than english (#541)
* Change termination type name to model

* change CHOICES to model names

* Change termination type name to model

* change CHOICES to model names
2024-07-29 10:32:30 +02:00
Mario 7ff0a9650f Fixed another mistake (#540) 2024-07-28 00:07:00 +02:00
Mario 8d5de5c49f fix saved filter params not defined (#539) 2024-07-27 22:26:18 +02:00
Mario 96afdf8d83 fix coordinate group in saved filter (#536) 2024-07-24 22:22:13 +02:00
aba0598947 Closes #436 (and #122?): Add options to disable smooth cables and physics (#488)
* allow disabling smooth cables and render them as straight lines instead

* rename 'disable_smooth_cables' to 'straight_cables'

* missed one in renaming

* fix inverted logic

* add GET param and option to DeviceFilterForm

* fix syntax error

* rename var

* add missing query field

* netbox v4 support

---------

Co-authored-by: Daniel Bremer <[email protected]>
Co-authored-by: mvanhaverbeke <[email protected]>
2024-07-08 15:37:18 +02:00
mattieserver 142de460b9 added restrict to query (#522) 2024-07-04 21:01:40 +02:00
mattieserver 2600209724 4.0 release (#513) 2024-06-24 20:10:05 +02:00
mattieserver ed8a717bc5 seconnd beta (#511) 2024-06-21 19:21:20 +02:00
mattieserver 0b7046b10d fix route name (#508) 2024-06-17 21:43:03 +02:00
mattieserver e784e717ca fix coordSaveCheckbox (#510) 2024-06-17 21:42:47 +02:00
2895294903 477 prepare for netbox 4.0 (#495)
* Change extras.plugins to netbox.plugins (#487)

* Remove ButtonColorChoices (#491)

* remove is_htmx

* fieldset update

* Additions to 477 prepare for netbox 4.0 (#504)

* Re-add overriding of default_renderer

Signed-off-by: Iain Buclaw <[email protected]>

* Restore i18n of field names

Signed-off-by: Iain Buclaw <[email protected]>

* Remove unnecessary FieldSets

Signed-off-by: Iain Buclaw <[email protected]>

* Remove trailing whitespaces in forms.py

Signed-off-by: Iain Buclaw <[email protected]>

* Fix error in resizeCanvas

Signed-off-by: Iain Buclaw <[email protected]>

* Remove btn-sm class from buttons

Signed-off-by: Iain Buclaw <[email protected]>

* Use htmx_partial instead of request.htmx

Signed-off-by: Iain Buclaw <[email protected]>

---------

Signed-off-by: Iain Buclaw <[email protected]>

* fix choises

* fix color switcher (use new attribute)

* fix htmx filter

* 4.0.0-beta.1 release

---------

Signed-off-by: Iain Buclaw <[email protected]>
Co-authored-by: Mario <[email protected]>
Co-authored-by: Iain Buclaw <[email protected]>
2024-06-05 13:23:34 +02:00
mattieserver 8368ffa2fd prepare 3.9.1 (#480) 2024-04-19 15:55:04 +02:00
Mario 23428c8ad2 set models to private (#476) 2024-04-01 23:26:46 +02:00
Mario c00b8c2cfe Fixes #236: Saved filter doesn't reload show cables (#475)
* fix restore saved filter options

* fix restore saved filter group options

* fix htmx export to xml
2024-03-30 17:29:26 +01:00
Mario 32003e59f9 fix power feeds attributeerror (#474) 2024-03-30 11:17:04 +01:00
Mario bd32642b5c refine group frame color (#472) 2024-03-30 10:13:29 +01:00
Mario f463804087 added group options to api (#466) 2024-03-08 16:19:55 +01:00
Mario b92b012309 Closes #329: Draw rectangles around Sites/Locations/Racks (#462) 2024-03-03 17:52:44 +01:00
mattieserver 74c295837c bump version (#449) 2024-01-13 21:59:37 +01:00
Mario a543f5cb0c fix pixel waste (#440) 2024-01-04 21:42:19 +01:00
mattieserver 50c90a4328 438 beta release for netbox v370 (#439)
* 3.9.0

* 3.9-beta1
2024-01-02 12:22:46 +01:00
mattieserver 374a88266a used EventRulesMixin (#437) 2024-01-02 11:42:47 +01:00
mattieserver 60cbc94a62 remove imp (#426) 2024-01-02 11:27:46 +01:00
Mario 649305c83e Fixes #416: Images View permissions incorrect (#418)
* Add resize listener and height calculation

* Fixed typos
2023-10-29 14:58:17 +01:00
Mario b3397f4f4a Fixes #417: README is missing some permissions (#419)
* Add resize listener and height calculation

* Fixed typos

* add permissions for new views
2023-10-29 14:56:42 +01:00
Mario a23604261a Update README.md (#415)
Version matrix wasn't in sync with the latest release.
2023-10-29 14:56:19 +01:00
mattieserver d9571b30b5 bump version (#410) 2023-10-23 19:17:22 +02:00
kkthxbye 76b43f5d1e Overwrite the form renderer of DeviceFilterForm to fix regression caused by netbox 3.6.4 (#408) 2023-10-20 06:38:33 +02:00
mattieserver becfaaa054 bump version (#397) 2023-10-13 13:08:18 +02:00
Mario bec301eb9d fix provider network error (#394) 2023-09-28 15:50:04 +02:00
Mario f28623b378 fix image save for old Python versions (#390) 2023-09-28 15:49:05 +02:00
Mario 16837047be fix device filter (#393) 2023-09-28 15:06:04 +02:00
Mario 987c7ef34c Fixes #377: Non-devices do not save coordinates (#387)
* corrected nodeId handling

* add models

* import models, migrate db

* correct migration deps

* load coordinates from db

* add serializers, correct imports

* add views and templates

* fix X-Y swap in help text

* add non-devices to coordinate group view
2023-09-27 09:13:17 +02:00
Mario dbe331afb8 add filters / housekeeping (#384) 2023-09-25 17:28:32 +02:00
Mario 86c0c55896 Closes #381: Filter by site group (#382)
* add Site Group filter

* revise query_params
2023-09-21 16:15:45 +02:00
76 changed files with 6589 additions and 1200 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
name: NetBox plugin manifest modified
on:
push:
branches: [ develop ]
paths:
- netbox-plugin.yaml
concurrency:
group: ${{ github.workflow }}
cancel-in-progress: false
jobs:
manifest-modified:
uses: netboxlabs/public-workflows/.github/workflows/reusable-plugin-manifest-modified.yml@release
+2 -1
View File
@@ -1,4 +1,5 @@
recursive-include netbox_topology_views/static *
recursive-include netbox_topology_views/templates *
recursive-include netbox_topology_views/api *
prune netbox_topology_views/api/__pycache__
prune netbox_topology_views/api/__pycache__
recursive-include netbox_topology_views/locale *.po *.mo
+192 -154
View File
@@ -1,202 +1,240 @@
# Netbox Topology Views Plugin
# MRB NetBox Topology Views
![Version](https://img.shields.io/pypi/v/netbox-topology-views) ![Downloads](https://img.shields.io/pypi/dm/netbox-topology-views)
A customised fork of **NetBox Topology Views** with extended rack views,
interactive cable tracing and additional network icons.
Create topology views/maps from your devices in NetBox.
The connections are based on the cables you created in NetBox.
Support to filter on name, site, tag and device role.
Options to export to xml (for draw.io/diagrams.net) or png.
The plugin builds topologies from the devices, ports and cables maintained in
NetBox. In addition to the classic topology, this fork provides a complete view
of one or more racks including front, rear and cabling.
## Preview
| | |
|---|---|
| **Plugin name** | `netbox_topology_views` |
| **Package** | `netbox-topology-views` |
| **NetBox** | `4.7.x` |
| **Python** | see `setup.py` |
| **Repository** | <https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views> |
![Topology with light mode](doc/img/topology_light.png)
![Topology with dark mode](doc/img/topology_dark.png)
## Screenshots
## Install
Cable topology of a site, arranged with a coordinate group:
**_NOTE:_** For docker please see: [Docker install](https://github.com/netbox-community/netbox-docker/wiki/Using-Netbox-Plugins)
![Topology view](docs/screenshots/topology.png)
**_NOTE:_** Add `RUN mkdir -p /opt/netbox/netbox/static/netbox_topology_views/img` to the Dockerfile-Plugins file to create the image folder
Rack view with front and rear elevations:
The plugin is available as a Python package and can be installed with pip.
![Rack view](docs/screenshots/rack-view.png)
Run `pip install netbox-topology-views` in your virtual env.
## Features
To ensure NetBox Topology Views plugin is automatically re-installed during future upgrades, create a file named `local_requirements.txt` (if not already existing) in the NetBox root directory (alongside `requirements.txt`) and list the `netbox-topology-views` package:
- Show one or more racks together
- Render devices at their exact rack unit position
- View front and rear of a rack separately
- Ascending/descending U numbering and custom starting unit are respected automatically
- Detect cross-rack and external cable connections
- Freely move devices in the cable topology
- Sort devices in the cable topology by rack position within each rack
- Browser full-screen mode for the cable topology
- Zoom the cable topology between 50 and 200 % and scroll in full-screen
- Render P2P wireless links and multi-access WLANs as purple dashed radio links
- Optionally show/hide wireless links and power cables in the rack view's cable topology, visually distinct from network cables (purple dashed / orange dotted)
- Store manual positions per rack selection in the browser
- Highlight a device's connections in white on hover
- Show all connected ports and peers of a device
- Show a cable's terminations on hover
- Open devices and cables in NetBox directly from the topology
- Export single racks, all racks or the cable topology as SVG, PNG and draw.io — always with transparent background
- Colours of rack view and export follow the active light or dark mode
- Additional icons for network, leaf, spine and aggregation switches
```no-highlight
# echo netbox-topology-views >> local_requirements.txt
### Changes compared to the original
1. New menu category **More views**.
2. A rack view with filters for site, location and multiple racks.
3. Position-accurate rack elevations for front and rear.
4. A cable table with A and B terminations.
5. An interactive, movable cable topology below the racks.
6. Hover highlighting and port-to-port tracing for devices and cables.
7. Locally stored device positions and a reset function.
8. An extended, scalable SVG icon set for switch roles.
9. Transparent SVG, PNG and draw.io exports for rack and topology views.
10. Adjustments for NetBox 4.6+, including the changed `Rack.units` property.
![Topology in light mode](doc/img/topology_light.png)
![Topology in dark mode](doc/img/topology_dark.png)
## Compatibility
- NetBox `4.7.x` (`min_version`/`max_version` in `netbox_topology_views/__init__.py`)
- Based on NetBox Topology Views `4.5.1`
Since the upstream release officially targets NetBox 4.5.x, test updates to
newer NetBox versions in a staging instance first.
## Installation
All paths assume a standard installation under `/opt/netbox`.
### 1. Install the package
```bash
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \
"git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop"
```
Once installed, the plugin needs to be enabled in your `configuration.py`
For reproducible production installs, replace `develop` with a release tag or a
full commit ID.
### 2. Add the plugin to `local_requirements.txt`
This makes `upgrade.sh` reinstall the plugin automatically on every NetBox upgrade:
```bash
grep -qxF "git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop" /opt/netbox/local_requirements.txt \
|| echo "git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop" | sudo tee -a /opt/netbox/local_requirements.txt
```
If the repository is private, the NetBox server needs a read-only deploy token
or an SSH key. Do not store credentials in `local_requirements.txt`.
### 3. Enable the plugin
In `/opt/netbox/netbox/netbox/configuration.py`:
```python
# In your configuration.py
PLUGINS = ["netbox_topology_views"]
```
PLUGINS = [
"netbox_topology_views",
]
First run `source /opt/netbox/venv/bin/activate` to enter the Python virtual environment.
Then run
```bash
cd /opt/netbox/netbox
pip3 install netbox-topology-views
python3 manage.py migrate netbox_topology_views
python3 manage.py collectstatic --no-input
```
### Versions
| netbox version | netbox-topology-views version |
| -------------- | ----------------------------- |
| >= 3.6.0 | >= v3.7.X |
| >= 3.5.0 | >= v3.4.X |
| >= 3.4.0 | >= v3.X.X |
| >= 3.3.0 | >= v3.0.0 |
| >= 3.2.0 | >= v1.1.0 |
| >= 3.1.8 | >= v1.0.0 |
| >= 2.11.1 | >= v0.5.3 |
| >= 2.10.0 | >= v0.5.0 |
| < 2.10.0 | =< v0.4.10 |
### Update
Run `pip install netbox-topology-views --upgrade` in your venv.
Run `python3 manage.py migrate netbox_topology_views`
Run `python3 manage.py collectstatic --no-input`
Clear you browser cache.
## Configure
### Individual Options
All individual options can be assigned a default value per user directly in the plugin. The default value can be overridden on the filter page.
![Individual Options](doc/img/topology_individual_options.png)
The remaining options must be configured in the `PLUGINS_CONFIG` section of your `netbox/configuration.py`.
Example:
```
PLUGINS_CONFIG = {
'netbox_topology_views': {
'static_image_directory': 'netbox_topology_views/img',
'allow_coordinates_saving': True,
'always_save_coordinates': True
}
"netbox_topology_views": {
"static_image_directory": "netbox_topology_views/img",
"allow_coordinates_saving": True,
"always_save_coordinates": False,
},
}
```
| Setting | Default value | Description |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| static_image_directory | netbox_topology_views/img | (str or pathlib.Path) Specifies the location that images will be loaded from by default. Must be within `STATIC_ROOT` |
| allow_coordinates_saving | False | (bool) Set to true if you want to enable the ability to save the coordinates. |
| always_save_coordinates | False | (bool) Set if you want to enable the option to save coordinates by default. Setting allow_coordinates_saving to true is mandatory. |
If other plugins are already configured, add `netbox_topology_views` to the
existing list and dictionary instead of replacing them.
### Custom field: coordinates
### 4. Apply migrations, collect static files, restart
There is also support for custom fields.
```bash
cd /opt/netbox/netbox
/opt/netbox/venv/bin/python manage.py migrate netbox_topology_views
/opt/netbox/venv/bin/python manage.py collectstatic --no-input
sudo systemctl restart netbox netbox-rq
```
>**_Note:_** The custom field "coordinates" is deprecated and will be removed in the future. Please use Coordinate Groups instead.
After changes to CSS or icons a hard reload in the browser (`Ctrl+F5`) may be
necessary.
If you create a custom field "coordinates" for "dcim > device" and "Circuits > circuit" with type "text" and name "coordinates" you will see the same layout every time. It is recommended to set this field to "UI visibility" "Hidden" and let the plugin manage it in the background.
## Update
The coordinates are stored as: "X;Y".
```bash
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \
"git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop"
> Please read the "Configure" chapter to set the `allow_coordinates_saving` option to True.
You might also set the `always_save_coordinates` option to True.
cd /opt/netbox/netbox
/opt/netbox/venv/bin/python manage.py migrate netbox_topology_views
/opt/netbox/venv/bin/python manage.py collectstatic --no-input
sudo systemctl restart netbox netbox-rq
```
### Convert custom field to Coordinate Groups
`--force-reinstall` is required because the fork still uses the internal
package version `4.5.2`.
Please note that values stored in the custom field "coordinates" are not being converted to Coordinate Groups automatically. A pragmatic way to do this conversion yourself is as follows:
+ Navigate to "Topology" > "Filters".
+ Select "Show Unconnected" and "Show Cables".
+ Leave all other filter settings alone. We want all entries to be displayed!
+ Click "Search" and wait for the results to be displayed
+ Select all nodes. This can be done by holding down the Shift key and dragging a frame around all icons with the left mouse button.
+ Drag the selection a tiny bit to the side. This causes all coordinates for all devices to be stored in the "default" group.
> **_Hint_**: Don't wait too long after clicking an icon in order to drag. If you hold the mouse button for too long before dragging starts, the selection is reset._
+ Storing the values might take some time, depending on the number of devices. Please be patient and check "Coordinates" in order to make sure that everthing has been stored.
+ It is save to delete the custom field now.
When NetBox itself is upgraded, `upgrade.sh` reinstalls the plugin from
`local_requirements.txt` and runs migrations and `collectstatic`:
### Custom Images
```bash
sudo /opt/netbox/upgrade.sh
sudo systemctl restart netbox netbox-rq
```
To change image with associated device use the `Images` page - it allows to map a device role with an image found in the NetBox static directory (defined by the plugin config `static_image_directory` which defaults to `netbox_topology_views/img`). You can also upload you own custom images to there - these images will automatically be used for a device (if it does not already have a specified image in the settings) if their name is the device role slug.
## Uninstall
![Images](doc/img/topology_images.png)
1. Remove `"netbox_topology_views"` from `PLUGINS` and `PLUGINS_CONFIG`.
2. Remove the line from `/opt/netbox/local_requirements.txt`.
3. Uninstall the package and restart NetBox:
## Use
```bash
/opt/netbox/venv/bin/pip uninstall netbox-topology-views
sudo systemctl restart netbox netbox-rq
```
Go to the plugins tab in the navbar and click topology or go to `$NETBOX_URL/plugins/netbox_topology_views/` to view your topologies
## Usage
Select your options for the topology view:
### Classic topology
![Filter Options](doc/img/topology_filter_options.png)
**Plugins → Topology Views → Topology** provides the original, filterable
topology view. It supports physical cables, logical connections, neighbour
devices, circuit terminations, power feeds, wireless links, coordinate groups,
and PNG and XML export.
<dl>
<dt>Coordinate Group</dt>
<dd>Select Coordinate Group. These groups allow devices to be displayed in different positions depending on the group, thus providing different representations for the same topology. If nothing is selected, the group "default" is set automatically.</dd>
<dt>Save Coordinates</dt>
<dd>Save the coordinates of devices in the topology view.</dd>
<dt>Show Unconnected</dt>
<dd>Show devices that have no connections or for which no connection is displayed. This option depends on other parameters like 'Show Cables' and 'Show Logical Connections'.</dd>
<dt>Show Cables</dt>
<dd>Show connections between interfaces, front / rear ports, etc., that are connected with one or more cables. These connections are displayed as solid lines in the color of the cable.</dd>
<dt>Show Logical Connections</dt>
<dd>Show logical connections between interfaces (referred to as Interface Connections in NetBox) in the topology view. Where the path between
interfaces includes multiple cables (e.g., via patch panels), only the end interface connections are shown, not the
intermediate front / rear port connections, etc. This is similar to what was referred to as 'end-to-end' connections in previous versions. These connections are displayed as yellow dotted lines.</dd>
<dt>Show redundant Cable and Logical Connection</dt>
<dd>Shows a logical connection (in addition to a cable), even if a cable is directly connected. Leaving this option disabled prevents that redundant display. This option only has an effect if 'Show Logical Connections' is activated.</dd>
<dt>Show Neighbors</dt>
<dd>Adds neighbors to the filter result set automatically. Link peers will be added if 'Show Cables' is ticked, far-end terminations will be added if 'Show Logical Connections' is ticked.</dd>
<dt>Show Circuit Terminations</dt>
<dd>Show connections which end at a circuit termination in the topology view. These connections are displayed as blue dashed lines.</dd>
<dt>Show Power Feeds</dt>
<dd>Displays connections between power outlets and power ports. These connections are displayed as solid lines in the color of the cable. This option depends on 'Show Cables'.</dd>
<dt>Show Wireless Links</dt>
<dd>Displays wireless connections. These connections are displayed as blue dotted lines.</dd>
</dl>
### Coordinates and Coordinate Groups
### Rack view
Netbox Topology Views stores the position of the devices. In order to allow different representations for the topology, Coordinate Groups are supported.
**Plugins → Topology Views → More views → Rack view**
> Please read the "Configure" chapter to set the `allow_coordinates_saving` option to True.
You might also set the `always_save_coordinates` option to True.
Select a single rack or several racks via site, location and rack; empty racks
can be shown optionally. Devices are rendered according to position, height and
rack face. Below the elevations follow:
Navigate to "Coordinate Groups" in the menu and create as many groups as you like. You can select a group later in the filter pane in order to show icon positions according to this group (see chapter "Use"). You can also omit creating a group if you don't need this feature. Netbox Topology Views automatically creates a group named "default" for you and stores all coordinates in this group, even if you do not select a group in the filter.
1. the interactive cable topology, and
2. a table of all involved cables.
By default, the position of the devices are calculated with a physics engine. As soon as a device icon is dragged to another location, its position is saved and excluded from the calculation by the physics engine. All saved coordinates can be viewed and edited under the menu item "Coordinates".
In the cable topology, devices can be moved via drag and drop. Hovering a device
highlights its cables and lists all connected ports; hovering a cable shows both
terminations. A click opens the NetBox object.
> **_Note:_** At the time of writing, it is not possible to store the positions of circuit terminations, power panels and power feeds, as these are not devices.
The export buttons save a single rack, all displayed racks or the cable topology
as SVG, PNG or draw.io, always without background. In the draw.io export, rack
frames, devices and labels remain individually editable, and topology cables are
real edges that follow the devices.
### Permissions
Positions are stored in the browser's `localStorage` and apply only to that
browser and the specific rack/filter selection.
To view `/plugins/netbox_topology-views/topology` you need the following permissions:
+ dcim | device | can view device
+ dcim | site | can view site
+ extras | tag | can view tag
+ dcim | device role | can view device role
With [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities)
installed, partial-width devices are rendered side by side in the rack view.
To save `Coordinates` when moving icons:
+ netbox_topology_views | coordinate | change
## Device icons
To view `/plugins/netbox_topology-views/images`:
+ dcim | site | view
+ dcim | device role | view
+ dcim | device role | add
+ dcim | device role | change
Icons are assigned by device role slug. This fork additionally ships:
To view `/plugins/netbox_topology-views/individualoptions`:
+ netbox_topology_views | individual options | change
| Device role slug | Icon file |
| --- | --- |
| `network-switch` | `network-switch.svg` |
| `leaf-switch` | `leaf-switch.svg` |
| `spine-switch` | `spine-switch.svg` |
| `aggregation-switch` | `aggregation-switch.svg` |
Set `Coordinate Groups` according to your needs:
+ netbox_topology_views | coordinate groups | view/add/change/delete
Custom images can still be assigned on the **Images** page. The default path is
`netbox_topology_views/img` within `STATIC_ROOT`.
Set `Coordinates` according to your needs:
+ netbox_topology_views | coordinate | view/add/change/delete
## Permissions
Classic topology: `dcim.view_site`, `dcim.view_device`.
Rack view: `dcim.view_rack`, `dcim.view_device`, `dcim.view_cable`.
Saving classic topology coordinates additionally requires the corresponding
permissions on `netbox_topology_views.coordinate`.
## Origin and credits
This project is a fork of the open-source plugin
[NetBox Topology Views](https://github.com/mattieserver/netbox-topology-views).
The original plugin was created by **Mattijs Vanhaverbeke**. Most of the classic
topology view, data models, filters and export functions are based on his work
and the contributions to the original project.
This fork is developed independently and is not officially affiliated with the
original author or the NetBox project.
## License
Like the original, this project is licensed under the
[Apache License 2.0](LICENSE). Existing copyright, license and attribution
notices of the original project are retained.
+3 -3
View File
@@ -1,7 +1,7 @@
version: '3.4'
services:
postgres:
image: postgres:12-alpine
image: postgres:16-alpine
environment:
POSTGRES_PASSWORD: J5brHrAXFLQSif0K #just for local dev
POSTGRES_DB: netbox
@@ -9,7 +9,7 @@ services:
ports:
- "5432:5432"
volumes:
- netbox-postgres-data:/var/lib/postgresql/data
- netbox-postgres-data-16:/var/lib/postgresql/data
redis:
image: redis:6-alpine
@@ -35,7 +35,7 @@ services:
- "6378:6379"
volumes:
netbox-postgres-data:
netbox-postgres-data-16:
driver: local
netbox-redis-data:
driver: local
Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

+36
View File
@@ -0,0 +1,36 @@
version: 0.1
package_name: netbox-topology-views
compatibility:
- release: 4.5.0
netbox_min: 4.5.0
netbox_max: 4.5.5
- release: 4.4.0
netbox_min: 4.4.0
netbox_max: 4.4.3
- release: 4.3.0
netbox_min: 4.3.0
netbox_max: 4.3.7
- release: 4.2.0
netbox_min: 4.2.0
netbox_max: 4.2.1
- release: 4.1.0
netbox_min: 4.1.0
netbox_max: 4.1.11
- release: 4.0.1
netbox_min: 4.0.9
netbox_max: 4.0.11
- release: 4.0.0
netbox_min: 4.0.0
netbox_max: 4.0.9
- release: 3.9.1
netbox_min: 3.7.1
netbox_max: 3.7.8
- release: 3.9.0
netbox_min: 3.7.1
netbox_max: 3.7.8
- release: 3.8.1
netbox_min: 3.6.9
netbox_max: 3.6.9
- release: 3.6.2
netbox_min: 3.5.1
netbox_max: 3.5.9
+8 -5
View File
@@ -1,14 +1,17 @@
from extras.plugins import PluginConfig
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginConfig
class TopologyViewsConfig(PluginConfig):
name = "netbox_topology_views"
verbose_name = "Topology views"
description = "An plugin to render topology maps"
version = "3.7.0"
author = "Mattijs Vanhaverbeke"
verbose_name = _("Topology views")
description = _("A plugin to render topology maps")
version = "4.5.2"
author = "Mattijs Vanhaverbeke, Codex & Claude"
author_email = "[email protected]"
base_url = "netbox_topology_views"
min_version = "4.7.0"
max_version = "4.7.99"
required_settings = []
default_settings = {
"static_image_directory": "netbox_topology_views/img",
+20 -2
View File
@@ -2,7 +2,7 @@ from dcim.models import Device, DeviceRole
from rest_framework.serializers import ModelSerializer
from netbox.api.serializers import NetBoxModelSerializer
from netbox_topology_views.models import RoleImage, IndividualOptions, CoordinateGroup, Coordinate
from netbox_topology_views.models import RoleImage, IndividualOptions, CoordinateGroup, Coordinate, CircuitCoordinate, PowerPanelCoordinate, PowerFeedCoordinate
class TopologyDummySerializer(ModelSerializer):
@@ -32,7 +32,25 @@ class CoordinateSerializer(NetBoxModelSerializer):
model = Coordinate
fields = ("x", "y")
class CircuitCoordinateSerializer(NetBoxModelSerializer):
class Meta:
model = CircuitCoordinate
fields = ("x", "y")
class PowerPanelCoordinateSerializer(NetBoxModelSerializer):
class Meta:
model = PowerPanelCoordinate
fields = ("x", "y")
class PowerFeedCoordinateSerializer(NetBoxModelSerializer):
class Meta:
model = PowerFeedCoordinate
fields = ("x", "y")
class IndividualOptionsSerializer(NetBoxModelSerializer):
class Meta:
model = IndividualOptions
fields = ("ignore_cable_type", "save_coords", "show_unconnected", "show_cables", "show_logical_connections", "show_single_cable_logical_conns", "show_neighbors", "show_circuit", "show_power", "show_wireless", "draw_default_layout")
fields = ("ignore_cable_type", "save_coords", "show_unconnected", "show_cables", "show_logical_connections",
"show_single_cable_logical_conns", "show_neighbors", "show_circuit", "show_power", "show_wireless", "group_sites",
"group_locations", "group_racks", "group_virtualchassis", "draw_default_layout", "straight_cables",
"draw_termination_labels", "draw_cable_labels", "grid_size", "node_label_items")
+6 -1
View File
@@ -6,6 +6,11 @@ router = NetBoxRouter()
router.register("save-coords", views.SaveCoordsViewSet)
router.register("images", views.SaveRoleImageViewSet)
router.register("xml-export", views.ExportTopoToXML)
router.register("xml-export", views.ExportTopoToXML, "xml-export")
router.register("coordinate-groups", views.CoordinateGroupViewSet)
router.register("coordinate", views.CoordinateViewSet)
router.register("circuitcoordinate", views.CircuitCoordinateViewSet)
router.register("powerpanelcoordinate", views.PowerPanelCoordinateViewSet)
router.register("powerfeedcoordinate", views.PowerFeedCoordinateViewSet)
urlpatterns = router.urls
+114 -25
View File
@@ -1,7 +1,11 @@
from typing import Dict
import sys
from netbox.api.viewsets import BaseViewSet, NetBoxModelViewSet
from circuits.models import Circuit
from dcim.models import Device, DeviceRole, PowerFeed, PowerPanel
from extras.models import SavedFilter
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.contenttypes.models import ContentType
@@ -13,13 +17,19 @@ from rest_framework.viewsets import ReadOnlyModelViewSet, ViewSet
from netbox_topology_views.api.serializers import (
RoleImageSerializer,
TopologyDummySerializer,
CoordinateGroupSerializer,
CoordinateSerializer,
CircuitCoordinateSerializer,
PowerPanelCoordinateSerializer,
PowerFeedCoordinateSerializer,
)
from netbox_topology_views.models import RoleImage, IndividualOptions, CoordinateGroup, Coordinate
import netbox_topology_views.models
from netbox_topology_views.models import RoleImage, IndividualOptions, CoordinateGroup, Coordinate, CircuitCoordinate, PowerPanelCoordinate, PowerFeedCoordinate
from netbox_topology_views.views import get_topology_data
from netbox_topology_views.utils import get_image_from_url, export_data_to_xml, get_query_settings
from netbox_topology_views.filters import DeviceFilterSet
class SaveCoordsViewSet(PermissionRequiredMixin, ReadOnlyModelViewSet):
class SaveCoordsViewSet(BaseViewSet, ReadOnlyModelViewSet):
permission_required = 'netbox_topology_views.change_coordinate'
queryset = Device.objects.none()
@@ -41,20 +51,26 @@ class SaveCoordsViewSet(PermissionRequiredMixin, ReadOnlyModelViewSet):
if device_id.startswith("c"):
device_id = device_id.lstrip("c")
actual_device = Circuit.objects.get(id=device_id)
model_name = 'CircuitCoordinate'
elif device_id.startswith("p"):
device_id = device_id.lstrip("p")
actual_device = PowerPanel.objects.get(id=device_id)
model_name = 'PowerPanelCoordinate'
elif device_id.startswith("f"):
device_id = device_id.lstrip("f")
actual_device = PowerFeed.objects.get(id=device_id)
model_name = 'PowerFeedCoordinate'
elif device_id.isnumeric():
actual_device = Device.objects.get(id=device_id)
model_name = 'Coordinate'
if not actual_device:
return Response({"status": "invalid node_id in body"}, status=400)
model_class = getattr(netbox_topology_views.models, model_name)
if group_id is None or group_id == "default":
group_id = Coordinate.get_or_create_default_group(group_id)
group_id = model_class.get_or_create_default_group(group_id)
if not group_id:
return Response(
{"status": "Error while creating default group."}, status=500
@@ -66,12 +82,12 @@ class SaveCoordsViewSet(PermissionRequiredMixin, ReadOnlyModelViewSet):
# Hen-and-egg-problem. Thanks, Django! By default, Django updates records that
# already exist and inserts otherwise. This does not work with our
# unique_together key if no pk is given. But: No record, no pk.
if not Coordinate.objects.filter(group=group, device=actual_device):
if not model_class.objects.filter(group=group, device=actual_device):
# Unique group/device pair does not exist. Prepare new data set
coords = Coordinate(group=group, device=actual_device, x=x_coord, y=y_coord)
coords = model_class(group=group, device=actual_device, x=x_coord, y=y_coord)
else:
# Unique group/device pair already exists. Update data
coords = Coordinate(pk=Coordinate.objects.get(group=group, device=actual_device).pk, group=group, device=actual_device, x=x_coord, y=y_coord)
coords = model_class(pk=model_class.objects.get(group=group, device=actual_device).pk, group=group, device=actual_device, x=x_coord, y=y_coord)
coords.save()
except:
return Response(
@@ -80,16 +96,14 @@ class SaveCoordsViewSet(PermissionRequiredMixin, ReadOnlyModelViewSet):
return Response({"status": "saved coords"})
class ExportTopoToXML(PermissionRequiredMixin, ViewSet):
permission_required = ("dcim.view_site", "dcim.view_device")
class ExportTopoToXML(BaseViewSet, ViewSet):
queryset = Device.objects.none()
serializer_class = TopologyDummySerializer
def list(self, request):
self.filterset = DeviceFilterSet
self.queryset = Device.objects.all().select_related(
self.queryset = Device.objects.restrict(request.user, 'view').select_related(
"device_type", "role"
)
self.queryset = self.filterset(request.GET, self.queryset).qs
@@ -100,14 +114,49 @@ class ExportTopoToXML(PermissionRequiredMixin, ViewSet):
if request.GET:
save_coords, show_unconnected, show_power, show_circuit, show_logical_connections, show_single_cable_logical_conns, show_cables, show_wireless, show_neighbors = get_query_settings(request)
filter_id, ignore_cable_type, save_coords, show_unconnected, show_power, show_circuit, show_logical_connections, show_single_cable_logical_conns, show_cables, show_wireless, group_sites, group_locations, group_racks, group_virtualchassis, group, show_neighbors, straight_cables, draw_termination_labels, draw_cable_labels, grid_size, node_label_items = get_query_settings(request)
# Read options from saved filters as NetBox does not handle custom plugin filters
if "filter_id" in request.GET and request.GET["filter_id"] != '':
try:
saved_filter = SavedFilter.objects.get(pk=filter_id)
saved_filter_params = getattr(saved_filter, 'parameters')
if ignore_cable_type == () and 'ignore_cable_type' in saved_filter_params: ignore_cable_type = saved_filter_params['ignore_cable_type']
if save_coords == False and 'save_coords' in saved_filter_params: save_coords = saved_filter_params['save_coords']
if show_unconnected == False and 'show_unconnected' in saved_filter_params: show_unconnected = saved_filter_params['show_unconnected']
if show_power == False and 'show_power' in saved_filter_params: show_power = saved_filter_params['show_power']
if show_circuit == False and 'show_circuit' in saved_filter_params: show_circuit = saved_filter_params['show_circuit']
if show_logical_connections == False and 'show_logical_connections' in saved_filter_params: show_logical_connections = saved_filter_params['show_logical_connections']
if show_single_cable_logical_conns == False and 'show_single_cable_logical_conns' in saved_filter_params: show_single_cable_logical_conns = saved_filter_params['show_single_cable_logical_conns']
if show_cables == False and 'show_cables' in saved_filter_params: show_cables = saved_filter_params['show_cables']
if show_wireless == False and 'show_wireless' in saved_filter_params: show_wireless = saved_filter_params['show_wireless']
if group_sites == False and 'group_sites' in saved_filter_params: group_sites = saved_filter_params['group_sites']
if group_locations == False and 'group_locations' in saved_filter_params: group_locations = saved_filter_params['group_locations']
if group_racks == False and 'group_racks' in saved_filter_params: group_racks = saved_filter_params['group_racks']
if group_virtualchassis == False and 'group_virtualchassis' in saved_filter_params: group_virtualchassis = saved_filter_params['group_virtualchassis']
if show_neighbors == False and 'show_neighbors' in saved_filter_params: show_neighbors = saved_filter_params['show_neighbors']
if straight_cables == False and 'straight_cables' in saved_filter_params: straight_cables = saved_filter_params['straight_cables']
if draw_termination_labels == False and 'draw_termination_labels' in saved_filter_params: draw_termination_labels = saved_filter_params['draw_termination_labels']
if draw_cable_labels == False and 'draw_cable_labels' in saved_filter_params: draw_cable_labels = saved_filter_params['draw_cable_labels']
if grid_size == 0 and 'grid_size' in saved_filter_params: grid_size = saved_filter_params['grid_size']
if node_label_items == () and 'node_label_items' in saved_filter_params: node_label_items = saved_filter_params['node_label_items']
except SavedFilter.DoesNotExist: # filter_id not found
pass
except Exception as inst:
print(type(inst))
if 'group' not in request.query_params:
group_id = "default"
if 'saved_filter_params' in locals() and "group" in saved_filter_params:
group_id = saved_filter_params['group'][0]
else:
group_id = "default"
else:
group_id = request.query_params["group"]
topo_data = get_topology_data(
queryset=self.queryset,
individualOptions=individualOptions,
ignore_cable_type=ignore_cable_type,
save_coords=save_coords,
show_unconnected=show_unconnected,
show_cables=show_cables,
@@ -117,9 +166,18 @@ class ExportTopoToXML(PermissionRequiredMixin, ViewSet):
show_circuit=show_circuit,
show_power=show_power,
show_wireless=show_wireless,
group_sites=group_sites,
group_locations=group_locations,
group_racks=group_racks,
group_virtualchassis=group_virtualchassis,
group_id=group_id,
straight_cables=straight_cables,
draw_termination_labels=draw_termination_labels,
draw_cable_labels=draw_cable_labels,
grid_size=grid_size,
node_label_items=node_label_items,
)
xml_data = export_data_to_xml(topo_data).decode('utf-8')
xml_data = export_data_to_xml(topo_data).decode('utf-8').replace('\n', '&#xa;')
return HttpResponse(xml_data, content_type="application/xml; charset=utf-8")
else:
@@ -127,12 +185,12 @@ class ExportTopoToXML(PermissionRequiredMixin, ViewSet):
{"status": "Missing or malformed request parameters"}, status=400
)
class SaveRoleImageViewSet(PermissionRequiredMixin, ReadOnlyModelViewSet):
class SaveRoleImageViewSet(BaseViewSet, ReadOnlyModelViewSet):
queryset = DeviceRole.objects.none()
serializer_class = RoleImageSerializer
permission_required = (
"dcim.add_device_role",
"dcim.change_device_role",
"dcim.add_devicerole",
"dcim.change_devicerole",
)
@action(detail=False, methods=["post"])
@@ -142,15 +200,26 @@ class SaveRoleImageViewSet(PermissionRequiredMixin, ReadOnlyModelViewSet):
{"status": "Missing or malformed request body"}, status=400
)
device_roles = {
k: v.removeprefix(settings.STATIC_URL)
for k, v in request.data.items()
if k.isnumeric()}
content_type_ids = {
k[2:]: v.removeprefix(settings.STATIC_URL)
for k, v in request.data.items()
if k.startswith("ct") and k[2:].isnumeric()
}
if sys.version_info >= (3,9,0):
device_roles = {
k: v.removeprefix(settings.STATIC_URL)
for k, v in request.data.items()
if k.isnumeric()}
content_type_ids = {
k[2:]: v.removeprefix(settings.STATIC_URL)
for k, v in request.data.items()
if k.startswith("ct") and k[2:].isnumeric()
}
else:
device_roles = {}
for k, v in request.data.items():
if k.isdigit() and v.startswith(settings.STATIC_URL):
device_roles[k] = v[len(settings.STATIC_URL):]
content_type_ids = {}
for k, v in request.data.items():
if k.startswith("ct") and k[2:].isdigit() and v.startswith(settings.STATIC_URL):
content_type_ids[k[2:]] = v[len(settings.STATIC_URL):]
roles: Dict[int, DeviceRole] = DeviceRole.objects.in_bulk(device_roles.keys())
content_types: Dict[int, ContentType] = ContentType.objects.in_bulk(
@@ -194,3 +263,23 @@ class SaveRoleImageViewSet(PermissionRequiredMixin, ReadOnlyModelViewSet):
)
return JsonResponse({"status": "Ok"})
class CoordinateGroupViewSet(NetBoxModelViewSet):
queryset = CoordinateGroup.objects.all()
serializer_class = CoordinateGroupSerializer
class CoordinateViewSet(NetBoxModelViewSet):
queryset = Coordinate.objects.all()
serializer_class = CoordinateSerializer
class CircuitCoordinateViewSet(NetBoxModelViewSet):
queryset = CircuitCoordinate.objects.all()
serializer_class = CircuitCoordinateSerializer
class PowerPanelCoordinateViewSet(NetBoxModelViewSet):
queryset = PowerPanelCoordinate.objects.all()
serializer_class = PowerPanelCoordinateSerializer
class PowerFeedCoordinateViewSet(NetBoxModelViewSet):
queryset = PowerFeedCoordinate.objects.all()
serializer_class = PowerFeedCoordinateSerializer
+37
View File
@@ -0,0 +1,37 @@
from django.utils.translation import gettext_lazy as _
from utilities.choices import ChoiceSet
class NodeLabelItems(ChoiceSet):
DEVICE_NAME = 'devicename'
DEVICE_TYPE = 'devicetype'
ROLE = 'role'
DESCRIPTION = 'description'
PRIMARY_IPV4 = 'primaryipv4'
PRIMARY_IPV6 = 'primaryipv6'
OUT_OF_BAND_IP = 'outofbandip'
PLATFORM = 'platform'
SERIAL = 'serial'
TENANT = 'tenant'
SITE = 'site'
LOCATION = 'location'
RACK = 'rack'
VIRTUAL_CHASSIS = 'virtualchassis'
ASSET_TAG = 'assettag'
CHOICES = [
(DEVICE_NAME, _('Device Name')),
(DEVICE_TYPE, _('Device Type')),
(ROLE, _('Role')),
(DESCRIPTION, _('Description')),
(PRIMARY_IPV4, _('Primary IPv4')),
(PRIMARY_IPV6, _('Primary IPv6')),
(OUT_OF_BAND_IP, _('Out-of-band IP')),
(PLATFORM, _('Platform')),
(SERIAL, _('Serial')),
(TENANT, _('Tenant')),
(SITE, _('Site')),
(LOCATION, _('Location')),
(RACK, _('Rack')),
(VIRTUAL_CHASSIS, _('Virtual Chassis')),
(ASSET_TAG, _('Asset Tag')),
]
+190 -12
View File
@@ -1,51 +1,127 @@
import django_filters
from circuits.models import Circuit
from dcim.choices import DeviceStatusChoices
from dcim.models import Device, DeviceRole, Location, Rack, Region, Site
from dcim.models import Device, DeviceRole, Location, Rack, Region, Site, SiteGroup, Manufacturer, DeviceType, Platform, PowerPanel, PowerFeed
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from extras.filtersets import LocalConfigContextFilterSet
from extras.models import ConfigTemplate
from netbox.filtersets import NetBoxModelFilterSet
from tenancy.filtersets import TenancyFilterSet
from utilities.filters import TreeNodeMultipleChoiceFilter
from netbox_topology_views.models import CoordinateGroup, Coordinate
from tenancy.filtersets import TenancyFilterSet, ContactModelFilterSet
from utilities.filters import TreeNodeMultipleChoiceFilter, MultiValueCharFilter, MultiValueMACAddressFilter
from netbox_topology_views.models import CoordinateGroup, Coordinate, CircuitCoordinate, PowerPanelCoordinate, PowerFeedCoordinate
class DeviceFilterSet(TenancyFilterSet, NetBoxModelFilterSet):
class DeviceFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet, LocalConfigContextFilterSet):
q = django_filters.CharFilter(
method="search",
label="Search",
label=_("Search"),
)
manufacturer_id = django_filters.ModelMultipleChoiceFilter(
field_name='device_type__manufacturer',
queryset=Manufacturer.objects.all(),
label=_("Manufacturer (ID)"),
)
manufacturer = django_filters.ModelMultipleChoiceFilter(
field_name='device_type__manufacturer__slug',
queryset=Manufacturer.objects.all(),
to_field_name='slug',
label=_("Manufacturer (slug)"),
)
device_type_id = django_filters.ModelMultipleChoiceFilter(
queryset=DeviceType.objects.all(),
label=_("Device type (ID)"),
)
role_id = django_filters.ModelMultipleChoiceFilter(
field_name="role_id",
queryset=DeviceRole.objects.all(),
label="Role (ID)",
label=_("Role (ID)"),
)
platform_id = django_filters.ModelMultipleChoiceFilter(
queryset=Platform.objects.all(),
label=_("Platform (ID)"),
)
region_id = TreeNodeMultipleChoiceFilter(
queryset=Region.objects.all(),
field_name="site__region",
lookup_expr="in",
label="Region (ID)",
label=_("Region (ID)"),
)
site_group_id = TreeNodeMultipleChoiceFilter(
queryset=SiteGroup.objects.all(),
field_name="site__group",
lookup_expr="in",
label=_("Site Group (ID)"),
)
site_id = django_filters.ModelMultipleChoiceFilter(
queryset=Site.objects.all(),
label="Site (ID)",
label=_("Site (ID)"),
)
location_id = TreeNodeMultipleChoiceFilter(
queryset=Location.objects.all(),
field_name="location",
lookup_expr="in",
label="Location (ID)",
label=_("Location (ID)"),
)
rack_id = django_filters.ModelMultipleChoiceFilter(
queryset=Rack.objects.all(),
field_name="rack_id",
label="Rack (ID)",
label=_("Rack (ID)"),
)
status = django_filters.MultipleChoiceFilter(
choices=DeviceStatusChoices,
null_value=None,
)
mac_address = MultiValueMACAddressFilter(
field_name='interfaces__mac_addresses__mac_address',
label=_("MAC address"),
)
serial = MultiValueCharFilter(
lookup_expr='iexact'
)
console_ports = django_filters.BooleanFilter(
method='_console_ports',
label=_("Has console ports"),
)
console_server_ports = django_filters.BooleanFilter(
method='_console_server_ports',
label=_("Has console server ports"),
)
power_ports = django_filters.BooleanFilter(
method='_power_ports',
label=_("Has power ports"),
)
power_outlets = django_filters.BooleanFilter(
method='_power_outlets',
label=_("Has power outlets"),
)
interfaces = django_filters.BooleanFilter(
method='_interfaces',
label=_("Has interfaces"),
)
pass_through_ports = django_filters.BooleanFilter(
method='_pass_through_ports',
label=_("Has pass-through ports"),
)
config_template_id = django_filters.ModelMultipleChoiceFilter(
queryset=ConfigTemplate.objects.all(),
label=_("Config template (ID)"),
)
has_primary_ip = django_filters.BooleanFilter(
method='_has_primary_ip',
label=_("Has a primary IP"),
)
has_oob_ip = django_filters.BooleanFilter(
method='_has_oob_ip',
label=_("Has an out-of-band IP"),
)
virtual_chassis_member = django_filters.BooleanFilter(
method='_virtual_chassis_member',
label=_("Is a virtual chassis member"),
)
class Meta:
model = Device
fields = ["id", "name"]
fields = ["id", "name", "asset_tag", "airflow"]
def search(self, queryset, name, value):
"""Perform the filtered search."""
@@ -54,6 +130,108 @@ class DeviceFilterSet(TenancyFilterSet, NetBoxModelFilterSet):
qs_filter = Q(name__icontains=value)
return queryset.filter(qs_filter)
def _console_ports(self, queryset, name, value):
return queryset.exclude(consoleports__isnull=value)
def _console_server_ports(self, queryset, name, value):
return queryset.exclude(consoleserverports__isnull=value)
def _power_ports(self, queryset, name, value):
return queryset.exclude(powerports__isnull=value)
def _power_outlets(self, queryset, name, value):
return queryset.exclude(poweroutlets__isnull=value)
def _interfaces(self, queryset, name, value):
return queryset.exclude(interfaces__isnull=value)
def _pass_through_ports(self, queryset, name, value):
return queryset.exclude(
frontports__isnull=value,
rearports__isnull=value
)
def _has_primary_ip(self, queryset, name, value):
params = Q(primary_ip4__isnull=False) | Q(primary_ip6__isnull=False)
if value:
return queryset.filter(params)
return queryset.exclude(params)
def _has_oob_ip(self, queryset, name, value):
params = Q(oob_ip__isnull=False)
if value:
return queryset.filter(params)
return queryset.exclude(params)
def _virtual_chassis_member(self, queryset, name, value):
return queryset.exclude(virtual_chassis__isnull=value)
class CircuitCoordinatesFilterSet(NetBoxModelFilterSet):
group = django_filters.ModelMultipleChoiceFilter(
queryset = CoordinateGroup.objects.all(),
)
device = django_filters.ModelMultipleChoiceFilter(
queryset = Circuit.objects.all(),
)
class Meta:
model = CircuitCoordinate
fields = ['id', 'group', 'device', 'x', 'y']
def search(self, queryset, name, value):
"""Perform the filtered search."""
if not value.strip():
return queryset
return queryset.filter(
Q(group__name__icontains=value) |
Q(device__name__icontains=value)
)
class PowerPanelCoordinatesFilterSet(NetBoxModelFilterSet):
group = django_filters.ModelMultipleChoiceFilter(
queryset = CoordinateGroup.objects.all(),
)
device = django_filters.ModelMultipleChoiceFilter(
queryset = PowerPanel.objects.all(),
)
class Meta:
model = PowerPanelCoordinate
fields = ['id', 'group', 'device', 'x', 'y']
def search(self, queryset, name, value):
"""Perform the filtered search."""
if not value.strip():
return queryset
return queryset.filter(
Q(group__name__icontains=value) |
Q(device__name__icontains=value)
)
class PowerFeedCoordinatesFilterSet(NetBoxModelFilterSet):
group = django_filters.ModelMultipleChoiceFilter(
queryset = CoordinateGroup.objects.all(),
)
device = django_filters.ModelMultipleChoiceFilter(
queryset = PowerFeed.objects.all(),
)
class Meta:
model = PowerFeedCoordinate
fields = ['id', 'group', 'device', 'x', 'y']
def search(self, queryset, name, value):
"""Perform the filtered search."""
if not value.strip():
return queryset
return queryset.filter(
Q(group__name__icontains=value) |
Q(device__name__icontains=value)
)
class CoordinatesFilterSet(NetBoxModelFilterSet):
group = django_filters.ModelMultipleChoiceFilter(
queryset = CoordinateGroup.objects.all(),
+622 -193
View File
@@ -1,157 +1,388 @@
from cProfile import label
import imp
from django import forms
from django.conf import settings
from django.utils.translation import gettext as _
from dcim.models import Device, Site, Region, DeviceRole, Location, Rack
from circuits.models import Circuit
from dcim.models import Device, Site, SiteGroup, Region, DeviceRole, Location, Rack, Manufacturer, DeviceType, Platform, PowerPanel, PowerFeed
from django import forms
from dcim.choices import DeviceStatusChoices
from dcim.choices import DeviceStatusChoices, DeviceAirflowChoices
from tenancy.models import TenantGroup, Tenant
from tenancy.forms import TenancyFilterForm
from extras.models import ConfigTemplate
from extras.forms import LocalConfigContextFilterForm
from tenancy.forms import ContactModelFilterForm, TenancyFilterForm
from django.conf import settings
from netbox.forms import NetBoxModelFilterSetForm, NetBoxModelForm, NetBoxModelImportForm
from utilities.forms.rendering import FieldSet
from utilities.forms import BOOLEAN_WITH_BLANK_CHOICES, add_blank_choice
from utilities.forms.fields import (
TagFilterField,
DynamicModelMultipleChoiceField
)
from netbox_topology_views.models import IndividualOptions, CoordinateGroup, Coordinate
from netbox_topology_views.models import IndividualOptions, CoordinateGroup, Coordinate, CircuitCoordinate, PowerPanelCoordinate, PowerFeedCoordinate
from netbox_topology_views.choices import NodeLabelItems
class DeviceFilterForm(TenancyFilterForm, NetBoxModelFilterSetForm):
class DeviceFilterForm(
LocalConfigContextFilterForm,
TenancyFilterForm,
ContactModelFilterForm,
NetBoxModelFilterSetForm
):
model = Device
fieldsets = (
(
None,
(
"q",
"filter_id",
),
FieldSet('q', 'filter_id', 'tag'),
FieldSet(
'group', 'ignore_cable_type', 'save_coords', 'show_unconnected', 'show_cables', 'show_wireless',
'show_logical_connections', 'show_single_cable_logical_conns', 'show_neighbors',
'group_sites', 'group_locations', 'group_racks', 'group_virtualchassis', 'straight_cables',
'draw_termination_labels', 'draw_cable_labels', 'grid_size', 'node_label_items', name=_("Options")
),
(
None,
(
"group",
"save_coords",
"show_unconnected",
"show_cables",
"show_logical_connections",
"show_single_cable_logical_conns",
"show_neighbors",
"show_circuit",
"show_power",
"show_wireless",
),
FieldSet(
'show_circuit', 'show_power', name=_("Additional filter-independent types (non-devices)")
),
(
None,
(
"tenant_group_id",
"tenant_id",
),
FieldSet('id', name=_("Device")),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_("Location")),
FieldSet('status', 'role_id', 'airflow', 'serial', 'asset_tag', 'mac_address', name=_("Operation")),
FieldSet('manufacturer_id', 'device_type_id', 'platform_id', name=_("Hardware")),
FieldSet('tenant_group_id', 'tenant_id', name=_("Tenant")),
FieldSet('contact', 'contact_role', 'contact_group', name=_("Contacts")),
FieldSet(
'console_ports', 'console_server_ports', 'power_ports', 'power_outlets', 'interfaces', 'pass_through_ports', name=_("Components")
),
(None, ("region_id", "site_id", "location_id", "rack_id")),
(
None,
(
"role_id",
"id",
"status",
),
FieldSet(
'has_primary_ip', 'has_oob_ip', 'virtual_chassis_member', 'config_template_id', 'local_context_data', name=_("Miscellaneous")
),
(None, ("tag",)),
)
group = forms.ModelChoiceField(
queryset=CoordinateGroup.objects.all(),
required=False,
label=_("Coordinate group"),
)
region_id = DynamicModelMultipleChoiceField(
queryset=Region.objects.all(), required=False, label=_("Region")
)
role_id = DynamicModelMultipleChoiceField(
queryset=DeviceRole.objects.all(), required=False, label=_("Device Role")
label=_('Coordinate group'),
)
id = DynamicModelMultipleChoiceField(
queryset=Device.objects.all(),
required=False,
label=_("Device"),
label=_('Device'),
query_params={
"location_id": "$location_id",
"region_id": "$region_id",
"site_id": "$site_id",
"role_id": "$role_id",
'location_id': '$location_id',
'region_id': '$region_id',
'site_group_id': '$site_group_id',
'site_id': '$site_id',
'role_id': '$role_id',
'contact': '$contact',
'contact_role': '$contact_role',
'contact_group': '$contact_group',
},
)
region_id = DynamicModelMultipleChoiceField(
queryset=Region.objects.all(),
required=False,
label=_('Region')
)
site_group_id = DynamicModelMultipleChoiceField(
queryset=SiteGroup.objects.all(),
required=False,
label=_('Site Group'),
)
site_id = DynamicModelMultipleChoiceField(
queryset=Site.objects.all(),
required=False,
query_params={
"region_id": "$region_id",
'region_id': '$region_id',
'group_id': '$site_group_id',
},
label=_("Site"),
label=_('Site'),
)
location_id = DynamicModelMultipleChoiceField(
queryset=Location.objects.all(),
required=False,
query_params={
"region_id": "$region_id",
"site_id": "$site_id",
'region_id': '$region_id',
'site_group_id': '$site_group_id',
'site_id': '$site_id',
},
label=_("Location"),
label=_('Location'),
)
rack_id = DynamicModelMultipleChoiceField(
queryset=Rack.objects.all(),
required=False,
query_params={
"region_id": "$region_id",
"site_id": "$site_id",
"location_id": "$location_id",
'region_id': '$region_id',
'site_group_id': '$site_group_id',
'site_id': '$site_id',
'location_id': '$location_id',
},
label=_("Rack"),
label=_('Rack'),
)
status = forms.MultipleChoiceField(
choices=DeviceStatusChoices, required=False, label=_("Device Status")
choices=DeviceStatusChoices,
required=False,
label=_('Device Status')
)
role_id = DynamicModelMultipleChoiceField(
queryset=DeviceRole.objects.all(),
required=False,
label=_('Role')
)
airflow = forms.MultipleChoiceField(
label=_('Airflow'),
choices=add_blank_choice(DeviceAirflowChoices),
required=False
)
serial = forms.CharField(
label=_('Serial'),
required=False
)
asset_tag = forms.CharField(
label=_('Asset tag'),
required=False
)
mac_address = forms.CharField(
required=False,
label=_('MAC address')
)
manufacturer_id = DynamicModelMultipleChoiceField(
queryset=Manufacturer.objects.all(),
required=False,
label=_('Manufacturer')
)
device_type_id = DynamicModelMultipleChoiceField(
queryset=DeviceType.objects.all(),
required=False,
query_params={
'manufacturer_id': '$manufacturer_id'
},
label=_('Model')
)
platform_id = DynamicModelMultipleChoiceField(
queryset=Platform.objects.all(),
required=False,
null_option=_('None'),
label=_('Platform')
)
console_ports = forms.NullBooleanField(
required=False,
label=_('Has console ports'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
console_server_ports = forms.NullBooleanField(
required=False,
label=_('Has console server ports'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
power_ports = forms.NullBooleanField(
required=False,
label=_('Has power ports'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
power_outlets = forms.NullBooleanField(
required=False,
label=_('Has power outlets'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
interfaces = forms.NullBooleanField(
required=False,
label=_('Has interfaces'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
pass_through_ports = forms.NullBooleanField(
required=False,
label=_('Has pass-through ports'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
config_template_id = DynamicModelMultipleChoiceField(
queryset=ConfigTemplate.objects.all(),
required=False,
label=_('Config template')
)
has_primary_ip = forms.NullBooleanField(
required=False,
label=_('Has a primary IP'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
has_oob_ip = forms.NullBooleanField(
required=False,
label=_('Has an OOB IP'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
virtual_chassis_member = forms.NullBooleanField(
required=False,
label=_('Virtual chassis member'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
tag = TagFilterField(model)
# options
save_coords = forms.BooleanField(
label=_("Save Coordinates"),
ignore_cable_type = forms.MultipleChoiceField(
label=_('Ignore Termination Types'),
required=False,
disabled=(not settings.PLUGINS_CONFIG["netbox_topology_views"]["allow_coordinates_saving"] or settings.PLUGINS_CONFIG["netbox_topology_views"]["always_save_coordinates"]),
initial=(settings.PLUGINS_CONFIG["netbox_topology_views"]["always_save_coordinates"])
choices=IndividualOptions.CHOICES
)
show_unconnected = forms.BooleanField(
label=_("Show Unconnected"), required=False, initial=False
save_coords = forms.NullBooleanField(
label=_('Save Coordinates'),
required=False,
disabled=(not settings.PLUGINS_CONFIG['netbox_topology_views']['allow_coordinates_saving'] or settings.PLUGINS_CONFIG['netbox_topology_views']['always_save_coordinates']),
initial=(settings.PLUGINS_CONFIG['netbox_topology_views']['always_save_coordinates']),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_cables = forms.BooleanField(
label =_("Show Cables"), required=False, initial=False
show_unconnected = forms.NullBooleanField(
label=_('Show Unconnected'),
required=False,
initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_logical_connections = forms.BooleanField(
label =_("Show Logical Connections"), required=False, initial=False
show_cables = forms.NullBooleanField(
required=False,
initial=False,
label=_('Show Cables'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_single_cable_logical_conns = forms.BooleanField(
label =_("Show redundant Cable and Logical Connection"), required=False, initial=False
show_wireless = forms.NullBooleanField(
label =_('Show Wireless Links'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_neighbors = forms.BooleanField(
label =_("Show Neighbors"), required=False, initial=False
show_logical_connections = forms.NullBooleanField(
label =_('Show Logical Connections'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_circuit = forms.BooleanField(
label=_("Show Circuit Terminations"), required=False, initial=False
show_single_cable_logical_conns = forms.NullBooleanField(
label =_('Show redundant Cable and Logical Connection'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_power = forms.BooleanField(
label=_("Show Power Feeds"), required=False, initial=False
show_neighbors = forms.NullBooleanField(
label =_('Show Neighbors'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_wireless = forms.BooleanField(
label =_("Show Wireless Links"), required=False, initial=False
group_sites = forms.NullBooleanField(
label =_('Group Sites'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
group_locations = forms.NullBooleanField(
label =_('Group Locations'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
group_racks = forms.NullBooleanField(
label =_('Group Racks'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
group_virtualchassis = forms.NullBooleanField(
label =_('Group Virtual Chassis'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
straight_cables = forms.BooleanField(
label=_('Straight Cables'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
draw_termination_labels = forms.BooleanField(
label=_('Termination Labels'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
draw_cable_labels = forms.BooleanField(
label=_('Cable Labels'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
grid_size = forms.IntegerField(
label=_('Grid Size'),
required=False,
initial=0,
min_value=0,
max_value=1000,
help_text=_('Show grid and snap dragged icons to grid. Set to 0 to disable grid and snapping.')
)
node_label_items = forms.MultipleChoiceField(
label=_('Node Label Items'),
required=False,
choices=NodeLabelItems
)
# Additional types (non-devices)
show_circuit = forms.NullBooleanField(
label=_('Show Circuit Terminations'), required=False, initial=False,
help_text=_('All Circuits will be displayed. Circuits cannot be filtered.'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_power = forms.NullBooleanField(
label=_('Show Power Feeds'), required=False, initial=False,
help_text=_('All Power Feeds will be displayed. Power Feeds cannot be filtered.'),
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
class RackElevationFilterForm(forms.Form):
"""Compact selector for the rack elevation view."""
site_id = DynamicModelMultipleChoiceField(
queryset=Site.objects.all(), required=False, label=_("Site")
)
location_id = DynamicModelMultipleChoiceField(
queryset=Location.objects.all(), required=False, label=_("Location"),
query_params={"site_id": "$site_id"},
)
rack_id = DynamicModelMultipleChoiceField(
queryset=Rack.objects.all(), required=False, label=_("Racks"),
query_params={"site_id": "$site_id", "location_id": "$location_id"},
help_text=_("Select one or more racks. If empty, all matching racks are shown."),
)
include_empty = forms.BooleanField(
required=False, initial=False, label=_("Include empty racks")
)
class CoordinateGroupsForm(NetBoxModelForm):
fieldsets = (
('Group Details', ('name', 'description')),
FieldSet('name', 'description', name=_("Group Details")),
)
class Meta:
@@ -163,25 +394,142 @@ class CoordinateGroupsImportForm(NetBoxModelImportForm):
model = CoordinateGroup
fields = ('name', 'description')
class CircuitCoordinatesForm(NetBoxModelForm):
fieldsets = (
FieldSet('group', 'device', 'x', 'y', name=_("Circuit Coordinate")),
)
class Meta:
model = CircuitCoordinate
fields = ('group', 'device', 'x', 'y')
class PowerPanelCoordinatesForm(NetBoxModelForm):
fieldsets = (
FieldSet('group', 'device', 'x', 'y', name=_("Power Panel")),
)
class Meta:
model = PowerPanelCoordinate
fields = ('group', 'device', 'x', 'y')
class PowerFeedCoordinatesForm(NetBoxModelForm):
fieldsets = (
FieldSet('group', 'device', 'x', 'y', name=_("PowerFeed Coordinate")),
)
class Meta:
model = PowerFeedCoordinate
fields = ('group', 'device', 'x', 'y')
class CoordinatesForm(NetBoxModelForm):
fieldsets = (
('Coordinate', ('group', 'device', 'x', 'y')),
FieldSet('group', 'device', 'x', 'y', name=_("Coordinate")),
)
class Meta:
model = Coordinate
fields = ('group', 'device', 'x', 'y')
class CircuitCoordinatesImportForm(NetBoxModelImportForm):
class Meta:
model = CircuitCoordinate
fields = ('group', 'device', 'x', 'y')
class PowerPanelCoordinatesImportForm(NetBoxModelImportForm):
class Meta:
model = PowerPanelCoordinate
fields = ('group', 'device', 'x', 'y')
class PowerFeedCoordinatesImportForm(NetBoxModelImportForm):
class Meta:
model = PowerFeedCoordinate
fields = ('group', 'device', 'x', 'y')
class CoordinatesImportForm(NetBoxModelImportForm):
class Meta:
model = Coordinate
fields = ('group', 'device', 'x', 'y')
class CircuitCoordinatesFilterForm(NetBoxModelFilterSetForm):
model = CircuitCoordinate
fieldsets = (
FieldSet('q', 'filter_id'),
FieldSet('group', 'device', 'x', 'y', name=_("Circuit Coordinates")),
)
group = forms.ModelMultipleChoiceField(
queryset=CoordinateGroup.objects.all(),
required=False
)
device = DynamicModelMultipleChoiceField(
queryset=Circuit.objects.all(),
required=False
)
x = forms.IntegerField(
required=False
)
y = forms.IntegerField(
required=False
)
class PowerPanelCoordinatesFilterForm(NetBoxModelFilterSetForm):
model = PowerPanelCoordinate
fieldsets = (
FieldSet('q', 'filter_id'),
FieldSet('group', 'device', 'x', 'y', name=_('PowerPanel Coordinates')),
)
group = forms.ModelMultipleChoiceField(
queryset=CoordinateGroup.objects.all(),
required=False
)
device = DynamicModelMultipleChoiceField(
queryset=PowerPanel.objects.all(),
required=False
)
x = forms.IntegerField(
required=False
)
y = forms.IntegerField(
required=False
)
class PowerFeedCoordinatesFilterForm(NetBoxModelFilterSetForm):
model = Coordinate
fieldsets = (
FieldSet('q', 'filter_id'),
FieldSet('group', 'device', 'x', 'y', name=_("PowerFeed Coordinates")),
)
group = forms.ModelMultipleChoiceField(
queryset=CoordinateGroup.objects.all(),
required=False
)
device = DynamicModelMultipleChoiceField(
queryset=PowerFeed.objects.all(),
required=False
)
x = forms.IntegerField(
required=False
)
y = forms.IntegerField(
required=False
)
class CoordinatesFilterForm(NetBoxModelFilterSetForm):
model = Coordinate
fieldsets = (
(None, ('q', 'filter_id')),
('Coordinates', ('group', 'device', 'x', 'y'))
FieldSet('q', 'filter_id'),
FieldSet('group', 'device', 'x', 'y', name=_("Coordinates")),
)
group = forms.ModelMultipleChoiceField(
@@ -204,133 +552,214 @@ class CoordinatesFilterForm(NetBoxModelFilterSetForm):
class IndividualOptionsForm(NetBoxModelForm):
fieldsets = (
(
None,
FieldSet
(
"user_id",
"ignore_cable_type",
"preselected_device_roles",
"preselected_tags",
"save_coords",
"show_unconnected",
"show_cables",
"show_logical_connections",
"show_single_cable_logical_conns",
"show_neighbors",
"show_circuit",
"show_power",
"show_wireless",
"draw_default_layout",
'ignore_cable_type',
'preselected_device_roles',
'preselected_tags',
'save_coords',
'show_unconnected',
'show_cables',
'show_wireless',
'show_logical_connections',
'show_single_cable_logical_conns',
'show_neighbors',
'group_sites',
'group_locations',
'group_racks',
'group_virtualchassis',
'draw_default_layout',
'straight_cables',
'draw_termination_labels',
'draw_cable_labels',
'grid_size',
'node_label_items',
),
FieldSet
(
'show_circuit',
'show_power',
name=_("Additional filter-independent types (non-devices)")
),
),
)
user_id = forms.CharField(widget=forms.HiddenInput())
ignore_cable_type = forms.MultipleChoiceField(
label=_("Ignore Termination Types"),
required=False,
label=_('Ignore Termination Types'),
required=False,
choices=IndividualOptions.CHOICES,
help_text=_("Choose Termination Types that you want to be ignored. "
"If any ignored Termination Type is part of a connection, the "
"cable is not displayed.")
help_text=_('Choose Termination Types that you want to be ignored. '
'If any ignored Termination Type is part of a connection, the '
'cable is not displayed.')
)
preselected_device_roles = DynamicModelMultipleChoiceField(
label=_("Preselected Device Role"),
label=_('Preselected Device Role'),
queryset=DeviceRole.objects.all(),
required=False,
help_text=_("Select Device Roles that you want to have "
"preselected in the filter tab.")
help_text=_('Select Device Roles that you want to have '
'preselected in the filter tab.')
)
preselected_tags = forms.ModelMultipleChoiceField(
label=_("Preselected Tags"),
label=_('Preselected Tags'),
queryset=Device.tags.all(),
required=False,
help_text=_("Select Tags that you want to have "
"preselected in the filter tab.")
help_text=_('Select Tags that you want to have '
'preselected in the filter tab.')
)
save_coords = forms.BooleanField(
label=_("Save Coordinates"),
required=False,
initial=False,
help_text=_("Coordinates of nodes will be saved if dragged to a different "
"position. This option depends on parameters set in the config file. "
"It has no effect if 'allow_coordinates_saving' has not been set or "
" 'always_save_coordinates' has been set.")
)
show_unconnected = forms.BooleanField(
label=_("Show Unconnected"),
required=False,
initial=False,
help_text=_("Draws devices that have no connections or for which no "
"connection is displayed. This option depends on other parameters "
"like 'Show Cables' and 'Show Logical Connections'.")
)
show_cables = forms.BooleanField(
label =_("Show Cables"),
required=False,
initial=False,
help_text=_("Displays connections between interfaces that are connected "
"with one or more cables. These connections are displayed as solid "
"lines in the color of the cable.")
)
show_logical_connections = forms.BooleanField(
label =_("Show Logical Connections"),
required=False,
initial=False,
help_text=_("Displays connections between devices that are not "
"directly connected (e.g. via patch panels). These connections "
"are displayed as yellow dotted lines.")
)
show_single_cable_logical_conns = forms.BooleanField(
label = ("Show redundant Cable and Logical Connection"),
required = False,
initial=False,
help_text=_("Shows a logical connection (in addition to a cable), "
"even if a cable is directly connected. Leaving this option "
"disabled prevents that redundant display. This option only "
"has an effect if 'Show Logical Connections' is activated.")
)
show_neighbors = forms.BooleanField(
label =_("Show Neighbors"),
required=False,
initial=False,
help_text=_("Adds neighbors to the filter result set automatically. "
"Link peers will be added if 'Show Cables' is ticked, far-end "
"terminations will be added if 'Show Logical Connections' is ticked.")
)
show_circuit = forms.BooleanField(
label=_("Show Circuit Terminations"),
required=False,
initial=False,
help_text=_("Displays connections between circuit terminations. "
"These connections are displayed as blue dashed lines.")
)
show_power = forms.BooleanField(
label=_("Show Power Feeds"),
required=False,
initial=False,
help_text=_("Displays connections between power outlets and power "
"ports. These connections are displayed as solid lines in the "
"color of the cable. This option depends on 'Show Cables'.")
)
show_wireless = forms.BooleanField(
label =_("Show Wireless Links"),
required=False,
initial=False,
help_text=_("Displays wireless connections. These connections are "
"displayed as blue dotted lines.")
)
draw_default_layout = forms.BooleanField(
label = ("Draw Default Layout"),
label=_('Save Coordinates'),
required=False,
initial=False,
help_text=_("Enable this option if you want to draw the topology on "
"the initial load (when you go to the topology plugin page).")
help_text=_('Coordinates of nodes will be saved if dragged to a different '
'position. This option depends on parameters set in the config file. '
'It has no effect if \'allow_coordinates_saving\' has not been set or '
' \'always_save_coordinates\' has been set.')
)
show_unconnected = forms.BooleanField(
label=_('Show Unconnected'),
required=False,
initial=False,
help_text=_('Draws devices that have no connections or for which no '
'connection is displayed. This option depends on other parameters '
'like \'Show Cables\' and \'Show Logical Connections\'.')
)
show_cables = forms.BooleanField(
label =_('Show Cables'),
required=False,
initial=False,
help_text=_('Displays connections between interfaces that are connected '
'with one or more cables. These connections are displayed as solid '
'lines in the color of the cable.')
)
show_wireless = forms.BooleanField(
label =_('Show Wireless Links'),
required=False,
initial=False,
help_text=_('Displays wireless connections. These connections are '
'displayed as blue dotted lines.')
)
show_logical_connections = forms.BooleanField(
label =_('Show Logical Connections'),
required=False,
initial=False,
help_text=_('Displays connections between devices that are not '
'directly connected (e.g. via patch panels). These connections '
'are displayed as yellow dotted lines.')
)
show_single_cable_logical_conns = forms.BooleanField(
label = _('Show redundant Cable and Logical Connection'),
required = False,
initial=False,
help_text=_('Shows a logical connection (in addition to a cable), '
'even if a cable is directly connected. Leaving this option '
'disabled prevents that redundant display. This option only '
'has an effect if \'Show Logical Connections\' is activated.')
)
show_neighbors = forms.BooleanField(
label =_('Show Neighbors'),
required=False,
initial=False,
help_text=_('Adds neighbors to the filter result set automatically. '
'Link peers will be added if \'Show Cables\' is ticked, far-end '
'terminations will be added if \'Show Logical Connections\' is ticked.')
)
group_sites = forms.BooleanField(
label =_('Group Sites'),
required=False,
initial=False,
help_text=_('Draws a rectangle around Devices that belong to the '
'same site.')
)
group_locations = forms.BooleanField(
label =_('Group Locations'),
required=False,
initial=False,
help_text=_('Draws a rectangle around Devices that belong to the '
'same location.')
)
group_racks = forms.BooleanField(
label =_('Group Racks'),
required=False,
initial=False,
help_text=_('Draws a rectangle around Devices that belong to the '
'same rack.')
)
group_virtualchassis = forms.BooleanField(
label =_('Group Virtual Chassis'),
required=False,
initial=False,
help_text=_('Draws a rectangle around Devices that belong to the '
'same virtual chassis.')
)
draw_default_layout = forms.BooleanField(
label = _('Draw Default Layout'),
required=False,
initial=False,
help_text=_('Enable this option if you want to draw the topology on '
'the initial load (when you go to the topology plugin page).')
)
straight_cables = forms.BooleanField(
label=_('Use Straight Cables'),
required=False,
initial=False,
help_text=_('Enable this option if you want to draw cables as straight lines '
'instead of curves.')
)
draw_termination_labels = forms.BooleanField(
label=_('Termination Labels'),
required=False,
initial=False,
help_text=_('Enable this option if you want to draw a label on each '
'cable end.')
)
draw_cable_labels = forms.BooleanField(
label=_('Cable Labels'),
required=False,
initial=False,
help_text=_('Enable this option if you want to draw a cable labels.')
)
grid_size = forms.IntegerField(
label=_('Grid Size'),
required=True,
initial=0,
min_value=0,
max_value=1000,
help_text=_('Default grid value. Set to 0 to disable grid. '
'Integers between 0 and 1000 are allowed. Snap to grid will be '
'automatically enabled for values > 0.')
)
node_label_items = forms.MultipleChoiceField(
label=_('Node Label Items'),
required=False,
choices=NodeLabelItems,
help_text=_('Choose Label Items that you want to be displayed.')
)
show_circuit = forms.BooleanField(
label=_('Show Circuit Terminations'),
required=False,
initial=False,
help_text=_('Displays connections between circuit terminations. '
'These connections are displayed as blue dashed lines. '
'Be aware that Circuits cannot be filtered.')
)
show_power = forms.BooleanField(
label=_('Show Power Feeds'),
required=False,
initial=False,
help_text=_('Displays connections between power outlets and power '
'ports. These connections are displayed as solid lines in the '
'color of the cable. This option depends on \'Show Cables\'. '
'Be aware that Power Feeds cannot be filtered.')
)
class Meta:
model = IndividualOptions
fields = [
'user_id', 'ignore_cable_type', 'preselected_device_roles', 'preselected_tags', 'save_coords', 'show_unconnected', 'show_cables', 'show_logical_connections', 'show_single_cable_logical_conns', 'show_neighbors', 'show_circuit', 'show_power', 'show_wireless', 'draw_default_layout'
]
'user_id', 'ignore_cable_type', 'preselected_device_roles', 'preselected_tags',
'save_coords', 'show_unconnected', 'show_cables', 'show_wireless',
'show_logical_connections', 'show_single_cable_logical_conns', 'show_neighbors',
'group_sites', 'group_locations', 'group_racks', 'group_virtualchassis',
'draw_default_layout', 'straight_cables', 'draw_termination_labels', 'draw_cable_labels',
'grid_size', 'node_label_items', 'show_circuit', 'show_power'
]
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,70 @@
# Generated by Django 4.1.8 on 2023-09-25 21:18
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
import utilities.json
class Migration(migrations.Migration):
dependencies = [
('netbox_topology_views', '0005_individualoptions_save_coords'),
]
operations = [
migrations.CreateModel(
name='PowerPanelCoordinate',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True, null=True)),
('last_updated', models.DateTimeField(auto_now=True, null=True)),
('custom_field_data', models.JSONField(blank=True, default=dict, encoder=utilities.json.CustomFieldJSONEncoder)),
('x', models.IntegerField()),
('y', models.IntegerField()),
('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dcim.powerpanel')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='netbox_topology_views.coordinategroup')),
('tags', taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag')),
],
options={
'ordering': ['group', 'device'],
'unique_together': {('device', 'group')},
},
),
migrations.CreateModel(
name='PowerFeedCoordinate',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True, null=True)),
('last_updated', models.DateTimeField(auto_now=True, null=True)),
('custom_field_data', models.JSONField(blank=True, default=dict, encoder=utilities.json.CustomFieldJSONEncoder)),
('x', models.IntegerField()),
('y', models.IntegerField()),
('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dcim.powerfeed')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='netbox_topology_views.coordinategroup')),
('tags', taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag')),
],
options={
'ordering': ['group', 'device'],
'unique_together': {('device', 'group')},
},
),
migrations.CreateModel(
name='CircuitCoordinate',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True, null=True)),
('last_updated', models.DateTimeField(auto_now=True, null=True)),
('custom_field_data', models.JSONField(blank=True, default=dict, encoder=utilities.json.CustomFieldJSONEncoder)),
('x', models.IntegerField()),
('y', models.IntegerField()),
('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='circuits.circuit')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='netbox_topology_views.coordinategroup')),
('tags', taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag')),
],
options={
'ordering': ['group', 'device'],
'unique_together': {('device', 'group')},
},
),
]
@@ -0,0 +1,28 @@
# Generated by Django 4.2.10 on 2024-03-02 16:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('netbox_topology_views', '0006_powerpanelcoordinate_powerfeedcoordinate_and_more'),
]
operations = [
migrations.AddField(
model_name='individualoptions',
name='group_locations',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='individualoptions',
name='group_racks',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='individualoptions',
name='group_sites',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 4.2.10 on 2024-04-29 14:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('netbox_topology_views', '0007_individualoptions_group_locations_and_more'),
]
operations = [
migrations.AddField(
model_name='individualoptions',
name='straight_cables',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.0.6 on 2024-07-29 08:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('netbox_topology_views', '0008_straight_cables'),
]
operations = [
migrations.AddField(
model_name='individualoptions',
name='group_virtualchassis',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.0.6 on 2024-08-14 09:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('netbox_topology_views', '0009_individualoptions_group_virtualchassis'),
]
operations = [
migrations.AddField(
model_name='individualoptions',
name='grid_size',
field=models.PositiveSmallIntegerField(default=0),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.0.9 on 2024-09-27 18:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('netbox_topology_views', '0010_individualoptions_grid_size'),
]
operations = [
migrations.AddField(
model_name='individualoptions',
name='node_label_items',
field=models.CharField(blank=True, max_length=255),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.2.9 on 2026-02-19 18:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('netbox_topology_views', '0011_individualoptions_node_label_items'),
]
operations = [
migrations.AddField(
model_name='individualoptions',
name='draw_termination_labels',
field=models.BooleanField(default=False),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.2.12 on 2026-03-26 07:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('netbox_topology_views', '0012_individualoptions_draw_termination_labels'),
]
operations = [
migrations.AddField(
model_name='individualoptions',
name='draw_cable_labels',
field=models.BooleanField(default=False),
),
]
+236 -18
View File
@@ -1,18 +1,20 @@
from pathlib import Path
from typing import Optional
from dcim.models import Device, DeviceRole
from circuits.models import Circuit
from dcim.models import Device, DeviceRole, PowerPanel, PowerFeed
from extras.models import Tag
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.templatetags.static import static
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from netbox.models import NetBoxModel
from netbox.models.features import (
ChangeLoggingMixin,
ExportTemplatesMixin,
WebhooksMixin,
EventRulesMixin,
)
from netbox_topology_views.utils import (
@@ -24,22 +26,27 @@ from netbox_topology_views.utils import (
image_static_url,
)
from netbox_topology_views.choices import NodeLabelItems
class RoleImage(ChangeLoggingMixin, ExportTemplatesMixin, WebhooksMixin):
class RoleImage(ChangeLoggingMixin, ExportTemplatesMixin, EventRulesMixin):
class Meta:
verbose_name = _('role image')
verbose_name_plural = _('role images')
indexes = [
models.Index(fields=["content_type", "object_id"]),
]
objects: "models.Manager[RoleImage]"
image = models.CharField("Path within the netbox static directory", max_length=255)
image = models.CharField(_("Path within the netbox static directory"), max_length=255)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField(null=True, blank=True)
__role: Optional[Role] = None
_netbox_private = True
@property
def role(self) -> Role:
if self.__role:
@@ -101,17 +108,23 @@ class CoordinateGroup(NetBoxModel):
This allows different visualizations with the same devices.
"""
name = models.CharField(
verbose_name=_('name'),
max_length=100,
unique=True,
)
description = models.CharField(
verbose_name=_('description'),
max_length=255,
blank = True,
)
_netbox_private = True
class Meta:
ordering = ['name']
verbose_name = _('coordinate group')
verbose_name_plural = _('coordinate groups')
def __str__(self):
return self.name
@@ -125,18 +138,22 @@ class Coordinate(NetBoxModel):
position. Devices belong to one or more coordinate groups. They have to
be unique together.
"""
device = models.ForeignKey(Device, on_delete=models.CASCADE)
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE)
device = models.ForeignKey(Device, on_delete=models.CASCADE, verbose_name=_('device'))
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group'))
x = models.IntegerField(
help_text='X-coordinate of the device (horizontal) on the canvas. '
'Smaller values correspond to a position further up on the monitor.',
verbose_name=_('X'),
help_text=_('X-coordinate of the device (horizontal) on the canvas. '
'Smaller values correspond to a position further to the left on the monitor.'),
)
y = models.IntegerField(
help_text='Y-coordinate of the device (vertical) on the canvas. '
'Smaller values correspond to a position further to the left on the monitor.',
verbose_name=_('Y'),
help_text=_('Y-coordinate of the device (vertical) on the canvas. '
'Smaller values correspond to a position further up on the monitor.'),
)
_netbox_private = True
def get_or_create_default_group(group_id):
# Default group named "default" must always exist in order to make sure
# that coordinate values can be stored even if no coordinate group has been
@@ -148,9 +165,9 @@ class Coordinate(NetBoxModel):
else:
group = CoordinateGroup(
name="default",
description="Automatically generated default group. If you delete "
description=_("Automatically generated default group. If you delete "
"this group, all default coordinates are gone for good but "
"the group itself will be re-created."
"the group itself will be re-created.")
)
group.save()
group_id = group.pk
@@ -161,6 +178,8 @@ class Coordinate(NetBoxModel):
class Meta:
ordering = ['group', 'device']
unique_together = ('device', 'group')
verbose_name = _('device coordinate')
verbose_name_plural = _('device coordinates')
def __str__(self):
return f'{self.x};{self.y}'
@@ -168,15 +187,180 @@ class Coordinate(NetBoxModel):
def get_absolute_url(self):
return reverse('plugins:netbox_topology_views:coordinate', args=[self.pk])
class CircuitCoordinate(NetBoxModel):
"""
Coordinates are being used to place devices in a topology view onto a certain
position. Devices belong to one or more coordinate groups. They have to
be unique together.
"""
device = models.ForeignKey(Circuit, on_delete=models.CASCADE, verbose_name=_('circuit'))
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group'))
x = models.IntegerField(
verbose_name=_('X'),
help_text=_('X-coordinate of the device (horizontal) on the canvas. '
'Smaller values correspond to a position further to the left on the monitor.'),
)
y = models.IntegerField(
verbose_name=_('Y'),
help_text=_('Y-coordinate of the device (vertical) on the canvas. '
'Smaller values correspond to a position further up on the monitor.'),
)
_netbox_private = True
def get_or_create_default_group(group_id):
# Default group named "default" must always exist in order to make sure
# that coordinate values can be stored even if no coordinate group has been
# selected. The default group will be added automatically if it does not exist.
try:
if CoordinateGroup.objects.filter(name="default"):
group = CoordinateGroup.objects.get(name="default")
group_id = group.pk
else:
group = CoordinateGroup(
name="default",
description=_("Automatically generated default group. If you delete "
"this group, all default coordinates are gone for good but "
"the group itself will be re-created.")
)
group.save()
group_id = group.pk
except:
return False
return group_id
class Meta:
ordering = ['group', 'device']
unique_together = ('device', 'group')
verbose_name = _('circuit coordinate')
verbose_name_plural = _('circuit coordinates')
def __str__(self):
return f'{self.x};{self.y}'
def get_absolute_url(self):
return reverse('plugins:netbox_topology_views:circuitcoordinate', args=[self.pk])
class PowerPanelCoordinate(NetBoxModel):
"""
Coordinates are being used to place devices in a topology view onto a certain
position. Devices belong to one or more coordinate groups. They have to
be unique together.
"""
device = models.ForeignKey(PowerPanel, on_delete=models.CASCADE, verbose_name=_('power panel'))
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group'))
x = models.IntegerField(
verbose_name=_('X'),
help_text=_('X-coordinate of the device (horizontal) on the canvas. '
'Smaller values correspond to a position further to the left on the monitor.'),
)
y = models.IntegerField(
verbose_name=_('Y'),
help_text=_('Y-coordinate of the device (vertical) on the canvas. '
'Smaller values correspond to a position further up on the monitor.'),
)
_netbox_private = True
def get_or_create_default_group(group_id):
# Default group named "default" must always exist in order to make sure
# that coordinate values can be stored even if no coordinate group has been
# selected. The default group will be added automatically if it does not exist.
try:
if CoordinateGroup.objects.filter(name="default"):
group = CoordinateGroup.objects.get(name="default")
group_id = group.pk
else:
group = CoordinateGroup(
name="default",
description=_("Automatically generated default group. If you delete "
"this group, all default coordinates are gone for good but "
"the group itself will be re-created.")
)
group.save()
group_id = group.pk
except:
return False
return group_id
class Meta:
ordering = ['group', 'device']
unique_together = ('device', 'group')
verbose_name = _('power panel coordinate')
verbose_name_plural = _('power panel coordinates')
def __str__(self):
return f'{self.x};{self.y}'
def get_absolute_url(self):
return reverse('plugins:netbox_topology_views:powerpanelcoordinate', args=[self.pk])
class PowerFeedCoordinate(NetBoxModel):
"""
Coordinates are being used to place devices in a topology view onto a certain
position. Devices belong to one or more coordinate groups. They have to
be unique together.
"""
device = models.ForeignKey(PowerFeed, on_delete=models.CASCADE, verbose_name=_('power feed'))
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group'))
x = models.IntegerField(
verbose_name=_('X'),
help_text=_('X-coordinate of the device (horizontal) on the canvas. '
'Smaller values correspond to a position further to the left on the monitor.'),
)
y = models.IntegerField(
verbose_name=_('Y'),
help_text=_('Y-coordinate of the device (vertical) on the canvas. '
'Smaller values correspond to a position further up on the monitor.'),
)
_netbox_private = True
def get_or_create_default_group(group_id):
# Default group named "default" must always exist in order to make sure
# that coordinate values can be stored even if no coordinate group has been
# selected. The default group will be added automatically if it does not exist.
try:
if CoordinateGroup.objects.filter(name="default"):
group = CoordinateGroup.objects.get(name="default")
group_id = group.pk
else:
group = CoordinateGroup(
name="default",
description=_("Automatically generated default group. If you delete "
"this group, all default coordinates are gone for good but "
"the group itself will be re-created.")
)
group.save()
group_id = group.pk
except:
return False
return group_id
class Meta:
ordering = ['group', 'device']
unique_together = ('device', 'group')
verbose_name = _('power feed coordinate')
verbose_name_plural = _('power feed coordinates')
def __str__(self):
return f'{self.x};{self.y}'
def get_absolute_url(self):
return reverse('plugins:netbox_topology_views:powerfeedcoordinate', args=[self.pk])
class IndividualOptions(NetBoxModel):
CHOICES = (
('interface', 'interface'),
('front port', 'front port'),
('rear port', 'rear port'),
('power outlet', 'power outlet'),
('power port', 'power port'),
('console port', 'console port'),
('console server port', 'console server port'),
('frontport', 'frontport'),
('rearport', 'rearport'),
('poweroutlet', 'poweroutlet'),
('powerport', 'powerport'),
('consoleport', 'consoleport'),
('consoleserverport', 'consoleserverport'),
)
user_id = models.IntegerField(
@@ -226,9 +410,43 @@ class IndividualOptions(NetBoxModel):
show_wireless = models.BooleanField(
default=False
)
group_sites = models.BooleanField(
default=False
)
group_locations = models.BooleanField(
default=False
)
group_racks = models.BooleanField(
default=False
)
group_virtualchassis = models.BooleanField(
default=False
)
draw_default_layout = models.BooleanField(
default=False
)
straight_cables = models.BooleanField(
default=False
)
draw_termination_labels = models.BooleanField(
default=False
)
draw_cable_labels = models.BooleanField(
default=False
)
grid_size = models.PositiveSmallIntegerField(
default=0
)
node_label_items = models.CharField(
max_length=255,
blank=True
)
_netbox_private = True
class Meta:
verbose_name = _('individual options')
verbose_name_plural = _('individual options')
def __str___(self):
return f"{self.user_id}"
+71 -18
View File
@@ -1,55 +1,108 @@
from extras.plugins import PluginMenu, PluginMenuItem, PluginMenuButton
from utilities.choices import ButtonColorChoices
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginMenu, PluginMenuItem, PluginMenuButton
coordinategroup_buttons = (
PluginMenuButton(
link='plugins:netbox_topology_views:coordinategroup_add',
title='Add',
title=_('Add'),
icon_class='mdi mdi-plus-thick',
color=ButtonColorChoices.GREEN,
permissions=['netbox_topology_views.add_coordinategroup']
),
PluginMenuButton(
link='plugins:netbox_topology_views:coordinategroup_import',
title='Import',
title=_('Import'),
icon_class='mdi mdi-upload',
color=ButtonColorChoices.CYAN,
permissions=['netbox_topology_views.add_coordinategroup']
)
)
circuitcoordinate_buttons = (
PluginMenuButton(
link='plugins:netbox_topology_views:circuitcoordinate_add',
title=_('Add'),
icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate']
),
PluginMenuButton(
link='plugins:netbox_topology_views:circuitcoordinate_import',
title=_('Import'),
icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate']
)
)
powerpanelcoordinate_buttons = (
PluginMenuButton(
link='plugins:netbox_topology_views:powerpanelcoordinate_add',
title=_('Add'),
icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate']
),
PluginMenuButton(
link='plugins:netbox_topology_views:powerpanelcoordinate_import',
title=_('Import'),
icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate']
)
)
powerfeedcoordinate_buttons = (
PluginMenuButton(
link='plugins:netbox_topology_views:powerfeedcoordinate_add',
title=_('Add'),
icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate']
),
PluginMenuButton(
link='plugins:netbox_topology_views:powerfeedcoordinate_import',
title=_('Import'),
icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate']
)
)
coordinate_buttons = (
PluginMenuButton(
link='plugins:netbox_topology_views:coordinate_add',
title='Add',
title=_('Add'),
icon_class='mdi mdi-plus-thick',
color=ButtonColorChoices.GREEN,
permissions=['netbox_topology_views.add_coordinate']
),
PluginMenuButton(
link='plugins:netbox_topology_views:coordinate_import',
title='Import',
title=_('Import'),
icon_class='mdi mdi-upload',
color=ButtonColorChoices.CYAN,
permissions=['netbox_topology_views.add_coordinate']
)
)
menu = PluginMenu(
label='Topology Views',
label=_('Topology Views'),
icon_class="mdi mdi-sitemap",
groups=(
('TOPOLOGY',
(_('Topology'),
(
PluginMenuItem(link="plugins:netbox_topology_views:home", link_text="Topology", permissions=["dcim.view_site", "dcim.view_device"]),
PluginMenuItem(link="plugins:netbox_topology_views:coordinategroup_list", link_text="Coordinate Groups", buttons=coordinategroup_buttons, permissions=['netbox_topology_views.view_coordinategroup']),
PluginMenuItem(link="plugins:netbox_topology_views:coordinate_list", link_text="Coordinates", buttons=coordinate_buttons, permissions=['netbox_topology_views.view_coordinate']),
PluginMenuItem(link="plugins:netbox_topology_views:home", link_text=_("Topology"), permissions=["dcim.view_site", "dcim.view_device"]),
),
),
('PREFERENCES',
(_('More views'),
(
PluginMenuItem(link="plugins:netbox_topology_views:images", link_text="Images", permissions=[ "dcim.view_site","dcim.view_device_role"]),
PluginMenuItem(link="plugins:netbox_topology_views:individualoptions", link_text="Individual Options", permissions=['netbox_topology_views.change_individualoptions']),
PluginMenuItem(link="plugins:netbox_topology_views:rack_elevation", link_text=_("Rack view"), permissions=["dcim.view_rack", "dcim.view_device", "dcim.view_cable"]),
),
),
(_('Coordinates'),
(
PluginMenuItem(link="plugins:netbox_topology_views:coordinategroup_list", link_text=_("Coordinate Groups"), buttons=coordinategroup_buttons, permissions=['netbox_topology_views.view_coordinategroup']),
PluginMenuItem(link="plugins:netbox_topology_views:coordinate_list", link_text=_("Device Coordinates"), buttons=coordinate_buttons, permissions=['netbox_topology_views.view_coordinate']),
PluginMenuItem(link="plugins:netbox_topology_views:powerfeedcoordinate_list", link_text=_("Power Feed Coords"), buttons=powerfeedcoordinate_buttons, permissions=['netbox_topology_views.view_coordinate']),
PluginMenuItem(link="plugins:netbox_topology_views:powerpanelcoordinate_list", link_text=_("Power Panel Coords"), buttons=powerpanelcoordinate_buttons, permissions=['netbox_topology_views.view_coordinate']),
PluginMenuItem(link="plugins:netbox_topology_views:circuitcoordinate_list", link_text=_("Circuit Coordinates"), buttons=circuitcoordinate_buttons, permissions=['netbox_topology_views.view_coordinate']),
),
),
(_('Preferences'),
(
PluginMenuItem(link="plugins:netbox_topology_views:images", link_text=_("Images"), permissions=[ "dcim.view_site","dcim.view_devicerole"]),
PluginMenuItem(link="plugins:netbox_topology_views:individualoptions", link_text=_("Individual Options"), permissions=['netbox_topology_views.change_individualoptions']),
),
),
),
@@ -1 +1 @@
#visgraph{height:64vh}html[data-netbox-color-mode=dark] #visgraph{background-color:#212529}.image-dropdown img{width:64px;height:64px}.image-dropdown-content{display:flex;flex-wrap:wrap;gap:.5rem;padding-inline:.5rem;width:50vw;max-width:32rem}.image-dropdown-content>img{cursor:pointer}
#visgraph{height:64vh;border:1px solid #ced4da}html[data-netbox-color-mode=dark] #visgraph{background-color:#212529;border:1px solid #495057}.image-dropdown img{width:64px;height:64px}.image-dropdown-content{display:flex;flex-wrap:wrap;gap:.5rem;padding-inline:.5rem;width:50vw;max-width:32rem}.image-dropdown-content>img{cursor:pointer}.rack-elevation-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(34rem,1fr));gap:1rem}.rack-card{border:1px solid var(--tblr-border-color,#ced4da);border-radius:.4rem;background:var(--tblr-bg-surface,#fff);padding:1rem}.rack-card>header{display:flex;justify-content:space-between;margin-bottom:.75rem}.rack-faces{display:grid;grid-template-columns:1fr 1fr;gap:.75rem}.rack-face-title{text-align:center;font-size:.75rem;text-transform:uppercase;margin-bottom:.25rem}.rack-frame{display:flex;height:calc(var(--rack-units)*14px);min-height:280px;max-height:70vh;border:4px solid #3b4654;background:repeating-linear-gradient(to top,rgba(127,127,127,.14) 0,rgba(127,127,127,.14) 1px,transparent 1px,transparent calc(100%/var(--rack-units)))}.rack-unit-labels{width:2rem;display:flex;flex-direction:column;justify-content:space-around;font-size:.55rem;text-align:center;color:var(--tblr-secondary,#667382)}.rack-device-area{position:relative;flex:1;border-left:1px solid #3b4654}.rack-device{position:absolute;left:3px;right:3px;min-height:2px;overflow:hidden;padding:1px 5px;border:2px solid #1685fc;border-radius:3px;background:#162e45;color:#fff;line-height:1.1;text-decoration:none}.rack-device:hover{filter:brightness(1.25);color:#fff;z-index:2}.rack-device span,.rack-device small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.rack-device small{font-size:.6rem;opacity:.8}@media(max-width:700px){.rack-elevation-grid{grid-template-columns:1fr}.rack-faces{grid-template-columns:1fr}}
@@ -0,0 +1,159 @@
.rack-frame {
height: calc(var(--rack-units) * 22px);
max-height: none;
}
.rack-device {
padding: 2px 6px;
font-size: .78rem;
line-height: 1.15;
background: #eef6ff;
color: #132238;
}
.rack-device:hover {
min-height: 2.8rem;
overflow: visible;
z-index: 3;
}
.rack-device:hover span { white-space: normal; }
.rack-frame {
border-color: #718096;
background-color: #fff;
background-image: repeating-linear-gradient(to top, rgba(56, 73, 89, .16) 0, rgba(56, 73, 89, .16) 1px, transparent 1px, transparent calc(100% / var(--rack-units)));
}
.rack-device:hover { color: #132238; }
html[data-bs-theme="dark"] .rack-frame,
body[data-bs-theme="dark"] .rack-frame,
html[data-netbox-color-mode="dark"] .rack-frame {
border-color: #3b4654;
background-color: #212b36;
background-image: repeating-linear-gradient(to top, rgba(200, 215, 230, .14) 0, rgba(200, 215, 230, .14) 1px, transparent 1px, transparent calc(100% / var(--rack-units)));
}
html[data-bs-theme="dark"] .rack-device,
body[data-bs-theme="dark"] .rack-device,
html[data-netbox-color-mode="dark"] .rack-device {
background: #162e45;
color: #fff;
}
.rack-topology {
position: relative;
min-height: 18rem;
overflow: auto;
padding: 1rem;
background: var(--tblr-bg-surface-secondary, rgba(127, 127, 127, .05));
}
.rack-topology-lines {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 1;
}
.rack-topology-columns {
position: relative;
z-index: 2;
display: flex;
align-items: flex-start;
justify-content: space-around;
gap: 5rem;
min-width: max-content;
pointer-events: none;
}
.rack-topology-column {
display: flex;
flex-direction: column;
gap: .75rem;
width: 15rem;
}
.rack-topology-column h4 { text-align: center; font-size: .85rem; }
.rack-topology-device-list { display: flex; flex-direction: column; gap: 40px; }
.rack-topology-node {
display: block;
padding: .55rem .75rem;
border: 2px solid var(--node-color);
border-radius: .35rem;
background: var(--tblr-bg-surface, #fff);
color: inherit;
text-decoration: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, .12);
cursor: grab;
touch-action: none;
user-select: none;
pointer-events: auto;
}
.rack-topology-node.is-dragging { cursor: grabbing; z-index: 5; }
.rack-topology-node:hover { color: inherit; filter: brightness(.95); }
.rack-topology-node strong,
.rack-topology-node small {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rack-topology-node small { opacity: .7; }
.rack-topology-edge {
fill: none;
stroke-width: 3;
opacity: .8;
pointer-events: stroke;
cursor: pointer;
transition: opacity .12s, stroke .12s, filter .12s, stroke-width .12s;
}
.rack-topology-edge.is-highlighted {
stroke: var(--topology-highlight-color, #16a34a) !important;
stroke-width: 5;
opacity: 1;
filter: drop-shadow(0 0 5px var(--topology-highlight-color, #16a34a));
}
.rack-topology-edge.is-dimmed { opacity: .12; }
.rack-topology-edge.is-wireless {
stroke-dasharray: 7 7;
stroke-linecap: round;
}
.rack-topology-edge.is-power {
stroke-dasharray: 2 4;
stroke-linecap: round;
}
#rack-topology-card:fullscreen {
margin: 0 !important;
border: 0;
border-radius: 0;
background: var(--tblr-bg-surface, #fff);
display: flex;
flex-direction: column;
overflow: hidden;
}
#rack-topology-card:fullscreen .card-body { min-height: 0; flex: 1; overflow: hidden; }
#rack-topology-card:fullscreen .rack-topology { height: calc(100vh - 5.5rem); }
.rack-topology-tooltip {
display: none;
position: absolute;
z-index: 10;
width: max-content;
max-width: 28rem;
padding: .65rem .8rem;
border: 1px solid var(--tblr-border-color, #ced4da);
border-radius: .35rem;
background: var(--tblr-bg-surface, #fff);
box-shadow: 0 4px 18px rgba(0, 0, 0, .25);
pointer-events: none;
}
.rack-topology-tooltip.is-visible { display: block; }
.rack-topology-tooltip > strong,
.rack-topology-tooltip > span,
.rack-topology-tooltip li span,
.rack-topology-tooltip li small { display: block; }
.rack-topology-tooltip ul { margin: .4rem 0 0; padding: 0; list-style: none; }
.rack-topology-tooltip li + li {
margin-top: .45rem;
padding-top: .45rem;
border-top: 1px solid var(--tblr-border-color, #ced4da);
}
.rack-topology-tooltip small { opacity: .65; }
.rack-cable-count {
min-width: 2rem;
margin-left: .35rem;
background-color: #52606d !important;
color: #fff !important;
text-align: center;
}
@@ -1 +1 @@
.vis-overlay{bottom:0;left:0;position:absolute;right:0;top:0;z-index:10}.vis-active{box-shadow:0 0 10px #86d5f8}.vis [class*=span]{min-height:0;width:auto}div.vis-color-picker{background-color:#fff;border-radius:15px;box-shadow:0 0 10px #00000080;display:none;height:444px;left:30px;margin-left:30px;margin-top:-140px;padding:10px;position:absolute;top:0;width:310px;z-index:1}div.vis-color-picker div.vis-arrow{left:5px;position:absolute;top:147px}div.vis-color-picker div.vis-arrow:after,div.vis-color-picker div.vis-arrow:before{border:solid transparent;content:" ";height:0;pointer-events:none;position:absolute;right:100%;top:50%;width:0}div.vis-color-picker div.vis-arrow:after{border-color:hsla(0,0%,100%,0) #fff hsla(0,0%,100%,0) hsla(0,0%,100%,0);border-width:30px;margin-top:-30px}div.vis-color-picker div.vis-color{cursor:pointer;height:289px;position:absolute;width:289px}div.vis-color-picker div.vis-brightness{position:absolute;top:313px}div.vis-color-picker div.vis-opacity{position:absolute;top:350px}div.vis-color-picker div.vis-selector{background:#4c4c4c;background:-moz-linear-gradient(top,#4c4c4c 0,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313 100%);background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#4c4c4c),color-stop(12%,#595959),color-stop(25%,#666),color-stop(39%,#474747),color-stop(50%,#2c2c2c),color-stop(51%,#000),color-stop(60%,#111),color-stop(76%,#2b2b2b),color-stop(91%,#1c1c1c),color-stop(100%,#131313));background:-webkit-linear-gradient(top,#4c4c4c,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313);background:-o-linear-gradient(top,#4c4c4c 0,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313 100%);background:-ms-linear-gradient(top,#4c4c4c 0,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313 100%);background:linear-gradient(180deg,#4c4c4c 0,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313);border:1px solid #fff;border-radius:15px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#4c4c4c",endColorstr="#131313",GradientType=0);height:15px;left:137px;position:absolute;top:137px;width:15px}div.vis-color-picker div.vis-new-color{left:159px;padding-right:2px;text-align:right}div.vis-color-picker div.vis-initial-color,div.vis-color-picker div.vis-new-color{border:1px solid rgba(0,0,0,.1);border-radius:5px;color:#0006;font-size:10px;height:20px;line-height:20px;position:absolute;top:380px;vertical-align:middle;width:140px}div.vis-color-picker div.vis-initial-color{left:10px;padding-left:2px;text-align:left}div.vis-color-picker div.vis-label{left:10px;position:absolute;width:300px}div.vis-color-picker div.vis-label.vis-brightness{top:300px}div.vis-color-picker div.vis-label.vis-opacity{top:338px}div.vis-color-picker div.vis-button{background-color:#f7f7f7;border:2px solid #d9d9d9;border-radius:10px;cursor:pointer;height:25px;line-height:25px;position:absolute;text-align:center;top:410px;vertical-align:middle;width:68px}div.vis-color-picker div.vis-button.vis-cancel{left:5px}div.vis-color-picker div.vis-button.vis-load{left:82px}div.vis-color-picker div.vis-button.vis-apply{left:159px}div.vis-color-picker div.vis-button.vis-save{left:236px}div.vis-color-picker input.vis-range{height:20px;width:290px}div.vis-configuration{display:block;float:left;font-size:12px;position:relative}div.vis-configuration-wrapper{display:block;width:700px}div.vis-configuration-wrapper:after{clear:both;content:"";display:block}div.vis-configuration.vis-config-option-container{background-color:#fff;border:2px solid #f7f8fa;border-radius:4px;display:block;left:10px;margin-top:20px;padding-left:5px;width:495px}div.vis-configuration.vis-config-button{background-color:#f7f8fa;border:2px solid #ceced0;border-radius:4px;cursor:pointer;display:block;height:25px;left:10px;line-height:25px;margin-bottom:30px;margin-top:20px;padding-left:5px;vertical-align:middle;width:495px}div.vis-configuration.vis-config-button.hover{background-color:#4588e6;border:2px solid #214373;color:#fff}div.vis-configuration.vis-config-item{display:block;float:left;height:25px;line-height:25px;vertical-align:middle;width:495px}div.vis-configuration.vis-config-item.vis-config-s2{background-color:#f7f8fa;border-radius:3px;left:10px;padding-left:5px}div.vis-configuration.vis-config-item.vis-config-s3{background-color:#e4e9f0;border-radius:3px;left:20px;padding-left:5px}div.vis-configuration.vis-config-item.vis-config-s4{background-color:#cfd8e6;border-radius:3px;left:30px;padding-left:5px}div.vis-configuration.vis-config-header{font-size:18px;font-weight:700}div.vis-configuration.vis-config-label{height:25px;line-height:25px;width:120px}div.vis-configuration.vis-config-label.vis-config-s3{width:110px}div.vis-configuration.vis-config-label.vis-config-s4{width:100px}div.vis-configuration.vis-config-colorBlocLine truncated
.vis-overlay{inset:0;position:absolute;z-index:10}.vis-active{box-shadow:0 0 10px #86d5f8}.vis [class*=span]{min-height:0;width:auto}div.vis-color-picker{background-color:#fff;border-radius:15px;box-shadow:0 0 10px #00000080;display:none;height:444px;left:30px;margin-left:30px;margin-top:-140px;padding:10px;position:absolute;top:0;width:310px;z-index:1}div.vis-color-picker div.vis-arrow{left:5px;position:absolute;top:147px}div.vis-color-picker div.vis-arrow:after,div.vis-color-picker div.vis-arrow:before{border:solid transparent;content:" ";height:0;pointer-events:none;position:absolute;right:100%;top:50%;width:0}div.vis-color-picker div.vis-arrow:after{border-color:hsla(0,0%,100%,0) #fff hsla(0,0%,100%,0) hsla(0,0%,100%,0);border-width:30px;margin-top:-30px}div.vis-color-picker div.vis-color{cursor:pointer;height:289px;position:absolute;width:289px}div.vis-color-picker div.vis-brightness{position:absolute;top:313px}div.vis-color-picker div.vis-opacity{position:absolute;top:350px}div.vis-color-picker div.vis-selector{background:#4c4c4c;background:-moz-linear-gradient(top,#4c4c4c 0,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313 100%);background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#4c4c4c),color-stop(12%,#595959),color-stop(25%,#666),color-stop(39%,#474747),color-stop(50%,#2c2c2c),color-stop(51%,#000),color-stop(60%,#111),color-stop(76%,#2b2b2b),color-stop(91%,#1c1c1c),color-stop(100%,#131313));background:-webkit-linear-gradient(top,#4c4c4c,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313);background:-o-linear-gradient(top,#4c4c4c 0,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313 100%);background:-ms-linear-gradient(top,#4c4c4c 0,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313 100%);background:linear-gradient(180deg,#4c4c4c 0,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313);border:1px solid #fff;border-radius:15px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#4c4c4c",endColorstr="#131313",GradientType=0);height:15px;left:137px;position:absolute;top:137px;width:15px}div.vis-color-picker div.vis-new-color{left:159px;padding-right:2px;text-align:right}div.vis-color-picker div.vis-initial-color,div.vis-color-picker div.vis-new-color{border:1px solid rgba(0,0,0,.1);border-radius:5px;color:#0006;font-size:10px;height:20px;line-height:20px;position:absolute;top:380px;vertical-align:middle;width:140px}div.vis-color-picker div.vis-initial-color{left:10px;padding-left:2px;text-align:left}div.vis-color-picker div.vis-label{left:10px;position:absolute;width:300px}div.vis-color-picker div.vis-label.vis-brightness{top:300px}div.vis-color-picker div.vis-label.vis-opacity{top:338px}div.vis-color-picker div.vis-button{background-color:#f7f7f7;border:2px solid #d9d9d9;border-radius:10px;cursor:pointer;height:25px;line-height:25px;position:absolute;text-align:center;top:410px;vertical-align:middle;width:68px}div.vis-color-picker div.vis-button.vis-cancel{left:5px}div.vis-color-picker div.vis-button.vis-load{left:82px}div.vis-color-picker div.vis-button.vis-apply{left:159px}div.vis-color-picker div.vis-button.vis-save{left:236px}div.vis-color-picker input.vis-range{height:20px;width:290px}div.vis-configuration{display:block;float:left;font-size:12px;position:relative}div.vis-configuration-wrapper{display:block;width:700px}div.vis-configuration-wrapper:after{clear:both;content:"";display:block}div.vis-configuration.vis-config-option-container{background-color:#fff;border:2px solid #f7f8fa;border-radius:4px;display:block;left:10px;margin-top:20px;padding-left:5px;width:495px}div.vis-configuration.vis-config-button{background-color:#f7f8fa;border:2px solid #ceced0;border-radius:4px;cursor:pointer;display:block;height:25px;left:10px;line-height:25px;margin-bottom:30px;margin-top:20px;padding-left:5px;vertical-align:middle;width:495px}div.vis-configuration.vis-config-button.hover{background-color:#4588e6;border:2px solid #214373;color:#fff}div.vis-configuration.vis-config-item{display:block;float:left;height:25px;line-height:25px;vertical-align:middle;width:495px}div.vis-configuration.vis-config-item.vis-config-s2{background-color:#f7f8fa;border-radius:3px;left:10px;padding-left:5px}div.vis-configuration.vis-config-item.vis-config-s3{background-color:#e4e9f0;border-radius:3px;left:20px;padding-left:5px}div.vis-configuration.vis-config-item.vis-config-s4{background-color:#cfd8e6;border-radius:3px;left:30px;padding-left:5px}div.vis-configuration.vis-config-header{font-size:18px;font-weight:700}div.vis-configuration.vis-config-label{height:25px;line-height:25px;width:120px}div.vis-configuration.vis-config-label.vis-config-s3{width:110px}div.vis-configuration.vis-config-label.vis-config-s4{width:100px}div.vis-configuration.vis-config-colorBlock{border:1px solid #44Line truncated
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><circle cx="64" cy="64" r="59" fill="#fff4e5" stroke="#e58a16" stroke-width="6"/><rect x="20" y="48" width="88" height="42" rx="7" fill="#513717"/><g fill="#ffc66f"><path d="M28 58h10v8H28zm14 0h10v8H42zm14 0h10v8H56zm14 0h10v8H70zm14 0h16v8H84zM28 71h10v8H28zm14 0h10v8H42zm14 0h10v8H56zm14 0h10v8H70zm14 0h16v8H84z"/></g><path d="M34 27h25m10 0h25M59 27l10 0M64 27v17" fill="none" stroke="#e58a16" stroke-width="7" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 510 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><circle cx="64" cy="64" r="59" fill="#eafff4" stroke="#20a86b" stroke-width="6"/><rect x="20" y="49" width="88" height="39" rx="7" fill="#174637"/><g fill="#8cf0bf"><path d="M29 59h9v7h-9zm13 0h9v7h-9zm13 0h9v7h-9zm13 0h9v7h-9zm13 0h9v7h-9zm13 0h6v7h-6zM29 70h9v7h-9zm13 0h9v7h-9zm13 0h9v7h-9zm13 0h9v7h-9zm13 0h9v7h-9zm13 0h6v7h-6z"/></g><path d="M64 20c-14 8-22 17-22 27 14 1 23-5 26-19 7 9 12 15 20 18-1-12-9-21-24-26z" fill="#20a86b"/></svg>

After

Width:  |  Height:  |  Size: 508 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><circle cx="64" cy="64" r="59" fill="#e8f4ff" stroke="#1685fc" stroke-width="6"/><rect x="22" y="42" width="84" height="45" rx="7" fill="#183a5a"/><path d="M28 52h72v25H28z" fill="#10283e"/><g fill="#52d273"><circle cx="34" cy="64" r="3"/><circle cx="43" cy="64" r="3"/></g><g fill="#8fc8ff"><path d="M55 55h10v7H55zm14 0h10v7H69zm14 0h10v7H83zM55 67h10v7H55zm14 0h10v7H69zm14 0h10v7H83z"/></g><path d="m35 33 9-8v6h40v-6l9 8-9 8v-6H44v6z" fill="#1685fc"/></svg>

After

Width:  |  Height:  |  Size: 525 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><circle cx="64" cy="64" r="59" fill="#f2ecff" stroke="#7654d6" stroke-width="6"/><rect x="20" y="48" width="88" height="42" rx="7" fill="#302657"/><g fill="#bca9ff"><path d="M28 58h9v8h-9zm13 0h9v8h-9zm13 0h9v8h-9zm13 0h9v8h-9zm13 0h9v8h-9zm13 0h7v8h-7zM28 71h9v8h-9zm13 0h9v8h-9zm13 0h9v8h-9zm13 0h9v8h-9zm13 0h9v8h-9zm13 0h7v8h-7z"/></g><path d="M64 45V20M64 25 44 39M64 25l20 14" fill="none" stroke="#7654d6" stroke-width="7" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 522 B

@@ -1,104 +1,114 @@
(()=>{var In=Object.create;var kt=Object.defineProperty,Pn=Object.defineProperties,Mn=Object.getOwnPropertyDescriptor,Dn=Object.getOwnPropertyDescriptors,Fn=Object.getOwnPropertyNames,Ui=Object.getOwnPropertySymbols,Nn=Object.getPrototypeOf,Yi=Object.prototype.hasOwnProperty,Bn=Object.prototype.propertyIsEnumerable;var Jt=(n,e,t)=>e in n?kt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,de=(n,e)=>{for(var t in e||(e={}))Yi.call(e,t)&&Jt(n,t,e[t]);if(Ui)for(var t of Ui(e))Bn.call(e,t)&&Jt(n,t,e[t]);return n},Be=(n,e)=>Pn(n,Dn(e)),An=n=>kt(n,"__esModule",{value:!0});var ei=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var zn=(n,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fn(e))!Yi.call(n,i)&&i!=="default"&&kt(n,i,{get:()=>e[i],enumerable:!(t=Mn(e,i))||t.enumerable});return n},ti=n=>zn(An(kt(n!=null?In(Nn(n)):{},"default",n&&n.__esModule&&"default"in n?{get:()=>n.default,enumerable:!0}:{value:n,enumerable:!0})),n);var $=(n,e,t)=>(Jt(n,typeof e!="symbol"?e+"":e,t),t);var Xi=(n,e,t)=>new Promise((i,s)=>{var o=d=>{try{a(t.next(d))}catch(h){s(h)}},r=d=>{try{a(t.throw(d))}catch(h){s(h)}},a=d=>d.done?i(d.value):Promise.resolve(d.value).then(o,r);a((t=t.apply(n,e)).next())});var si=ei((Va,ii)=>{typeof ii!="undefined"&&(ii.exports=ne);function ne(n){if(n)return Ln(n)}function Ln(n){for(var e in ne.prototype)n[e]=ne.prototype[e];return n}ne.prototype.on=ne.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};ne.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};ne.prototype.off=ne.prototype.removeListener=ne.prototype.removeAllListeners=ne.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var i,s=0;s<t.length;s++)if(i=t[s],i===e||i.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+n],this};ne.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(t){t=t.slice(0);for(var i=0,s=t.length;i<s;++i)t[i].apply(this,e)}return this};ne.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};ne.prototype.hasListeners=function(n){return!!this.listeners(n).length}});var io=ei(Ut=>{(function(n,e){if(typeof define=="function"&&define.amd)define("timsort",["exports"],e);else if(typeof Ut!="undefined")e(Ut);else{var t={exports:{}};e(t.exports),n.timsort=t.exports}})(Ut,function(n){"use strict";n.__esModule=!0,n.sort=C;function e(f,g){if(!(f instanceof g))throw new TypeError("Cannot call a class as a function")}var t=32,i=7,s=256,o=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9];function r(f){return f<1e5?f<100?f<10?0:1:f<1e4?f<1e3?2:3:4:f<1e7?f<1e6?5:6:f<1e9?f<1e8?7:8:9}function a(f,g){if(f===g)return 0;if(~~f===f&&~~g===g){if(f===0||g===0)return f<g?-1:1;if(f<0||g<0){if(g>=0)return-1;if(f>=0)return 1;f=-f,g=-g}var m=r(f),v=r(g),_=0;return m<v?(f*=o[v-m-1],g/=10,_=-1):m>v&&(g*=o[m-v-1],f/=10,_=1),f===g?_:f<g?-1:1}var E=String(f),T=String(g);return E===T?0:E<T?-1:1}function d(f){for(var g=0;f>=t;)g|=f&1,f>>=1;return f+g}function h(f,g,m,v){var _=g+1;if(_===m)return 1;if(v(f[_++],f[g])<0){for(;_<m&&v(f[_],f[_-1])<0;)_++;l(f,g,_)}else for(;_<m&&v(f[_],f[_-1])>=0;)_++;return _-g}function l(f,g,m){for(m--;g<m;){var v=f[g];f[g++]=f[m],f[m--]=v}}function c(f,g,m,v,_){for(v===g&&v++;v<m;v++){for(var E=f[v],T=g,x=v;T<x;){var w=T+x>>>1;_(E,f[w])<0?x=w:T=w+1}var k=v-T;switch(k){case 3:f[T+3]=f[T+2];case 2:f[T+2]=f[T+1];case 1:f[T+1]=f[T];break;default:for(;k>0;)f[T+k]=f[T+k-1],k--}f[T]=E}}function u(f,g,m,v,_,E){var T=0,x=0,w=1;if(E(f,g[m+_])>0){for(x=v-_;w<x&&E(f,g[m+_+w])>0;)T=w,w=(w<<1)+1,w<=0&&(w=x);w>x&&(w=x),T+=_,w+=_}else{for(x=_+1;w<x&&E(f,g[m+_-w])<=0;)T=w,w=(w<<1)+1,w<=0&&(w=x);w>x&&(w=x);var k=T;T=_-w,w=_-k}for(T++;T<w;){var N=T+(w-T>>>1);E(f,g[m+N])>0?T=N+1:w=N}return w}function p(f,g,m,v,_,E){var T=0,x=0,w=1;if(E(f,g[m+_])<0){for(x=_+1;w<x&&E(f,g[m+_-w])<0;)T=w,w=(w<<1)+1,w<=0&&(w=x);w>x&&(w=x);var k=T;T=_-w,w=_-k}else{for(x=v-_;w<x&&E(f,g[m+_+w])>=0;)T=w,w=(w<<1)+1,w<=0&&(w=x);w>x&&(w=x),T+=_,w+=_}for(T++;T<w;){var N=T+(w-T>>>1);E(f,g[m+N])<0?w=N:T=N+1}return w}var b=function(){function f(g,m){e(this,f),this.array=null,this.compare=null,this.minGallop=i,this.length=0,this.tmpStorageLength=s,this.stackLength=0,this.runStart=null,this.runLength=null,this.stackSize=0,this.array=g,this.compare=m,this.length=g.length,this.length<2*s&&(this.tmpStorageLength=this.length>>>1),this.tmp=new Array(this.tmpStorageLength),this.stackLength=this.length<120?5:this.length<1542?10:this.length<119151?19:40,this.runStart=new Array(this.stackLength),this.runLength=neLine truncated
(()=>{var Cn=Object.create;var ci=Object.defineProperty,kn=Object.defineProperties,On=Object.getOwnPropertyDescriptor,Sn=Object.getOwnPropertyDescriptors,In=Object.getOwnPropertyNames,Vs=Object.getOwnPropertySymbols,Pn=Object.getPrototypeOf,qs=Object.prototype.hasOwnProperty,Mn=Object.prototype.propertyIsEnumerable;var li=(r,e,t)=>e in r?ci(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ge=(r,e)=>{for(var t in e||(e={}))qs.call(e,t)&&li(r,t,e[t]);if(Vs)for(var t of Vs(e))Mn.call(e,t)&&li(r,t,e[t]);return r},je=(r,e)=>kn(r,Sn(e));var Dn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Nn=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of In(e))!qs.call(r,o)&&o!==t&&ci(r,o,{get:()=>e[o],enumerable:!(s=On(e,o))||s.enumerable});return r};var Ys=(r,e,t)=>(t=r!=null?Cn(Pn(r)):{},Nn(e||!r||!r.__esModule?ci(t,"default",{value:r,enumerable:!0}):t,r));var se=(r,e,t)=>li(r,typeof e!="symbol"?e+"":e,t);var Xs=(r,e,t)=>new Promise((s,o)=>{var n=h=>{try{d(t.next(h))}catch(l){o(l)}},a=h=>{try{d(t.throw(h))}catch(l){o(l)}},d=h=>h.done?s(h.value):Promise.resolve(h.value).then(n,a);d((t=t.apply(r,e)).next())});var fi=Dn((Wa,ui)=>{typeof ui!="undefined"&&(ui.exports=ce);function ce(r){if(r)return Fn(r)}function Fn(r){for(var e in ce.prototype)r[e]=ce.prototype[e];return r}ce.prototype.on=ce.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};ce.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};ce.prototype.off=ce.prototype.removeListener=ce.prototype.removeAllListeners=ce.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var s,o=0;o<t.length;o++)if(s=t[o],s===e||s.fn===e){t.splice(o,1);break}return t.length===0&&delete this._callbacks["$"+r],this};ce.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(t){t=t.slice(0);for(var s=0,o=t.length;s<o;++s)t[s].apply(this,e)}return this};ce.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};ce.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var Do=Ys(fi());function ve(){return ve=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(r[s]=t[s])}return r},ve.apply(this,arguments)}function ye(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,r.__proto__=e}function Pt(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}var pi;typeof Object.assign!="function"?pi=function(e){if(e==null)throw new TypeError("Cannot convert undefined or null to object");for(var t=Object(e),s=1;s<arguments.length;s++){var o=arguments[s];if(o!=null)for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])}return t}:pi=Object.assign;var Ye=pi,Us=["","webkit","Moz","MS","ms","o"],Bn=typeof document=="undefined"?{style:{}}:document.createElement("div"),An="function",Je=Math.round,Xe=Math.abs,bi=Date.now;function zt(r,e){for(var t,s,o=e[0].toUpperCase()+e.slice(1),n=0;n<Us.length;){if(t=Us[n],s=t?t+o:e,s in r)return s;n++}}var ke;typeof window=="undefined"?ke={}:ke=window;var oo=zt(Bn.style,"touchAction"),no=oo!==void 0;function zn(){if(!no)return!1;var r={},e=ke.CSS&&ke.CSS.supports;return["auto","manipulation","pan-y","pan-x","pan-x pan-y","none"].forEach(function(t){return r[t]=e?ke.CSS.supports("touch-action",t):!0}),r}var ro="compute",ao="auto",gi="manipulation",Ve="none",ct="pan-x",ut="pan-y",Mt=zn(),Rn=/mobile|tablet|ip(ad|hone|od)|android/i,ho="ontouchstart"in ke,Ln=zt(ke,"PointerEvent")!==void 0,Hn=ho&&Rn.test(navigator.userAgent),mt="touch",jn="pen",vi="mouse",Wn="kinect",Vn=25,oe=1,Ge=2,Q=4,de=8,Ft=1,yt=2,bt=4,vt=8,tt=16,Ee=yt|bt,qe=vt|tt,lo=Ee|qe,co=["x","y"],Bt=["clientX","clientY"];function Oe(r,e,t){var s;if(r)if(r.forEach)r.forEach(e,t);else if(r.length!==void 0)for(s=0;s<r.length;)e.call(t,r[s],s,r),s++;else for(s in r)r.hasOwnProperty(s)&&e.call(t,r[s],s,r)}function Rt(r,e){return typeof r===An?r.apply(e&&e[0]||void 0,e):r}function We(r,e){return r.indexOf(e)>-1}function qn(r){if(We(r,Ve))return Ve;var e=We(r,ct),t=We(r,ut);return e&&t?Ve:e||t?e?ct:ut:We(r,gi)?gi:ao}var uo=function(){function r(t,s){this.manager=t,this.set(s)}var e=r.prototype;return e.set=function(s){s===ro&&(s=this.compute()),no&&this.manager.element.style&&Mt[s]&&(this.manager.element.style[oo]=s),this.actions=s.toLowerCase().trim()},e.update=function(){this.set(this.manager.options.touchAction)},e.compute=function(){var s=[];return Oe(this.manager.recognizers,function(o){RtLine truncated
`+t+` AT
`;return function(){var s=new Error("get-stack-trace"),o=s&&s.stack?s.stack.replace(/^[^\(]+?[\n$]/gm,"").replace(/^\s+at\s+/gm,"").replace(/^Object.<anonymous>\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",r=window.console&&(window.console.warn||window.console.log);return r&&r.call(window.console,i,o),n.apply(this,arguments)}}var ks=Ts(function(n,e,t){for(var i=Object.keys(e),s=0;s<i.length;)(!t||t&&n[i[s]]===void 0)&&(n[i[s]]=e[i[s]]),s++;return n},"extend","Use `assign`."),Er=Ts(function(n,e){return ks(n,e,!0)},"merge","Use `assign`.");function xr(n,e,t){var i=e.prototype,s;s=n.prototype=Object.create(i),s.constructor=n,s._super=i,t&&Ae(s,t)}function Ss(n,e){return function(){return n.apply(e,arguments)}}var Os=function(){var n=function(t,i){return i===void 0&&(i={}),new Cs(t,fe({recognizers:_s.concat()},i))};return n.VERSION="2.0.17-rc",n.DIRECTION_ALL=es,n.DIRECTION_DOWN=Qe,n.DIRECTION_LEFT=dt,n.DIRECTION_RIGHT=ht,n.DIRECTION_UP=lt,n.DIRECTION_HORIZONTAL=pe,n.DIRECTION_VERTICAL=He,n.DIRECTION_NONE=Pt,n.DIRECTION_DOWN=Qe,n.INPUT_START=ee,n.INPUT_MOVE=Re,n.INPUT_END=K,n.INPUT_CANCEL=se,n.STATE_POSSIBLE=Nt,n.STATE_BEGAN=le,n.STATE_CHANGED=et,n.STATE_ENDED=Oe,n.STATE_RECOGNIZED=ve,n.STATE_CANCELLED=gt,n.STATE_FAILED=ge,n.Manager=Cs,n.Input=$e,n.TouchAction=is,n.TouchInput=ci,n.MouseInput=ui,n.PointerEventInput=ls,n.TouchMouseInput=fs,n.SingleTouchInput=wr,n.Recognizer=mt,n.AttrRecognizer=tt,n.Tap=fi,n.Pan=pi,n.Swipe=ms,n.Pinch=ys,n.Rotate=bs,n.Press=vs,n.on=ut,n.off=ft,n.each=be,n.merge=Er,n.extend=ks,n.bindFn=Ss,n.assign=Ae,n.inherit=xr,n.bindFn=Ss,n.prefixed=Ot,n.toArray=pt,n.inArray=We,n.uniqueArray=li,n.splitStr=ct,n.boolOrFn=Dt,n.hasParent=di,n.addEventListeners=ut,n.removeEventListeners=ft,n.defaults=Ae({},ws,{preset:_s}),n}(),qa=Os.defaults,Is=Os;var gi=Symbol("DELETE");function Ms(n,...e){return Ds({},n,...e)}function Ds(...n){let e=At(...n);return Ns(e),e}function At(...n){if(n.length<2)return n[0];if(n.length>2)return At(Ds(n[0],n[1]),...n.slice(2));let e=n[0],t=n[1];for(let i of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,i)&&(t[i]===gi?delete e[i]:e[i]!==null&&t[i]!==null&&typeof e[i]=="object"&&typeof t[i]=="object"&&!Array.isArray(e[i])&&!Array.isArray(t[i])?e[i]=At(e[i],t[i]):e[i]=Fs(t[i]));return e}function Fs(n){return Array.isArray(n)?n.map(e=>Fs(e)):typeof n=="object"&&n!==null?At({},n):n}function Ns(n){for(let e of Object.keys(n))n[e]===gi?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&Ns(n[e])}function yt(...n){return Cr(n.length?n:[Date.now()])}function Cr(n){let[e,t,i]=Tr(n),s=1,o=()=>{let r=2091639*e+s*23283064365386963e-26;return e=t,t=i,i=r-(s=r|0)};return o.uint32=()=>o()*4294967296,o.fract53=()=>o()+(o()*2097152|0)*11102230246251565e-32,o.algorithm="Alea",o.seed=n,o.version="0.9",o}function Tr(...n){let e=kr(),t=e(" "),i=e(" "),s=e(" ");for(let o=0;o<n.length;o++)t-=e(n[o]),t<0&&(t+=1),i-=e(n[o]),i<0&&(i+=1),s-=e(n[o]),s<0&&(s+=1);return[t,i,s]}function kr(){let n=4022871197;return function(e){let t=e.toString();for(let i=0;i<t.length;i++){n+=t.charCodeAt(i);let s=.02519603282416938*n;n=s>>>0,s-=n,s*=n,n=s>>>0,s-=n,n+=s*4294967296}return(n>>>0)*23283064365386963e-26}}function Sr(){let n=()=>{};return{on:n,off:n,destroy:n,emit:n,get(){return{set:n}}}}var mi=typeof window!="undefined"?window.Hammer||Is:function(){return Sr()};function me(n){this._cleanupQueue=[],this.active=!1,this._dom={container:n,overlay:document.createElement("div")},this._dom.overlay.classList.add("vis-overlay"),this._dom.container.appendChild(this._dom.overlay),this._cleanupQueue.push(()=>{this._dom.overlay.parentNode.removeChild(this._dom.overlay)});let e=mi(this._dom.overlay);e.on("tap",this._onTapOverlay.bind(this)),this._cleanupQueue.push(()=>{e.destroy()}),["tap","doubletap","press","pinch","pan","panstart","panmove","panend"].forEach(i=>{e.on(i,s=>{s.srcEvent.stopPropagation()})}),document&&document.body&&(this._onClick=i=>{Or(i.target,n)||this.deactivate()},document.body.addEventListener("click",this._onClick),this._cleanupQueue.push(()=>{document.body.removeEventListener("click",this._onClick)})),this._escListener=i=>{("key"in i?i.key==="Escape":i.keyCode===27)&&this.deactivate()}}(0,Ps.default)(me.prototype);me.current=null;me.prototype.destroy=function(){this.deactivate();for(let n of this._cleanupQueue.splice(0).reverse())n()};me.prototype.activate=function(){me.current&&me.current.deactivate(),me.current=this,this.active=!0,this._dom.overlay.style.display="none",this._dom.container.classList.add("vis-active"),this.emit("change"),this.emit("activate"),document.body.addEventListener("keydown",this._escListener)};me.prototype.deactivate=function(){this.active=!1,this._dom.overlay.style.display="block",this._dom.container.classList.remove("vis-active"),document.body.removeEventListener("keydown",this._escListener),this.emit("change"),this.emit("deactivate")};me.prototype._onTapOverlay=function(n){this.activate(),n.srcEvent.stopPropagation()};function Or(n,e){for(;n;){if(n===e) Line truncated
`;return function(){var o=new Error("get-stack-trace"),n=o&&o.stack?o.stack.replace(/^[^\(]+?[\n$]/gm,"").replace(/^\s+at\s+/gm,"").replace(/^Object.<anonymous>\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",a=window.console&&(window.console.warn||window.console.log);return a&&a.call(window.console,s,n),r.apply(this,arguments)}}var Oo=ko(function(r,e,t){for(var s=Object.keys(e),o=0;o<s.length;)(!t||t&&r[s[o]]===void 0)&&(r[s[o]]=e[s[o]]),o++;return r},"extend","Use `assign`."),br=ko(function(r,e){return Oo(r,e,!0)},"merge","Use `assign`.");function vr(r,e,t){var s=e.prototype,o;o=r.prototype=Object.create(s),o.constructor=r,o._super=s,t&&Ye(o,t)}function so(r,e){return function(){return r.apply(e,arguments)}}var So=function(){var r=function(t,s){return s===void 0&&(s={}),new io(t,ve({recognizers:Js.concat()},s))};return r.VERSION="2.0.17-rc",r.DIRECTION_ALL=lo,r.DIRECTION_DOWN=tt,r.DIRECTION_LEFT=yt,r.DIRECTION_RIGHT=bt,r.DIRECTION_UP=vt,r.DIRECTION_HORIZONTAL=Ee,r.DIRECTION_VERTICAL=qe,r.DIRECTION_NONE=Ft,r.DIRECTION_DOWN=tt,r.INPUT_START=oe,r.INPUT_MOVE=Ge,r.INPUT_END=Q,r.INPUT_CANCEL=de,r.STATE_POSSIBLE=Nt,r.STATE_BEGAN=me,r.STATE_CHANGED=it,r.STATE_ENDED=Be,r.STATE_RECOGNIZED=Se,r.STATE_CANCELLED=gt,r.STATE_FAILED=_e,r.Manager=io,r.Input=ot,r.TouchAction=uo,r.TouchInput=Ei,r.MouseInput=xi,r.PointerEventInput=bo,r.TouchMouseInput=vo,r.SingleTouchInput=mr,r.Recognizer=wt,r.AttrRecognizer=st,r.Tap=yi,r.Pan=Ti,r.Swipe=_o,r.Pinch=Eo,r.Rotate=xo,r.Press=To,r.on=ht,r.off=lt,r.each=Oe,r.merge=br,r.extend=Oo,r.bindFn=so,r.assign=Ye,r.inherit=vr,r.bindFn=so,r.prefixed=zt,r.toArray=pt,r.inArray=Ue,r.uniqueArray=_i,r.splitStr=ft,r.boolOrFn=Rt,r.hasParent=wi,r.addEventListeners=ht,r.removeEventListeners=lt,r.defaults=Ye({},Co,{preset:Js}),r}(),Va=So.defaults,Io=So;var Oi=Symbol("DELETE");function No(r,...e){return Fo({},r,...e)}function Fo(...r){let e=Ht(...r);return Ao(e),e}function Ht(...r){if(r.length<2)return r[0];if(r.length>2)return Ht(Fo(r[0],r[1]),...r.slice(2));let e=r[0],t=r[1];if(e instanceof Date&&t instanceof Date)return e.setTime(t.getTime()),e;for(let s of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,s)&&(t[s]===Oi?delete e[s]:e[s]!==null&&t[s]!==null&&typeof e[s]=="object"&&typeof t[s]=="object"&&!Array.isArray(e[s])&&!Array.isArray(t[s])?e[s]=Ht(e[s],t[s]):e[s]=Bo(t[s]));return e}function Bo(r){return Array.isArray(r)?r.map(e=>Bo(e)):typeof r=="object"&&r!==null?r instanceof Date?new Date(r.getTime()):Ht({},r):r}function Ao(r){for(let e of Object.keys(r))r[e]===Oi?delete r[e]:typeof r[e]=="object"&&r[e]!==null&&Ao(r[e])}function xt(...r){return wr(r.length?r:[Date.now()])}function wr(r){let[e,t,s]=_r(r),o=1,n=()=>{let a=2091639*e+o*23283064365386963e-26;return e=t,t=s,s=a-(o=a|0)};return n.uint32=()=>n()*4294967296,n.fract53=()=>n()+(n()*2097152|0)*11102230246251565e-32,n.algorithm="Alea",n.seed=r,n.version="0.9",n}function _r(...r){let e=Er(),t=e(" "),s=e(" "),o=e(" ");for(let n=0;n<r.length;n++)t-=e(r[n]),t<0&&(t+=1),s-=e(r[n]),s<0&&(s+=1),o-=e(r[n]),o<0&&(o+=1);return[t,s,o]}function Er(){let r=4022871197;return function(e){let t=e.toString();for(let s=0;s<t.length;s++){r+=t.charCodeAt(s);let o=.02519603282416938*r;r=o>>>0,o-=r,o*=r,r=o>>>0,o-=r,r+=o*4294967296}return(r>>>0)*23283064365386963e-26}}function xr(){let r=()=>{};return{on:r,off:r,destroy:r,emit:r,get(){return{set:r}}}}var Si=typeof window!="undefined"?window.Hammer||Io:function(){return xr()};function xe(r){this._cleanupQueue=[],this.active=!1,this._dom={container:r,overlay:document.createElement("div")},this._dom.overlay.classList.add("vis-overlay"),this._dom.container.appendChild(this._dom.overlay),this._cleanupQueue.push(()=>{this._dom.overlay.parentNode.removeChild(this._dom.overlay)});let e=Si(this._dom.overlay);e.on("tap",this._onTapOverlay.bind(this)),this._cleanupQueue.push(()=>{e.destroy()}),["tap","doubletap","press","pinch","pan","panstart","panmove","panend"].forEach(s=>{e.on(s,o=>{o.srcEvent.stopPropagation()})}),document&&document.body&&(this._onClick=s=>{Tr(s.target,r)||this.deactivate()},document.body.addEventListener("click",this._onClick),this._cleanupQueue.push(()=>{document.body.removeEventListener("click",this._onClick)})),this._escListener=s=>{("key"in s?s.key==="Escape":s.keyCode===27)&&this.deactivate()}}(0,Do.default)(xe.prototype);xe.current=null;xe.prototype.destroy=function(){this.deactivate();for(let r of this._cleanupQueue.splice(0).reverse())r()};xe.prototype.activate=function(){xe.current&&xe.current.deactivate(),xe.current=this,this.active=!0,this._dom.overlay.style.display="none",this._dom.container.classList.add("vis-active"),this.emit("change"),this.emit("activate"),document.body.addEventListener("keydown",this._escListener)};xe.prototype.deactivate=function(){this.active=!1,this._dom.overlay.style.display="block",this._dom.container.classList.remove("vis-active"),document.body.removeEventListener("keydown",this._escListener),this.emit("change"),this.emit("deactivate")};xe.proto Line truncated
`:o.distance<=a&&s.distance>o.distance?d=" in "+X.printLocation(s.path,e,"")+"Perhaps it was misplaced? Matching option found at: "+X.printLocation(o.path,o.closestMatch,""):s.distance<=r?d='. Did you mean "'+s.closestMatch+'"?'+X.printLocation(s.path,e):d=". Did you mean one of these: "+X.print(Object.keys(t))+X.printLocation(i,e),console.error('%cUnknown option detected: "'+e+'"'+d,wi),wt=!0}static findInOptions(e,t,i,s=!1){let o=1e9,r="",a=[],d=e.toLowerCase(),h;for(let l in t){let c;if(t[l].__type__!==void 0&&s===!0){let u=X.findInOptions(e,t[l],zt(i,l));o>u.distance&&(r=u.closestMatch,a=u.path,o=u.distance,h=u.indexMatch)}else l.toLowerCase().indexOf(d)!==-1&&(h=l),c=X.levenshteinDistance(e,l),o>c&&(r=l,a=Fr(i),o=c)}return{closestMatch:r,path:a,distance:o,indexMatch:h}}static printLocation(e,t,i=`Problem value found at:
`){let s=`
`:n.distance<=d&&o.distance>n.distance?h=" in "+G.printLocation(o.path,e,"")+"Perhaps it was misplaced? Matching option found at: "+G.printLocation(n.path,n.closestMatch,""):o.distance<=a?h='. Did you mean "'+o.closestMatch+'"?'+G.printLocation(o.path,e):h=". Did you mean one of these: "+G.print(Object.keys(t))+G.printLocation(s,e),console.error('%cUnknown option detected: "'+e+'"'+h,ki),_t=!0}static findInOptions(e,t,s,o=!1){let n=1e9,a="",d=[],h=e.toLowerCase(),l;for(let c in t){let u;if(t[c].__type__!==void 0&&o===!0){let f=G.findInOptions(e,t[c],jt(s,c));n>f.distance&&(a=f.closestMatch,d=f.path,n=f.distance,l=f.indexMatch)}else c.toLowerCase().indexOf(h)!==-1&&(l=c),u=G.levenshteinDistance(e,c),n>u&&(a=c,d=Ir(s),n=u)}return{closestMatch:a,path:d,distance:n,indexMatch:l}}static printLocation(e,t,s=`Problem value found at:
`){let o=`
`+i+`options = {
`;for(let o=0;o<e.length;o++){for(let r=0;r<o+1;r++)s+=" ";s+=e[o]+`: {
`}for(let o=0;o<e.length+1;o++)s+=" ";s+=t+`
`;for(let o=0;o<e.length+1;o++){for(let r=0;r<e.length-o;r++)s+=" ";s+=`}
`}return s+`
`+s+`options = {
`;for(let n=0;n<e.length;n++){for(let a=0;a<n+1;a++)o+=" ";o+=e[n]+`: {
`}for(let n=0;n<e.length+1;n++)o+=" ";o+=t+`
`;for(let n=0;n<e.length+1;n++){for(let a=0;a<e.length-n;a++)o+=" ";o+=`}
`}return o+`
`}static print(e){return JSON.stringify(e).replace(/(")|(\[)|(\])|(,"__type__")/g,"").replace(/(,)/g,", ")}static levenshteinDistance(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let i=[],s;for(s=0;s<=t.length;s++)i[s]=[s];let o;for(o=0;o<=e.length;o++)i[0][o]=o;for(s=1;s<=t.length;s++)for(o=1;o<=e.length;o++)t.charAt(s-1)==e.charAt(o-1)?i[s][o]=i[s-1][o-1]:i[s][o]=Math.min(i[s-1][o-1]+1,Math.min(i[s][o-1]+1,i[s-1][o]+1));return i[t.length][e.length]}},Gs=me;var Ks=Us,Ue=mi,Zs=Ys,_i=wi,Qs=X;var jt,zr=new Uint8Array(16);function Ei(){if(!jt&&(jt=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!jt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return jt(zr)}var $s=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Lr(n){return typeof n=="string"&&$s.test(n)}var Js=Lr;var Q=[];for(Wt=0;Wt<256;++Wt)Q.push((Wt+256).toString(16).substr(1));var Wt;function Rr(n){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(Q[n[e+0]]+Q[n[e+1]]+Q[n[e+2]]+Q[n[e+3]]+"-"+Q[n[e+4]]+Q[n[e+5]]+"-"+Q[n[e+6]]+Q[n[e+7]]+"-"+Q[n[e+8]]+Q[n[e+9]]+"-"+Q[n[e+10]]+Q[n[e+11]]+Q[n[e+12]]+Q[n[e+13]]+Q[n[e+14]]+Q[n[e+15]]).toLowerCase();if(!Js(t))throw TypeError("Stringified UUID is invalid");return t}var eo=Rr;function Hr(n,e,t){n=n||{};var i=n.random||(n.rng||Ei)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(var s=0;s<16;++s)e[t+s]=i[s];return e}return eo(i)}var Ce=Hr;function to(n){return typeof n=="string"||typeof n=="number"}var Vt=class{constructor(e){$(this,"delay");$(this,"max");$(this,"_queue",[]);$(this,"_timeout",null);$(this,"_extended",null);this.delay=null,this.max=1/0,this.setOptions(e)}setOptions(e){e&&typeof e.delay!="undefined"&&(this.delay=e.delay),e&&typeof e.max!="undefined"&&(this.max=e.max),this._flushIfNeeded()}static extend(e,t){let i=new Vt(t);if(e.flush!==void 0)throw new Error("Target object already has a property flush");e.flush=()=>{i.flush()};let s=[{name:"flush",original:void 0}];if(t&&t.replace)for(let o=0;o<t.replace.length;o++){let r=t.replace[o];s.push({name:r,original:e[r]}),i.replace(e,r)}return i._extended={object:e,methods:s},i}destroy(){if(this.flush(),this._extended){let e=this._extended.object,t=this._extended.methods;for(let i=0;i<t.length;i++){let s=t[i];s.original?e[s.name]=s.original:delete e[s.name]}this._extended=null}}replace(e,t){let i=this,s=e[t];if(!s)throw new Error("Method "+t+" undefined");e[t]=function(...o){i.queue({args:o,fn:s,context:this})}}queue(e){typeof e=="function"?this._queue.push({fn:e}):this._queue.push(e),this._flushIfNeeded()}_flushIfNeeded(){this._queue.length>this.max&&this.flush(),this._timeout!=null&&(clearTimeout(this._timeout),this._timeout=null),this.queue.length>0&&typeof this.delay=="number"&&(this._timeout=setTimeout(()=>{this.flush()},this.delay))}flush(){this._queue.splice(0).forEach(e=>{e.fn.apply(e.context||e.fn,e.args||[])})}},_t=class{constructor(){$(this,"_subscribers",{"*":[],add:[],remove:[],update:[]});$(this,"subscribe",_t.prototype.on);$(this,"unsubscribe",_t.prototype.off)}_trigger(e,t,i){if(e==="*")throw new Error("Cannot trigger event *");[...this._subscribers[e],...this._subscribers["*"]].forEach(s=>{s(e,t,i!=null?i:null)})}on(e,t){typeof t=="function"&&this._subscribers[e].push(t)}off(e,t){this._subscribers[e]=this._subscribers[e].filter(i=>i!==t)}},Ie=class{constructor(e){$(this,"_pairs");this._pairs=e}*[Symbol.iterator](){for(let[e,t]of this._pairs)yield[e,t]}*entries(){for(let[e,t]of this._pairs)yield[e,t]}*keys(){for(let[e]of this._pairs)yield e}*values(){for(let[,e]of this._pairs)yield e}toIdArray(){return[...this._pairs].map(e=>e[0])}toItemArray(){return[...this._pairs].map(e=>e[1])}toEntryArray(){return[...this._pairs]}toObjectMap(){let e=Object.create(null);for(let[t,i]of this._pairs)e[t]=i;return e}toMap(){return new Map(this._pairs)}toIdSet(){return new Set(this.toIdArray())}toItemSet(){return new Set(this.toItemArray())}cache(){return new Ie([...this._pairs])}distinct(e){let t=new Set;for(let[i,s]of this._pairs)t.add(e(s,i));return t}filter(e){let t=this._pairs;return new Ie({*[Symbol.iterator](){for(let[i,s]of t)e(s,i)&&(yield[i,s])}})}forEach(e){for(let[t,i]of this._pairs)e(i,t)}map(e){let t=this._pairs;return new Ie({*[Symbol.iterator](){for(let[i,s]of t)yield[i,e(s,i)]}})}max(e){let t=this._pairs[Symbol.iterator](),i=t.next();if(i.done)return null;let s=i.value[1],o=e(i.value[1],i.value[0]);for(;!(i=t.next()).done;){let[r,a]=i.value,d=e(a,r);d>o&&(o=d,s=a)}return s}min(e){let t=this._pairs[Symbol.iterator](),i=t.next();if(i.done)return null;let s=i.value[1],o=e(i.value[1],i.value[0]);for(;!(i=t.next()).done;){let[r,a]=i.value,d=e(a,r);d<o&&(o=d,s=a)}return s}reduce(e,t){for(let[i,s]of Line truncated
`||z==="\r";)Z();do{var n=!1;if(z==="#"){for(var e=it-1;Pe.charAt(e)===" "||Pe.charAt(e)===" ";)e--;if(Pe.charAt(e)===`
`||Pe.charAt(e)===""){for(;z!=""&&z!=`
`;)Z();n=!0}}if(z==="/"&&st()==="/"){for(;z!=""&&z!=`
`;)Z();n=!0}if(z==="/"&&st()==="*"){for(;z!="";)if(z==="*"&&st()==="/"){Z(),Z();break}else Z();n=!0}for(;z===" "||z===" "||z===`
`||z==="\r";)Z()}while(n);if(z===""){oe=te.DELIMITER;return}var t=z+st();if(uo[t]){oe=te.DELIMITER,M=t,Z(),Z();return}if(uo[z]){oe=te.DELIMITER,M=z,Z();return}if(fo(z)||z==="-"){for(M+=z,Z();fo(z);)M+=z,Z();M==="false"?M=!1:M==="true"?M=!0:isNaN(Number(M))||(M=Number(M)),oe=te.IDENTIFIER;return}if(z==='"'){for(Z();z!=""&&(z!='"'||z==='"'&&st()==='"');)z==='"'?(M+=z,Z()):z==="\\"&&st()==="n"?(M+=`
`,Z()):M+=z,Z();if(z!='"')throw ie('End of string " expected');Z(),oe=te.IDENTIFIER;return}for(oe=te.UNKNOWN;z!="";)M+=z,Z();throw new SyntaxError('Syntax error in part "'+vo(M,30)+'"')}function ea(){var n={};if(Qr(),V(),M==="strict"&&(n.strict=!0,V()),(M==="graph"||M==="digraph")&&(n.type=M,V()),oe===te.IDENTIFIER&&(n.id=M,V()),M!="{")throw ie("Angle bracket { expected");if(V(),mo(n),M!="}")throw ie("Angle bracket } expected");if(V(),M!=="")throw ie("End of file expected");return V(),delete n.node,delete n.edge,delete n.graph,n}function mo(n){for(;M!==""&&M!="}";)ta(n),M===";"&&V()}function ta(n){var e=yo(n);if(e){bo(n,e);return}var t=ia(n);if(!t){if(oe!=te.IDENTIFIER)throw ie("Identifier expected");var i=M;if(V(),M==="="){if(V(),oe!=te.IDENTIFIER)throw ie("Identifier expected");n[i]=M,V()}else sa(n,i)}}function yo(n){var e=null;if(M==="subgraph"&&(e={},e.type="subgraph",V(),oe===te.IDENTIFIER&&(e.id=M,V())),M==="{"){if(V(),e||(e={}),e.parent=n,e.node=n.node,e.edge=n.edge,e.graph=n.graph,mo(e),M!="}")throw ie("Angle bracket } expected");V(),delete e.node,delete e.edge,delete e.graph,delete e.parent,n.subgraphs||(n.subgraphs=[]),n.subgraphs.push(e)}return e}function ia(n){return M==="node"?(V(),n.node=xt(),"node"):M==="edge"?(V(),n.edge=xt(),"edge"):M==="graph"?(V(),n.graph=xt(),"graph"):null}function sa(n,e){var t={id:e},i=xt();i&&(t.attr=i),po(n,t),bo(n,e)}function bo(n,e){for(;M==="->"||M==="--";){var t,i=M;V();var s=yo(n);if(s)t=s;else{if(oe!=te.IDENTIFIER)throw ie("Identifier or subgraph expected");t=M,po(n,{id:t}),V()}var o=xt(),r=go(n,e,t,i,o);Jr(n,r),e=t}}function xt(){for(var n,e=null,t={dashed:!0,solid:!1,dotted:[1,5]},i={dot:"circle",box:"box",crow:"crow",curve:"curve",icurve:"inv_curve",normal:"triangle",inv:"inv_triangle",diamond:"diamond",tee:"bar",vee:"vee"},s=new Array,o=new Array;M==="[";){for(V(),e={};M!==""&&M!="]";){if(oe!=te.IDENTIFIER)throw ie("Attribute name expected");var r=M;if(V(),M!="=")throw ie("Equal sign = expected");if(V(),oe!=te.IDENTIFIER)throw ie("Attribute value expected");var a=M;r==="style"&&(a=t[a]);var d;r==="arrowhead"&&(d=i[a],r="arrows",a={to:{enabled:!0,type:d}}),r==="arrowtail"&&(d=i[a],r="arrows",a={from:{enabled:!0,type:d}}),s.push({attr:e,name:r,value:a}),o.push(r),V(),M==","&&V()}if(M!="]")throw ie("Bracket ] expected");V()}if(o.includes("dir")){var h={};for(h.arrows={},n=0;n<s.length;n++)if(s[n].name==="arrows")if(s[n].value.to!=null)h.arrows.to=n;else if(s[n].value.from!=null)h.arrows.from=n;else throw ie("Invalid value of arrows");else s[n].name==="dir"&&(h.dir=n);var l=s[h.dir].value;if(!o.includes("arrows"))if(l==="both")s.push({attr:s[h.dir].attr,name:"arrows",value:{to:{enabled:!0}}}),h.arrows.to=s.length-1,s.push({attr:s[h.dir].attr,name:"arrows",value:{from:{enabled:!0}}}),h.arrows.from=s.length-1;else if(l==="forward")s.push({attr:s[h.dir].attr,name:"arrows",value:{to:{enabled:!0}}}),h.arrows.to=s.length-1;else if(l==="back")s.push({attr:s[h.dir].attr,name:"arrows",value:{from:{enabled:!0}}}),h.arrows.from=s.length-1;else if(l==="none")s.push({attr:s[h.dir].attr,name:"arrows",value:""}),h.arrows.to=s.length-1;else throw ie('Invalid dir type "'+l+'"');var c,u;if(l==="both")h.arrows.to&&h.arrows.from?(u=s[h.arrows.to].value.to.type,c=s[h.arrows.from].value.from.type,s[h.arrows.to]={attr:s[h.arrows.to].attr,name:s[h.arrows.to].name,value:{to:{enabled:!0,type:u},from:{enabled:!0,type:c}}},s.splice(h.arrows.from,1)):h.arrows.to?(u=s[h.arrows.to].value.to.type,c="arrow",s[h.arrows.to]={attr:s[h.arrows.to].attr,name:s[h.arrows.to].name,value:{to:{enabled:!0,type:u},from:{enabled:!0,type:c}}}):h.arrows.from&&(u="arrow",c=s[h.arrows.from].value.from.type,s[h.arrows.from]={attr:s[h.arrows.from].attr,name:s[h.arrows.from].name,value:{to:{enabled:!0,type:u},from:{enabled:!0,type:c}}});else if(l==="back")h.arrows.to&&h.arrows.from?(u="",c=s[h.arrows.from].value.from.type,s[h.arrows.from]={attr:s[h.arrows.from].attr,name:s[h.arrows.from].name,value:{to:{enabled:!0,type:u},from:{enabled:!0,type:c}}}):h.arrows.to?(u="",c="arrow",h.arrows.from=h.arrows.to,s[h.arrows.from]={attr:s[h.arrows.from].attr,name:s[h.arrows.from].name,value:{to:{enabled:!0,type:u},from:{enabled:!0,type:c}}}):h.arrows.from&&(u="",c=s[h.arrows.from].value.from.type,s[h.arrows.to]={attr:s[h.arrows.from].attr,name:s[h.arrows.from].name,value:{to:{enabled:!0,type:u},from:{enabled:!0,type:c}}}),s[h.arrows.from]={attr:s[h.arrows.from].attr,name:s[h.arrows.from].name,value:{from:{enabled:!0,type:s[h.arrows.from].value.from.type}}};else if(l==="none"){var p;h.arrows.to?p=h.arrows.to:p=h.arrows.from,s[p]={attr:s[p].attr,name:s[p].name,value:""}}else if(l==="forward")h.arrows.to&&h.arrows.from?(u=s[h.arrows.to].value.to.type,c="",s[h.arrows.to]={attr:s[h.arrows.to].attr,name:s[h.arrows.to].name,value:{to:{enabled:!0,type:u},from:{enabled:!0,type:c}}}):h.arrows.to?(u=s[h.arrows.to].value.to.type,c="",s[h.arrows.to]={attr:s[h.arrows.to].attr,name:s[h.arrows.to].name,value:{to:{enabled:!0,type:u},from:{en Line truncated
`}static print(e){return JSON.stringify(e).replace(/(")|(\[)|(\])|(,"__type__")/g,"").replace(/(,)/g,", ")}static levenshteinDistance(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let s=[],o;for(o=0;o<=t.length;o++)s[o]=[o];let n;for(n=0;n<=e.length;n++)s[0][n]=n;for(o=1;o<=t.length;o++)for(n=1;n<=e.length;n++)t.charAt(o-1)==e.charAt(n-1)?s[o][n]=s[o-1][n-1]:s[o][n]=Math.min(s[o-1][n-1]+1,Math.min(s[o][n-1]+1,s[o-1][n]+1));return s[t.length][e.length]}},Vo=xe;var qo=Fr,Ze=Si,Yo=Br,Mi=ki,Xo=Ar;var qt,zr=new Uint8Array(16);function Di(){if(!qt&&(qt=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!qt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return qt(zr)}var Uo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Rr(r){return typeof r=="string"&&Uo.test(r)}var Go=Rr;var ee=[];for(Yt=0;Yt<256;++Yt)ee.push((Yt+256).toString(16).substr(1));var Yt;function Lr(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(ee[r[e+0]]+ee[r[e+1]]+ee[r[e+2]]+ee[r[e+3]]+"-"+ee[r[e+4]]+ee[r[e+5]]+"-"+ee[r[e+6]]+ee[r[e+7]]+"-"+ee[r[e+8]]+ee[r[e+9]]+"-"+ee[r[e+10]]+ee[r[e+11]]+ee[r[e+12]]+ee[r[e+13]]+ee[r[e+14]]+ee[r[e+15]]).toLowerCase();if(!Go(t))throw TypeError("Stringified UUID is invalid");return t}var Ko=Lr;function Hr(r,e,t){r=r||{};var s=r.random||(r.rng||Di)();if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,e){t=t||0;for(var o=0;o<16;++o)e[t+o]=s[o];return e}return Ko(s)}var Ne=Hr;function $o(r){return typeof r=="string"||typeof r=="number"}var Ni=class r{constructor(e){se(this,"delay");se(this,"max");se(this,"_queue",[]);se(this,"_timeout",null);se(this,"_extended",null);this.delay=null,this.max=1/0,this.setOptions(e)}setOptions(e){e&&typeof e.delay!="undefined"&&(this.delay=e.delay),e&&typeof e.max!="undefined"&&(this.max=e.max),this._flushIfNeeded()}static extend(e,t){let s=new r(t);if(e.flush!==void 0)throw new Error("Target object already has a property flush");e.flush=()=>{s.flush()};let o=[{name:"flush",original:void 0}];if(t&&t.replace)for(let n=0;n<t.replace.length;n++){let a=t.replace[n];o.push({name:a,original:e[a]}),s.replace(e,a)}return s._extended={object:e,methods:o},s}destroy(){if(this.flush(),this._extended){let e=this._extended.object,t=this._extended.methods;for(let s=0;s<t.length;s++){let o=t[s];o.original?e[o.name]=o.original:delete e[o.name]}this._extended=null}}replace(e,t){let s=this,o=e[t];if(!o)throw new Error("Method "+t+" undefined");e[t]=function(...n){s.queue({args:n,fn:o,context:this})}}queue(e){typeof e=="function"?this._queue.push({fn:e}):this._queue.push(e),this._flushIfNeeded()}_flushIfNeeded(){this._queue.length>this.max&&this.flush(),this._timeout!=null&&(clearTimeout(this._timeout),this._timeout=null),this.queue.length>0&&typeof this.delay=="number"&&(this._timeout=setTimeout(()=>{this.flush()},this.delay))}flush(){this._queue.splice(0).forEach(e=>{e.fn.apply(e.context||e.fn,e.args||[])})}},Fi=class r{constructor(){se(this,"_subscribers",{"*":[],add:[],remove:[],update:[]});se(this,"subscribe",r.prototype.on);se(this,"unsubscribe",r.prototype.off)}_trigger(e,t,s){if(e==="*")throw new Error("Cannot trigger event *");[...this._subscribers[e],...this._subscribers["*"]].forEach(o=>{o(e,t,s!=null?s:null)})}on(e,t){typeof t=="function"&&this._subscribers[e].push(t)}off(e,t){this._subscribers[e]=this._subscribers[e].filter(s=>s!==t)}},Xt=class r{constructor(e){se(this,"_pairs");this._pairs=e}*[Symbol.iterator](){for(let[e,t]of this._pairs)yield[e,t]}*entries(){for(let[e,t]of this._pairs)yield[e,t]}*keys(){for(let[e]of this._pairs)yield e}*values(){for(let[,e]of this._pairs)yield e}toIdArray(){return[...this._pairs].map(e=>e[0])}toItemArray(){return[...this._pairs].map(e=>e[1])}toEntryArray(){return[...this._pairs]}toObjectMap(){let e=Object.create(null);for(let[t,s]of this._pairs)e[t]=s;return e}toMap(){return new Map(this._pairs)}toIdSet(){return new Set(this.toIdArray())}toItemSet(){return new Set(this.toItemArray())}cache(){return new r([...this._pairs])}distinct(e){let t=new Set;for(let[s,o]of this._pairs)t.add(e(o,s));return t}filter(e){let t=this._pairs;return new r({*[Symbol.iterator](){for(let[s,o]of t)e(o,s)&&(yield[s,o])}})}forEach(e){for(let[t,s]of this._pairs)e(s,t)}map(e){let t=this._pairs;return new r({*[Symbol.iterator](){for(let[s,o]of t)yield[s,e(o,s)]}})}max(e){let t=this._pairs[Symbol.iterator](),s=t.next();if(s.done)return null;let o=s.value[1],n=e(s.value[1],s.value[0]);for(;!(s=t.next()).done;){let[a,d]=s.value,h=e(d,a);h>n&&(n=h,o=d)}return o}min(e){let t=this._pairs[Symbol.iterator](),s=t.next();if(s.done)return null;let o=s.value[1],n=e(s.value[1],s.value[0]);for(;!(s=t.next()).done;){let[a,d]=s.value,h=e(d,a);h<n&&(n=h,o=d)}return o Line truncated
`||B==="\r";)J();do{var r=!1;if(B==="#"){for(var e=at-1;Re.charAt(e)===" "||Re.charAt(e)===" ";)e--;if(Re.charAt(e)===`
`||Re.charAt(e)===""){for(;B!=""&&B!=`
`;)J();r=!0}}if(B==="/"&&nt()==="/"){for(;B!=""&&B!=`
`;)J();r=!0}if(B==="/"&&nt()==="*"){for(;B!="";)if(B==="*"&&nt()==="/"){J(),J();break}else J();r=!0}for(;B===" "||B===" "||B===`
`||B==="\r";)J()}while(r);if(B===""){he=re.DELIMITER;return}var t=B+nt();if(Qo[t]){he=re.DELIMITER,M=t,J(),J();return}if(Qo[B]){he=re.DELIMITER,M=B,J();return}if(Jo(B)||B==="-"){for(M+=B,J();Jo(B);)M+=B,J();M==="false"?M=!1:M==="true"?M=!0:isNaN(Number(M))||(M=Number(M)),he=re.IDENTIFIER;return}if(B==='"'){for(J();B!=""&&(B!='"'||B==='"'&&nt()==='"');)B==='"'?(M+=B,J()):B==="\\"&&nt()==="n"?(M+=`
`,J()):M+=B,J();if(B!='"')throw ae('End of string " expected');J(),he=re.IDENTIFIER;return}for(he=re.UNKNOWN;B!="";)M+=B,J();throw new SyntaxError('Syntax error in part "'+fn(M,30)+'"')}function ea(){var r={};if(Zr(),Y(),M==="strict"&&(r.strict=!0,Y()),(M==="graph"||M==="digraph")&&(r.type=M,Y()),he===re.IDENTIFIER&&(r.id=M,Y()),M!="{")throw ae("Angle bracket { expected");if(Y(),ln(r),M!="}")throw ae("Angle bracket } expected");if(Y(),M!=="")throw ae("End of file expected");return Y(),delete r.node,delete r.edge,delete r.graph,r}function ln(r){for(;M!==""&&M!="}";)ta(r),M===";"&&Y()}function ta(r){var e=cn(r);if(e){un(r,e);return}var t=ia(r);if(!t){if(he!=re.IDENTIFIER)throw ae("Identifier expected");var s=M;if(Y(),M==="="){if(Y(),he!=re.IDENTIFIER)throw ae("Identifier expected");r[s]=M,Y()}else sa(r,s)}}function cn(r){var e=null;if(M==="subgraph"&&(e={},e.type="subgraph",Y(),he===re.IDENTIFIER&&(e.id=M,Y())),M==="{"){if(Y(),e||(e={}),e.parent=r,e.node=r.node,e.edge=r.edge,e.graph=r.graph,ln(e),M!="}")throw ae("Angle bracket } expected");Y(),delete e.node,delete e.edge,delete e.graph,delete e.parent,r.subgraphs||(r.subgraphs=[]),r.subgraphs.push(e)}return e}function ia(r){return M==="node"?(Y(),r.node=kt(),"node"):M==="edge"?(Y(),r.edge=kt(),"edge"):M==="graph"?(Y(),r.graph=kt(),"graph"):null}function sa(r,e){var t={id:e},s=kt();s&&(t.attr=s),dn(r,t),un(r,e)}function un(r,e){for(;M==="->"||M==="--";){var t,s=M;Y();var o=cn(r);if(o)t=o;else{if(he!=re.IDENTIFIER)throw ae("Identifier or subgraph expected");t=M,dn(r,{id:t}),Y()}var n=kt(),a=hn(r,e,t,s,n);Jr(r,a),e=t}}function kt(){for(var r,e=null,t={dashed:!0,solid:!1,dotted:[1,5]},s={dot:"circle",box:"box",crow:"crow",curve:"curve",icurve:"inv_curve",normal:"triangle",inv:"inv_triangle",diamond:"diamond",tee:"bar",vee:"vee"},o=new Array,n=new Array;M==="[";){for(Y(),e={};M!==""&&M!="]";){if(he!=re.IDENTIFIER)throw ae("Attribute name expected");var a=M;if(Y(),M!="=")throw ae("Equal sign = expected");if(Y(),he!=re.IDENTIFIER)throw ae("Attribute value expected");var d=M;a==="style"&&(d=t[d]);var h;a==="arrowhead"&&(h=s[d],a="arrows",d={to:{enabled:!0,type:h}}),a==="arrowtail"&&(h=s[d],a="arrows",d={from:{enabled:!0,type:h}}),o.push({attr:e,name:a,value:d}),n.push(a),Y(),M==","&&Y()}if(M!="]")throw ae("Bracket ] expected");Y()}if(n.includes("dir")){var l={};for(l.arrows={},r=0;r<o.length;r++)if(o[r].name==="arrows")if(o[r].value.to!=null)l.arrows.to=r;else if(o[r].value.from!=null)l.arrows.from=r;else throw ae("Invalid value of arrows");else o[r].name==="dir"&&(l.dir=r);var c=o[l.dir].value;if(!n.includes("arrows"))if(c==="both")o.push({attr:o[l.dir].attr,name:"arrows",value:{to:{enabled:!0}}}),l.arrows.to=o.length-1,o.push({attr:o[l.dir].attr,name:"arrows",value:{from:{enabled:!0}}}),l.arrows.from=o.length-1;else if(c==="forward")o.push({attr:o[l.dir].attr,name:"arrows",value:{to:{enabled:!0}}}),l.arrows.to=o.length-1;else if(c==="back")o.push({attr:o[l.dir].attr,name:"arrows",value:{from:{enabled:!0}}}),l.arrows.from=o.length-1;else if(c==="none")o.push({attr:o[l.dir].attr,name:"arrows",value:""}),l.arrows.to=o.length-1;else throw ae('Invalid dir type "'+c+'"');var u,f;if(c==="both")l.arrows.to&&l.arrows.from?(f=o[l.arrows.to].value.to.type,u=o[l.arrows.from].value.from.type,o[l.arrows.to]={attr:o[l.arrows.to].attr,name:o[l.arrows.to].name,value:{to:{enabled:!0,type:f},from:{enabled:!0,type:u}}},o.splice(l.arrows.from,1)):l.arrows.to?(f=o[l.arrows.to].value.to.type,u="arrow",o[l.arrows.to]={attr:o[l.arrows.to].attr,name:o[l.arrows.to].name,value:{to:{enabled:!0,type:f},from:{enabled:!0,type:u}}}):l.arrows.from&&(f="arrow",u=o[l.arrows.from].value.from.type,o[l.arrows.from]={attr:o[l.arrows.from].attr,name:o[l.arrows.from].name,value:{to:{enabled:!0,type:f},from:{enabled:!0,type:u}}});else if(c==="back")l.arrows.to&&l.arrows.from?(f="",u=o[l.arrows.from].value.from.type,o[l.arrows.from]={attr:o[l.arrows.from].attr,name:o[l.arrows.from].name,value:{to:{enabled:!0,type:f},from:{enabled:!0,type:u}}}):l.arrows.to?(f="",u="arrow",l.arrows.from=l.arrows.to,o[l.arrows.from]={attr:o[l.arrows.from].attr,name:o[l.arrows.from].name,value:{to:{enabled:!0,type:f},from:{enabled:!0,type:u}}}):l.arrows.from&&(f="",u=o[l.arrows.from].value.from.type,o[l.arrows.to]={attr:o[l.arrows.from].attr,name:o[l.arrows.from].name,value:{to:{enabled:!0,type:f},from:{enabled:!0,type:u}}}),o[l.arrows.from]={attr:o[l.arrows.from].attr,name:o[l.arrows.from].name,value:{from:{enabled:!0,type:o[l.arrows.from].value.from.type}}};else if(c==="none"){var p;l.arrows.to?p=l.arrows.to:p=l.arrows.from,o[p]={attr:o[p].attr,name:o[p].name,value:""}}else if(c==="forward")l.arrows.to&&l.arrows.from?(f=o[l.arrows.to].value.to.type,u="",o[l.arrows.to]={attr:o[l.arrows.to].attr,name:o[l.arrows.to].name,value:{to:{enabled:!0,type:f},from:{enabled:!0,type:u}}}):l.arrows.to?(f=o[l.arrows.to].value.to.type,u="",o[l.arrows.to]={attr:o[l.arrows.to].attr,name:o[l.arrows.to].name,value:{to:{enabled:!0,type:f},from:{en Line truncated
`),e=e.replace(/\r/g,`
`);let i=String(e).split(`
`),s=i.length;if(t.multi)for(let o=0;o<s;o++){let r=this.splitBlocks(i[o],t.multi);if(r!==void 0){if(r.length===0){this.lines.newLine("");continue}if(t.maxWdt>0)for(let a=0;a<r.length;a++){let d=r[a].mod,h=r[a].text;this.splitStringIntoLines(h,d,!0)}else for(let a=0;a<r.length;a++){let d=r[a].mod,h=r[a].text;this.lines.append(h,d)}this.lines.newLine()}}else if(t.maxWdt>0)for(let o=0;o<s;o++)this.splitStringIntoLines(i[o]);else for(let o=0;o<s;o++)this.lines.newLine(i[o]);return this.lines.finalize()}decodeMarkupSystem(e){let t="none";return e==="markdown"||e==="md"?t="markdown":(e===!0||e==="html")&&(t="html"),t}splitHtmlBlocks(e){let t=new Pi(e),i=s=>/&/.test(s)?(t.replace(t.text,"&lt;","<")||t.replace(t.text,"&amp;","&")||t.add("&"),!0):!1;for(;t.position<t.text.length;){let s=t.text.charAt(t.position);t.parseWS(s)||/</.test(s)&&(t.parseStartTag("bold","<b>")||t.parseStartTag("ital","<i>")||t.parseStartTag("mono","<code>")||t.parseEndTag("bold","</b>")||t.parseEndTag("ital","</i>")||t.parseEndTag("mono","</code>"))||i(s)||t.add(s),t.position++}return t.emitBlock(),t.blocks}splitMarkdownBlocks(e){let t=new Pi(e),i=!0,s=o=>/\\/.test(o)?(t.position<this.text.length+1&&(t.position++,o=this.text.charAt(t.position),/ \t/.test(o)?t.spacing=!0:(t.add(o),i=!1)),!0):!1;for(;t.position<t.text.length;){let o=t.text.charAt(t.position);t.parseWS(o)||s(o)||(i||t.spacing)&&(t.parseStartTag("bold","*")||t.parseStartTag("ital","_")||t.parseStartTag("mono","`"))||t.parseEndTag("bold","*","afterBold")||t.parseEndTag("ital","_","afterItal")||t.parseEndTag("mono","`","afterMono")||(t.add(o),i=!1),t.position++}return t.emitBlock(),t.blocks}splitBlocks(e,t){let i=this.decodeMarkupSystem(t);if(i==="none")return[{text:e,mod:"normal"}];if(i==="markdown")return this.splitMarkdownBlocks(e);if(i==="html")return this.splitHtmlBlocks(e)}overMaxWidth(e){let t=this.ctx.measureText(e).width;return this.lines.curWidth()+t>this.parent.fontOptions.maxWdt}getLongestFit(e){let t="",i=0;for(;i<e.length;){let o=t+(t===""?"":" ")+e[i];if(this.overMaxWidth(o))break;t=o,i++}return i}getLongestFitWord(e){let t=0;for(;t<e.length&&!this.overMaxWidth(e.slice(0,t));)t++;return t}splitStringIntoLines(e,t="normal",i=!1){this.parent.getFormattingValues(this.ctx,this.selected,this.hover,t),e=e.replace(/^( +)/g,"$1\r"),e=e.replace(/([^\r][^ ]*)( +)/g,"$1\r$2\r");let s=e.split("\r");for(;s.length>0;){let o=this.getLongestFit(s);if(o===0){let r=s[0],a=this.getLongestFitWord(r);this.lines.newLine(r.slice(0,a),t),s[0]=r.slice(a)}else{let r=o;s[o-1]===" "?o--:s[r]===" "&&r++;let a=s.slice(0,o).join("");o==s.length&&i?this.lines.append(a,t):this.lines.newLine(a,t),s=s.slice(r)}}}},Xt=["bold","ital","boldital","mono"],Ye=class{constructor(e,t,i=!1){this.body=e,this.pointToSelf=!1,this.baseSize=void 0,this.fontOptions={},this.setOptions(t),this.size={top:0,left:0,width:0,height:0,yLine:0},this.isEdgeLabel=i}setOptions(e){if(this.elementOptions=e,this.initFontOptions(e.font),Yt(e.label)?this.labelDirty=!0:e.label=void 0,e.font!==void 0&&e.font!==null){if(typeof e.font=="string")this.baseSize=this.fontOptions.size;else if(typeof e.font=="object"){let t=e.font.size;t!==void 0&&(this.baseSize=t)}}}initFontOptions(e){if(A(Xt,t=>{this.fontOptions[t]={}}),Ye.parseFontString(this.fontOptions,e)){this.fontOptions.vadjust=0;return}A(e,(t,i)=>{t!=null&&typeof t!="object"&&(this.fontOptions[i]=t)})}static parseFontString(e,t){if(!t||typeof t!="string")return!1;let i=t.split(" ");return e.size=+i[0].replace("px",""),e.face=i[1],e.color=i[2],!0}constrain(e){let t={constrainWidth:!1,maxWdt:-1,minWdt:-1,constrainHeight:!1,minHgt:-1,valign:"middle"},i=xe(e,"widthConstraint");if(typeof i=="number")t.maxWdt=Number(i),t.minWdt=Number(i);else if(typeof i=="object"){let o=xe(e,["widthConstraint","maximum"]);typeof o=="number"&&(t.maxWdt=Number(o));let r=xe(e,["widthConstraint","minimum"]);typeof r=="number"&&(t.minWdt=Number(r))}let s=xe(e,"heightConstraint");if(typeof s=="number")t.minHgt=Number(s);else if(typeof s=="object"){let o=xe(e,["heightConstraint","minimum"]);typeof o=="number"&&(t.minHgt=Number(o));let r=xe(e,["heightConstraint","valign"]);typeof r=="string"&&(r==="top"||r==="bottom")&&(t.valign=r)}return t}update(e,t){this.setOptions(e,!0),this.propagateFonts(t),j(this.fontOptions,this.constrain(t)),this.fontOptions.chooser=Oi("label",t)}adjustSizes(e){let t=e?e.right+e.left:0;this.fontOptions.constrainWidth&&(this.fontOptions.maxWdt-=t,this.fontOptions.minWdt-=t);let i=e?e.top+e.bottom:0;this.fontOptions.constrainHeight&&(this.fontOptions.minHgt-=i)}addFontOptionsToPile(e,t){for(let i=0;i<t.length;++i)this.addFontToPile(e,t[i])}addFontToPile(e,t){if(t===void 0||t.font===void 0||t.font===null)return;let i=t.font;e.push(i)}getBasicOptions(e){let t={};for(let i=0;i<e.length;++i){let s=e[i],o={};Ye.parseFontString(o,s)&&(s=o),A(s,(r,a)=>{r!==void 0&&(Object.prototype.hasOwnProperty.call(t,a)||(Xt.indexOf(a)!==-1?t[a]={}:t[a]=r))})}return t}getFontOption(e,t,i){let s;for(let o=0; Line truncated
/*! Hammer.JS - v2.0.17-rc - 2019-12-16
* http://naver.github.io/egjs
*
* Forked By Naver egjs
* Copyright (c) hammerjs
* Licensed under the MIT license */
/**
* vis-data
* http://visjs.org/
*
* Manage unstructured data using DataSet. Add, update, and remove data, and listen for changes in the data.
*
* @version 7.1.6
* @date 2023-03-22T11:39:37.256Z
*
* @copyright (c) 2011-2017 Almende B.V, http://almende.com
* @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
*
* @license
* vis.js is dual licensed under both
*
* 1. The Apache 2.0 License
* http://www.apache.org/licenses/LICENSE-2.0
*
* and
*
* 2. The MIT License
* http://opensource.org/licenses/MIT
*
* vis.js may be distributed under either license.
*/
/**
* vis-network
* https://visjs.github.io/vis-network/
*
* A dynamic, browser-based visualization library.
*
* @version 9.1.6
* @date 2023-03-23T21:31:19.223Z
*
* @copyright (c) 2011-2017 Almende B.V, http://almende.com
* @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
*
* @license
* vis.js is dual licensed under both
*
* 1. The Apache 2.0 License
* http://www.apache.org/licenses/LICENSE-2.0
*
* and
*
* 2. The MIT License
* http://opensource.org/licenses/MIT
*
* vis.js may be distributed under either license.
*/
/**
* vis-util
* https://github.com/visjs/vis-util
*
* utilitie collection for visjs
*
* @version 5.0.3
* @date 2022-03-04T18:53:16.725Z
*
* @copyright (c) 2011-2017 Almende B.V, http://almende.com
* @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
*
* @license
* vis.js is dual licensed under both
*
* 1. The Apache 2.0 License
* http://www.apache.org/licenses/LICENSE-2.0
*
* and
*
* 2. The MIT License
* http://opensource.org/licenses/MIT
*
* vis.js may be distributed under either license.
*/
`);let s=String(e).split(`
`),o=s.length;if(t.multi)for(let n=0;n<o;n++){let a=this.splitBlocks(s[n],t.multi);if(a!==void 0){if(a.length===0){this.lines.newLine("");continue}if(t.maxWdt>0)for(let d=0;d<a.length;d++){let h=a[d].mod,l=a[d].text;this.splitStringIntoLines(l,h,!0)}else for(let d=0;d<a.length;d++){let h=a[d].mod,l=a[d].text;this.lines.append(l,h)}this.lines.newLine()}}else if(t.maxWdt>0)for(let n=0;n<o;n++)this.splitStringIntoLines(s[n]);else for(let n=0;n<o;n++)this.lines.newLine(s[n]);return this.lines.finalize()}decodeMarkupSystem(e){let t="none";return e==="markdown"||e==="md"?t="markdown":(e===!0||e==="html")&&(t="html"),t}splitHtmlBlocks(e){let t=new Zt(e),s=o=>/&/.test(o)?(t.replace(t.text,"&lt;","<")||t.replace(t.text,"&amp;","&")||t.add("&"),!0):!1;for(;t.position<t.text.length;){let o=t.text.charAt(t.position);t.parseWS(o)||/</.test(o)&&(t.parseStartTag("bold","<b>")||t.parseStartTag("ital","<i>")||t.parseStartTag("mono","<code>")||t.parseEndTag("bold","</b>")||t.parseEndTag("ital","</i>")||t.parseEndTag("mono","</code>"))||s(o)||t.add(o),t.position++}return t.emitBlock(),t.blocks}splitMarkdownBlocks(e){let t=new Zt(e),s=!0,o=n=>/\\/.test(n)?(t.position<this.text.length+1&&(t.position++,n=this.text.charAt(t.position),/ \t/.test(n)?t.spacing=!0:(t.add(n),s=!1)),!0):!1;for(;t.position<t.text.length;){let n=t.text.charAt(t.position);t.parseWS(n)||o(n)||(s||t.spacing)&&(t.parseStartTag("bold","*")||t.parseStartTag("ital","_")||t.parseStartTag("mono","`"))||t.parseEndTag("bold","*","afterBold")||t.parseEndTag("ital","_","afterItal")||t.parseEndTag("mono","`","afterMono")||(t.add(n),s=!1),t.position++}return t.emitBlock(),t.blocks}splitBlocks(e,t){let s=this.decodeMarkupSystem(t);if(s==="none")return[{text:e,mod:"normal"}];if(s==="markdown")return this.splitMarkdownBlocks(e);if(s==="html")return this.splitHtmlBlocks(e)}overMaxWidth(e){let t=this.ctx.measureText(e).width;return this.lines.curWidth()+t>this.parent.fontOptions.maxWdt}getLongestFit(e){let t="",s=0;for(;s<e.length;){let n=t+(t===""?"":" ")+e[s];if(this.overMaxWidth(n))break;t=n,s++}return s}getLongestFitWord(e){let t=0;for(;t<e.length&&!this.overMaxWidth(e.slice(0,t));)t++;return t}splitStringIntoLines(e,t="normal",s=!1){this.parent.getFormattingValues(this.ctx,this.selected,this.hover,t),e=e.replace(/^( +)/g,"$1\r"),e=e.replace(/([^\r][^ ]*)( +)/g,"$1\r$2\r");let o=e.split("\r");for(;o.length>0;){let n=this.getLongestFit(o);if(n===0){let a=o[0],d=this.getLongestFitWord(a);this.lines.newLine(a.slice(0,d),t),o[0]=a.slice(d)}else{let a=n;o[n-1]===" "?n--:o[a]===" "&&a++;let d=o.slice(0,n).join("");n==o.length&&s?this.lines.append(d,t):this.lines.newLine(d,t),o=o.slice(a)}}}},Gt=["bold","ital","boldital","mono"],Qt=class r{constructor(e,t,s=!1){this.body=e,this.pointToSelf=!1,this.baseSize=void 0,this.fontOptions={},this.setOptions(t),this.size={top:0,left:0,width:0,height:0,yLine:0},this.isEdgeLabel=s}setOptions(e){if(this.elementOptions=e,this.initFontOptions(e.font),$t(e.label)?this.labelDirty=!0:e.label=void 0,e.font!==void 0&&e.font!==null){if(typeof e.font=="string")this.baseSize=this.fontOptions.size;else if(typeof e.font=="object"){let t=e.font.size;t!==void 0&&(this.baseSize=t)}}}initFontOptions(e){if(F(Gt,t=>{this.fontOptions[t]={}}),r.parseFontString(this.fontOptions,e)){this.fontOptions.vadjust=0;return}F(e,(t,s)=>{t!=null&&typeof t!="object"&&(this.fontOptions[s]=t)})}static parseFontString(e,t){if(!t||typeof t!="string")return!1;let s=t.split(" ");return e.size=+s[0].replace("px",""),e.face=s[1],e.color=s[2],!0}constrain(e){let t={constrainWidth:!1,maxWdt:-1,minWdt:-1,constrainHeight:!1,minHgt:-1,valign:"middle"},s=De(e,"widthConstraint");if(typeof s=="number")t.maxWdt=Number(s),t.minWdt=Number(s);else if(typeof s=="object"){let n=De(e,["widthConstraint","maximum"]);typeof n=="number"&&(t.maxWdt=Number(n));let a=De(e,["widthConstraint","minimum"]);typeof a=="number"&&(t.minWdt=Number(a))}let o=De(e,"heightConstraint");if(typeof o=="number")t.minHgt=Number(o);else if(typeof o=="object"){let n=De(e,["heightConstraint","minimum"]);typeof n=="number"&&(t.minHgt=Number(n));let a=De(e,["heightConstraint","valign"]);typeof a=="string"&&(a==="top"||a==="bottom")&&(t.valign=a)}return t}update(e,t){this.setOptions(e,!0),this.propagateFonts(t),V(this.fontOptions,this.constrain(t)),this.fontOptions.chooser=js("label",t)}adjustSizes(e){let t=e?e.right+e.left:0;this.fontOptions.constrainWidth&&(this.fontOptions.maxWdt-=t,this.fontOptions.minWdt-=t);let s=e?e.top+e.bottom:0;this.fontOptions.constrainHeight&&(this.fontOptions.minHgt-=s)}addFontOptionsToPile(e,t){for(let s=0;s<t.length;++s)this.addFontToPile(e,t[s])}addFontToPile(e,t){if(t===void 0||t.font===void 0||t.font===null)return;let s=t.font;e.push(s)}getBasicOptions(e){let t={};for(let s=0;s<e.length;++s){let o=e[s],n={};r.parseFontString(n,o)&&(o=n),F(o,(a,d)=>{a!==void 0&&(Object.prototype.hasOwnProperty.call(t,d)||(Gt.indexOf(d)!==-1?t[d]={}:t[d]=a))})}return t}getFontOption(e,t,s){let o;for(let n=0; Line truncated
/*! Bundled license information:
@egjs/hammerjs/dist/hammer.esm.js:
(*! Hammer.JS - v2.0.17-rc - 2019-12-16
* http://naver.github.io/egjs
*
* Forked By Naver egjs
* Copyright (c) hammerjs
* Licensed under the MIT license *)
vis-util/esnext/esm/vis-util.js:
(**
* vis-util
* https://github.com/visjs/vis-util
*
* utilitie collection for visjs
*
* @version 5.0.7
* @date 2023-11-20T09:06:51.067Z
*
* @copyright (c) 2011-2017 Almende B.V, http://almende.com
* @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
*
* @license
* vis.js is dual licensed under both
*
* 1. The Apache 2.0 License
* http://www.apache.org/licenses/LICENSE-2.0
*
* and
*
* 2. The MIT License
* http://opensource.org/licenses/MIT
*
* vis.js may be distributed under either license.
*)
vis-data/esnext/esm/vis-data.js:
(**
* vis-data
* http://visjs.org/
*
* Manage unstructured data using DataSet. Add, update, and remove data, and listen for changes in the data.
*
* @version 7.1.9
* @date 2023-11-24T17:53:34.179Z
*
* @copyright (c) 2011-2017 Almende B.V, http://almende.com
* @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
*
* @license
* vis.js is dual licensed under both
*
* 1. The Apache 2.0 License
* http://www.apache.org/licenses/LICENSE-2.0
*
* and
*
* 2. The MIT License
* http://opensource.org/licenses/MIT
*
* vis.js may be distributed under either license.
*)
vis-network/esnext/esm/vis-network.js:
(**
* vis-network
* https://visjs.github.io/vis-network/
*
* A dynamic, browser-based visualization library.
*
* @version 9.1.10
* @date 2025-05-10T16:57:42.930Z
*
* @copyright (c) 2011-2017 Almende B.V, http://almende.com
* @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
*
* @license
* vis.js is dual licensed under both
*
* 1. The Apache 2.0 License
* http://www.apache.org/licenses/LICENSE-2.0
*
* and
*
* 2. The MIT License
* http://opensource.org/licenses/MIT
*
* vis.js may be distributed under either license.
*)
*/
@@ -1 +1 @@
(()=>{var l=(e,t,o)=>new Promise((n,r)=>{var c=s=>{try{i(o.next(s))}catch(a){r(a)}},m=s=>{try{i(o.throw(s))}catch(a){r(a)}},i=s=>s.done?n(s.value):Promise.resolve(s.value).then(c,m);i((o=o.apply(e,t)).next())});var d=e=>{if(!document.cookie)return;let t=null,o=document.cookie.split(";");for(let n=0;n<o.length;n++){let r=o[n].trim();if(r.substring(0,e.length+1)===e+"="){t=decodeURIComponent(r.substring(e.length+1));break}}return t};var u={success:e=>{let t=document.querySelector("#topology-plugin-success-toast");if(!t)return console.error("Could not find toast component!");let o=t.querySelector("span");o.textContent=e,new window.Toast(t).show()},error:e=>{let t=document.querySelector("#topology-plugin-error-toast");if(!t)return console.error("Could not find toast component!");let o=t.querySelector("span");o.textContent=e,new window.Toast(t).show()}};var g={},p=d("csrftoken");document.querySelector("form#images").addEventListener("submit",e=>l(void 0,null,function*(){e.preventDefault();try{let t=yield fetch("/"+basePath+"api/plugins/netbox_topology_views/images/save/",{method:"POST",body:JSON.stringify(g),headers:{"X-CSRFToken":p,"Content-Type":"application/json"}});if(!t.ok)throw new Error(yield t.text());u.success("Saved settings")}catch(t){console.dir(t),u.error(t.message)}}));document.querySelectorAll("form#images .dropdown-menu img").forEach(e=>{e.addEventListener("click",t=>{var c;if(!(t.currentTarget instanceof HTMLElement))return;let{dataset:{role:o,image:n}}=t.currentTarget;g[o]=n;let r=(c=t.currentTarget.closest(".dropdown"))==null?void 0:c.querySelector(`#dropdownMenuButton${o}`);r&&(r.innerHTML=`<img src="${n}" />`)})});})();
(()=>{var w=(o,t)=>()=>(o&&(t=o(o=0)),t);var f=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var l=(o,t,e)=>new Promise((r,s)=>{var c=n=>{try{a(e.next(n))}catch(i){s(i)}},g=n=>{try{a(e.throw(n))}catch(i){s(i)}},a=n=>n.done?r(n.value):Promise.resolve(n.value).then(c,g);a((e=e.apply(o,t)).next())});var u,d=w(()=>{u={success:o=>{let t=document.querySelector("#topology-plugin-success-toast");if(!t)return console.error("Could not find toast component!");let e=t.querySelector("span");e.textContent=o,new window.Toast(t).show()},error:o=>{let t=document.querySelector("#topology-plugin-error-toast");if(!t)return console.error("Could not find toast component!");let e=t.querySelector("span");e.textContent=o,new window.Toast(t).show()}}});var y=f(p=>{d();var m={};document.querySelector("form#images").addEventListener("submit",o=>l(null,null,function*(){o.preventDefault();try{let t=yield fetch("/"+basePath+"api/plugins/netbox_topology_views/images/save/",{method:"POST",body:JSON.stringify(m),headers:{"X-CSRFToken":window.CSRF_TOKEN,"Content-Type":"application/json"}});if(!t.ok)throw new Error(yield t.text());u.success(window.topologyI18n?.savedSettings??"Saved settings")}catch(t){console.dir(t),u.error(t.message)}}));document.querySelectorAll("form#images .dropdown-menu img").forEach(o=>{o.addEventListener("click",t=>{var c;if(!(t.currentTarget instanceof HTMLElement))return;let{dataset:{role:e,image:r}}=t.currentTarget;m[e]=r;let s=(c=t.currentTarget.closest(".dropdown"))==null?void 0:c.querySelector(`#dropdownMenuButton${e}`);s&&(s.innerHTML=`<img src="${r}" />`)})})});y();})();
@@ -1,6 +1,6 @@
{
"version": 3,
"sources": ["../../../static_dev/js/csrftoken.js", "../../../static_dev/js/toast.js", "../../../static_dev/js/images.js"],
"mappings": "mNAAO,GAAM,GAAY,AAAC,GAAS,CAC/B,GAAI,CAAC,SAAS,OAAQ,OAEtB,GAAI,GAAc,KACZ,EAAU,SAAS,OAAO,MAAM,KAEtC,OAAS,GAAI,EAAG,EAAI,EAAQ,OAAQ,IAAK,CACrC,GAAM,GAAS,EAAQ,GAAG,OAE1B,GAAI,EAAO,UAAU,EAAG,EAAK,OAAS,KAAO,EAAO,IAAK,CACrD,EAAc,mBAAmB,EAAO,UAAU,EAAK,OAAS,IAChE,OAIR,MAAO,ICfJ,GAAM,GAAQ,CACjB,QAAS,AAAC,GAAY,CAClB,GAAM,GAAK,SAAS,cAAc,kCAClC,GAAI,CAAC,EAAI,MAAO,SAAQ,MAAM,mCAC9B,GAAM,GAAU,EAAG,cAAc,QACjC,EAAQ,YAAc,EAEtB,AADc,GAAI,QAAO,MAAM,GACzB,QAEV,MAAO,AAAC,GAAY,CAChB,GAAM,GAAK,SAAS,cAAc,gCAClC,GAAI,CAAC,EAAI,MAAO,SAAQ,MAAM,mCAC9B,GAAM,GAAU,EAAG,cAAc,QACjC,EAAQ,YAAc,EAEtB,AADc,GAAI,QAAO,MAAM,GACzB,SCZd,GAAM,GAAU,GACV,EAAY,EAAU,aAE5B,SAAS,cAAc,eAAe,iBAAiB,SAAU,AAAO,GAAM,0BAC1E,EAAE,iBACF,GAAI,CACA,GAAM,GAAM,KAAM,OAAM,IAAM,SAAW,iDAAkD,CACvF,OAAQ,OACR,KAAM,KAAK,UAAU,GACrB,QAAS,CACL,cAAe,EACf,eAAgB,sBAIxB,GAAI,CAAC,EAAI,GAAI,KAAM,IAAI,OAAM,KAAM,GAAI,QACvC,EAAM,QAAQ,wBACT,EAAP,CACE,QAAQ,IAAI,GACZ,EAAM,MAAM,EAAI,aAIxB,SAAS,iBAAiB,kCAAkC,QAAQ,AAAC,GAAO,CACxE,EAAG,iBAAiB,QAAS,AAAC,GAAM,CA3BxC,MA4BQ,GAAI,CAAE,GAAE,wBAAyB,cAAc,OAC/C,GAAM,CACF,QAAS,CAAE,OAAM,UACjB,EAAE,cAEN,EAAQ,GAAQ,EAEhB,GAAM,GAAS,KAAE,cACZ,QAAQ,eADE,cAET,cAAc,sBAAsB,KAC1C,AAAI,GAAQ,GAAO,UAAY,aAAa",
"names": []
"sources": ["../../../static_dev/js/toast.js", "../../../static_dev/js/images.js"],
"mappings": "oTAAA,IAAaA,EAAbC,EAAAC,EAAA,KAAaF,EAAQ,CACjB,QAAUG,GAAY,CAClB,IAAMC,EAAK,SAAS,cAAc,gCAAgC,EAClE,GAAI,CAACA,EAAI,OAAO,QAAQ,MAAM,iCAAiC,EAC/D,IAAMC,EAAUD,EAAG,cAAc,MAAM,EACvCC,EAAQ,YAAcF,EACR,IAAI,OAAO,MAAMC,CAAE,EAC3B,KAAK,CACf,EACA,MAAQD,GAAY,CAChB,IAAMC,EAAK,SAAS,cAAc,8BAA8B,EAChE,GAAI,CAACA,EAAI,OAAO,QAAQ,MAAM,iCAAiC,EAC/D,IAAMC,EAAUD,EAAG,cAAc,MAAM,EACvCC,EAAQ,YAAcF,EACR,IAAI,OAAO,MAAMC,CAAE,EAC3B,KAAK,CACf,CACJ,ICjBA,IAAAE,EAAAC,EAAAC,GAAA,CAAAC,IAEA,IAAMC,EAAU,CAAC,EAEjB,SAAS,cAAc,aAAa,EAAE,iBAAiB,SAAiBC,GAAMC,EAAA,sBAC1ED,EAAE,eAAe,EACjB,GAAI,CACA,IAAME,EAAM,MAAM,MAAM,IAAM,SAAW,iDAAkD,CACvF,OAAQ,OACR,KAAM,KAAK,UAAUH,CAAO,EAC5B,QAAS,CACL,cAAe,OAAO,WACtB,eAAgB,kBACpB,CACJ,CAAC,EAED,GAAI,CAACG,EAAI,GAAI,MAAM,IAAI,MAAM,MAAMA,EAAI,KAAK,CAAC,EAC7CC,EAAM,QAAQ,gBAAgB,CAClC,OAASC,EAAK,CACV,QAAQ,IAAIA,CAAG,EACfD,EAAM,MAAMC,EAAI,OAAO,CAC3B,CACJ,EAAC,EAED,SAAS,iBAAiB,gCAAgC,EAAE,QAASC,GAAO,CACxEA,EAAG,iBAAiB,QAAUL,GAAM,CAzBxC,IAAAM,EA0BQ,GAAI,EAAEN,EAAE,yBAAyB,aAAc,OAC/C,GAAM,CACF,QAAS,CAAE,KAAAO,EAAM,MAAAC,CAAM,CAC3B,EAAIR,EAAE,cAEND,EAAQQ,CAAI,EAAIC,EAEhB,IAAMC,GAASH,EAAAN,EAAE,cACZ,QAAQ,WAAW,IADT,YAAAM,EAET,cAAc,sBAAsBC,CAAI,IAC1CE,IAAQA,EAAO,UAAY,aAAaD,CAAK,OACrD,CAAC,CACL,CAAC",
"names": ["toast", "init_toast", "__esmMin", "message", "el", "content", "require_images", "__commonJSMin", "exports", "init_toast", "mapping", "e", "__async", "res", "toast", "err", "el", "_a", "role", "image", "button"]
}
+68 -1
View File
@@ -1,12 +1,13 @@
#visgraph {
height: 64vh;
border: 1px solid #ced4da
}
html[data-netbox-color-mode=dark] #visgraph {
background-color: #212529;
border: 1px solid #495057
}
.image-dropdown img {
width: 64px;
height: 64px;
@@ -25,3 +26,69 @@ html[data-netbox-color-mode=dark] #visgraph {
cursor: pointer;
}
}
.rack-elevation-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(34rem, 1fr));
gap: 1rem;
}
.rack-card {
border: 1px solid var(--tblr-border-color, #ced4da);
border-radius: .4rem;
background: var(--tblr-bg-surface, #fff);
padding: 1rem;
}
.rack-card > header { display: flex; justify-content: space-between; margin-bottom: .75rem; }
.rack-faces { display: grid; grid-template-columns: 1fr 1fr; gap: .75rem; }
.rack-face-title { text-align: center; font-size: .75rem; text-transform: uppercase; margin-bottom: .25rem; }
.rack-frame { display: flex; height: calc(var(--rack-units) * 22px); min-height: 280px; border: 4px solid #3b4654; background: repeating-linear-gradient(to top, rgba(127,127,127,.14) 0, rgba(127,127,127,.14) 1px, transparent 1px, transparent calc(100% / var(--rack-units))); }
.rack-unit-labels { width: 2rem; display: flex; flex-direction: column; justify-content: space-around; font-size: .55rem; text-align: center; color: var(--tblr-secondary, #667382); }
.rack-device-area { position: relative; flex: 1; border-left: 1px solid #3b4654; }
.rack-device { position: absolute; left: 3px; right: 3px; min-height: 2px; overflow: hidden; padding: 2px 6px; border: 2px solid #1685fc; border-radius: 3px; background: #eef6ff; color: #132238; font-size: .78rem; line-height: 1.15; text-decoration: none; }
.rack-device:hover { min-height: 2.8rem; overflow: visible; filter: brightness(1.25); color: #fff; z-index: 3; }
.rack-device:hover span { white-space: normal; }
.rack-device span, .rack-device small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rack-device small { font-size: .6rem; opacity: .8; }
.rack-topology { position: relative; min-height: 18rem; overflow: auto; padding: 1rem; background: var(--tblr-bg-surface-secondary, rgba(127,127,127,.05)); }
.rack-topology-lines { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; }
.rack-topology-columns { position: relative; z-index: 2; display: flex; align-items: flex-start; justify-content: space-around; gap: 5rem; min-width: max-content; pointer-events: none; }
.rack-topology-column { display: flex; flex-direction: column; gap: .75rem; width: 15rem; }
.rack-topology-column h4 { text-align: center; font-size: .85rem; }
.rack-topology-node { display: block; padding: .55rem .75rem; border: 2px solid var(--node-color); border-radius: .35rem; background: var(--tblr-bg-surface, #fff); color: inherit; text-decoration: none; box-shadow: 0 2px 6px rgba(0,0,0,.12); cursor: grab; touch-action: none; user-select: none; pointer-events: auto; }
.rack-topology-node.is-dragging { cursor: grabbing; z-index: 5; }
.rack-topology-node:hover { color: inherit; filter: brightness(.95); }
.rack-topology-node strong, .rack-topology-node small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rack-topology-node small { opacity: .7; }
.rack-topology-edge { fill: none; stroke-width: 3; opacity: .8; pointer-events: stroke; cursor: pointer; transition: opacity .12s, stroke .12s, filter .12s, stroke-width .12s; }
.rack-topology-edge.is-highlighted { stroke: var(--topology-highlight-color, #16a34a) !important; stroke-width: 5; opacity: 1; filter: drop-shadow(0 0 5px var(--topology-highlight-color, #16a34a)); }
.rack-topology-edge.is-dimmed { opacity: .12; }
.rack-topology-tooltip { display: none; position: absolute; z-index: 10; width: max-content; max-width: 28rem; padding: .65rem .8rem; border: 1px solid var(--tblr-border-color, #ced4da); border-radius: .35rem; background: var(--tblr-bg-surface, #fff); box-shadow: 0 4px 18px rgba(0,0,0,.25); pointer-events: none; }
.rack-topology-tooltip.is-visible { display: block; }
.rack-topology-tooltip > strong, .rack-topology-tooltip > span, .rack-topology-tooltip li span, .rack-topology-tooltip li small { display: block; }
.rack-topology-tooltip ul { margin: .4rem 0 0; padding: 0; list-style: none; }
.rack-topology-tooltip li + li { margin-top: .45rem; padding-top: .45rem; border-top: 1px solid var(--tblr-border-color, #ced4da); }
.rack-topology-tooltip small { opacity: .65; }
.rack-cable-count { min-width: 2rem; margin-left: .35rem; background-color: #52606d !important; color: #fff !important; text-align: center; }
.rack-frame {
border-color: #718096;
background-color: #fff;
}
.rack-topology-device-list { display: flex; flex-direction: column; gap: 40px; }
.rack-topology-edge.is-wireless { stroke-dasharray: 7 7; stroke-linecap: round; }
#rack-topology-card:fullscreen { margin: 0 !important; border: 0; border-radius: 0; background: var(--tblr-bg-surface, #fff); display: flex; flex-direction: column; overflow: hidden; }
#rack-topology-card:fullscreen .card-body { min-height: 0; flex: 1; overflow: hidden; }
#rack-topology-card:fullscreen .rack-topology { height: calc(100vh - 5.5rem); }
html[data-bs-theme="dark"], body[data-bs-theme="dark"], html[data-netbox-color-mode="dark"] {
.rack-frame { border-color: #3b4654; background-color: #212b36; }
.rack-device { background: #162e45; color: #fff; }
}
@media (max-width: 700px) {
.rack-elevation-grid { grid-template-columns: 1fr; }
.rack-faces { grid-template-columns: 1fr; }
}
@@ -1,17 +0,0 @@
export const getCookie = (name) => {
if (!document.cookie) return
let cookieValue = null
const cookies = document.cookie.split(';')
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim()
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === name + '=') {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
break
}
}
return cookieValue
}
+427 -17
View File
@@ -1,6 +1,43 @@
import { DataSet } from 'vis-data/esnext'
import { Network } from 'vis-network/esnext'
import { getCookie } from './csrftoken.js'
function generatePortSVG(text) {
// pre-calculate text width
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const textEl = document.createElementNS('http://www.w3.org/2000/svg', 'text');
const fontFamily = 'helvetica';
const fontSize = 14;
textEl.textContent = text;
textEl.setAttribute('font-family', fontFamily);
textEl.setAttribute('font-size', fontSize + 'px');
svg.appendChild(textEl);
document.body.appendChild(svg);
const textWidth = textEl.getComputedTextLength();
textEl.remove();
svg.remove();
const rectPadding = 2;
const rectBorderWidth = 2;
const rectX = rectBorderWidth / 2;
const rectY = rectBorderWidth / 2;
const rectWidth = textWidth + rectBorderWidth + rectPadding * 2;
const rectHeight = fontSize + rectBorderWidth + rectPadding * 2;
const svgHeight = rectHeight + rectY + rectBorderWidth / 2;
const svgWidth = rectWidth + rectX + rectBorderWidth / 2;
const textX = svgWidth / 2 ;
const textY = svgHeight / 2;
// generate SVG
return 'data:image/svg+xml;charset=utf-8,' +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="' + (svgWidth) + '" height="' + (svgHeight) + '">' +
'<rect x="' + rectX + '" y="' + rectY + '" rx="4" ry="4" width="' + (rectWidth) + '" height="' + (rectHeight) + '" fill="#ffdf3f" stroke="#ffc93f" stroke-width="' + (rectBorderWidth) + '" style="opacity:0.5"/>' +
'<text x="' + textX + '" y="' + textY + '" font-family="' + fontFamily + '" font-size="' + (fontSize) + '" fill="black" text-anchor="middle" dominant-baseline="middle">' + text + '</text>' +
'</svg>'
)
}
const options = {
interaction: {
@@ -36,9 +73,6 @@ const options = {
}
}
// Load CSRF token
const csrftoken = getCookie('csrftoken')
// Render vis graph
let graph = null // vis graph instance
@@ -66,26 +100,183 @@ const coordSaveCheckbox = document.querySelector('#id_save_coords')
const edges = new DataSet(
topologyData.edges.map((node) => ({
...node,
title: htmlTitle(node.title)
title: htmlTitle(node.title),
...(node.drawTerminationLabel && {
arrows: {
from: {
enabled: true,
type: "image",
src: generatePortSVG(node.cable_a_name)
},
to: {
enabled: true,
type: "image",
src: generatePortSVG(node.cable_b_name)
}
}
})
}))
)
const group_sites = topologyData.options.group_sites
const group_locations = topologyData.options.group_locations
const group_racks = topologyData.options.group_racks
const group_virtualchassis = topologyData.options.group_virtualchassis
const gridSize = parseInt(topologyData.options.grid_size[0]);
var dragMode = false;
graph = new Network(container, { nodes, edges }, options)
graph.fit()
function getGridPosition(nodeId, gridSize) {
x = graph.getPosition(nodeId).x;
y = graph.getPosition(nodeId).y;
if(x >= 0) {
if((x % gridSize) > (gridSize / 2)) {
x += gridSize;
}
}
else {
if((-x % gridSize) > (gridSize / 2)) {
x -= gridSize;
}
}
x = x - x % gridSize;
if(y >= 0) {
if((y % gridSize) > (gridSize / 2)) {
y += gridSize;
}
}
else {
if((-y % gridSize) > (gridSize / 2)) {
y -= gridSize;
}
}
y = y - y % gridSize;
return {
x: x,
y: y
};
}
function drawGrid(canvascontext) {
// Canvas can be zoomed. It then contains more or less virtual pixels than the real number of pixels
const zoomFactor = graph.getScale() * window.devicePixelRatio;
const virtualWidth = canvascontext.canvas.width / zoomFactor;
const virtualHeight = canvascontext.canvas.height / zoomFactor;
// Canvas can be moved. Get the center of the virtual canvas. Take the grid into account
const virtualCenter = graph.getViewPosition();
const rasterizedCenterX = virtualCenter.x - virtualCenter.x % gridSize;
const rasterizedCenterY = virtualCenter.y - virtualCenter.y % gridSize;
// Calculate virtual space for the grid
const hSpace = (virtualWidth / 2) - (virtualWidth / 2) % gridSize + gridSize;
const vSpace = (virtualHeight / 2) - (virtualHeight / 2) % gridSize + gridSize;
// Calculate virtual position for the grid
const left = rasterizedCenterX - gridSize - hSpace;
const right = rasterizedCenterX + gridSize + hSpace;
const top = rasterizedCenterY - gridSize - vSpace;
const bottom = rasterizedCenterY + gridSize + vSpace;
// Draw grid
canvascontext.beginPath();
for (let x = left; x < right; x += gridSize) {
canvascontext.moveTo(x, top);
canvascontext.lineTo(x, bottom);
}
for (let y = top; y < bottom; y += gridSize) {
canvascontext.moveTo(left, y);
canvascontext.lineTo(right, y);
}
canvascontext.strokeStyle = '#777777';
canvascontext.stroke();
}
function drawGridSnapHint(canvascontext) {
// Draw grid hinting line and circle
if(gridSize > 0 && dragMode == true && graph.getSelectedNodes().length > 0) {
for(i = 0; i < graph.getSelectedNodes().length; i++) {
id = graph.getSelectedNodes()[i];
if(window.nodes.get(id).x != graph.getPosition(id).x || window.nodes.get(id).y != graph.getPosition(id).y) {
pos = getGridPosition(graph.getSelectedNodes()[i], gridSize);
canvascontext.beginPath();
canvascontext.arc(graph.getPosition(graph.getSelectedNodes()[i]).x, graph.getPosition(graph.getSelectedNodes()[i]).y, 5, 0, 2 * Math.PI);
canvascontext.fillStyle = '#FF3D3D';
canvascontext.fill();
canvascontext.beginPath();
canvascontext.moveTo(graph.getPosition(graph.getSelectedNodes()[i]).x, graph.getPosition(graph.getSelectedNodes()[i]).y);
canvascontext.lineTo(pos.x, pos.y);
canvascontext.strokeStyle = '#FF3D3D';
canvascontext.stroke();
canvascontext.beginPath();
canvascontext.arc(pos.x, pos.y, 10, 0, 2 * Math.PI);
canvascontext.fillStyle = '#9C0000';
canvascontext.fill();
}
}
}
}
graph.on('dragStart', (params) => {
dragMode = true;
})
graph.on('dragEnd', (params) => {
if (coordSaveCheckbox == null) return
if (!coordSaveCheckbox.checked) return
dragMode = false;
// Place icon on the grid
if(gridSize > 0 && graph.getSelectedNodes().length > 0) {
for(i = 0; i < graph.getSelectedNodes().length; i++) {
id = graph.getSelectedNodes()[i];
if(window.nodes.get(id).x != graph.getPosition(id).x || window.nodes.get(id).y != graph.getPosition(id).y) {
pos = getGridPosition(graph.getSelectedNodes()[i], gridSize);
window.nodes.update({id: graph.getSelectedNodes()[i], x: pos.x, y: pos.y});
}
}
}
if (coordSaveCheckbox.options[coordSaveCheckbox.selectedIndex].text != "Yes") return
Promise.allSettled(
Object.entries(graph.getPositions(params.nodes)).map(
async ([nodeId, nodePosition]) => {
window.nodes.update({id: parseInt(nodeId), physics: false, x: nodePosition.x, y: nodePosition.y});
if(!isNaN(parseInt(nodeId))) {
nodeKey = parseInt(nodeId);
}
else {
nodeKey = nodeId;
}
try {
window.nodes.update({id: nodeKey, physics: false, x: nodePosition.x, y: nodePosition.y});
}
catch (e) {
console.log([
'Error while executing window.nodes.update()',
'nodeId: ' + nodeId,
'nodeKey: ' + nodeKey,
'x: ' + nodePosition.x,
'y: ' + nodePosition.y
]);
console.log(e);
}
const res = await fetch(
'/' + basePath + 'api/plugins/netbox_topology_views/save-coords/save_coords/',
{
method: 'PATCH',
headers: {
'X-CSRFToken': csrftoken,
'X-CSRFToken': window.CSRF_TOKEN,
Accept: 'application/json',
'Content-Type': 'application/json'
},
@@ -97,8 +288,6 @@ const coordSaveCheckbox = document.querySelector('#id_save_coords')
})
}
)
console.log(nodeId, res.status, res.statusText)
}
)
)
@@ -116,6 +305,227 @@ const coordSaveCheckbox = document.querySelector('#id_save_coords')
})
}
})
graph.on('beforeDrawing', (canvascontext) => {
if (gridSize > 0) {
drawGrid(canvascontext);
}
})
graph.on('afterDrawing', (canvascontext) => {
allRectangles = [];
if(group_sites != null && group_sites == 'on') { drawGroupRectangles(canvascontext, groupedNodeSites, siteRectParams); }
if(group_locations != null && group_locations == 'on') { drawGroupRectangles(canvascontext, groupedNodeLocations, locationRectParams); }
if(group_racks != null && group_racks == 'on') { drawGroupRectangles(canvascontext, groupedNodeRacks, rackRectParams); }
if(group_virtualchassis != null && group_virtualchassis == 'on') { drawGroupRectangles(canvascontext, groupedNodeVirtualchassis, virtualchassisRectParams); }
drawGridSnapHint(canvascontext);
})
graph.on('click', (canvascontext) => {
allRectangles.forEach(key => {
// Is the mouse pointer inside of the current rectangle?
if(canvascontext.pointer.canvas.x > (key.x1 - key.border / 2 - 3) && canvascontext.pointer.canvas.x < (key.x2 + key.border / 2 + 3)
&& canvascontext.pointer.canvas.y > (key.y1 - key.border / 2 - 3) && canvascontext.pointer.canvas.y < (key.y2 + key.border / 2 + 3)) {
// We just want to react when the border has been clicked, not the whole rectangle
if (canvascontext.pointer.canvas.x < (key.x1 + key.border / 2 + 3) || canvascontext.pointer.canvas.x > (key.x2 - key.border / 2 - 3)
|| canvascontext.pointer.canvas.y < (key.y1 + key.border / 2 + 3) || canvascontext.pointer.canvas.y > (key.y2 - key.border / 2 - 3)) {
// Generate an array of affected nodes in order to pass it to the select.Nodes() function
let arr = [];
if(key.category == "Site") {
groupedNodeSites.forEach(subArray => {
subArray.forEach(element => {
if (element[1] == key.id) {
arr.push(element[0]);
}
});
});
}
if(key.category == "Location") {
groupedNodeLocations.forEach(subArray => {
subArray.forEach(element => {
if (element[1] === key.id) {
arr.push(element[0]);
}
});
});
}
if(key.category == "Rack") {
groupedNodeRacks.forEach(subArray => {
subArray.forEach(element => {
if (element[1] === key.id) {
arr.push(element[0]);
}
});
});
}
if(key.category == "Virtual Chassis") {
groupedNodeVirtualchassis.forEach(subArray => {
subArray.forEach(element => {
if (element[1] === key.id) {
arr.push(element[0]);
}
});
});
}
graph.selectNodes(arr);
}
}
});
})
// Add information on which node belongs to which group (site/location/rack/virtualchassis).
// Create an array for each group in order to loop through that arrays later
function combineNodeInfo(typeId, type) {
let nodesArray = [];
// Extract node ids and node type ids from all nodes
for (let [key, value] of nodes._data) {
if (value[typeId] != undefined) {
nodesArray.push([value.id, value[typeId], value[type], value.label_num_lines]);
}
}
// Split single array above into arrays grouped by node id
let groupedNodeArray = nodesArray.reduce((acc, value) => {
let key = value[1]; // node id
acc[key] = acc[key] || [];
acc[key].push(value);
return acc;
}, {});
return Object.values(groupedNodeArray);
}
var allRectangles = [];
/* Draw a single rectangle with given parameters
rectangle expects an object that consists of the following keys:
ctx: canvas context on which the rectangle should be drawn
x: x-coordinate of top left point of the rectangle
y: y-coordinate of top left point of the rectangle
width: width of rectangle
height: height of rectangle
lineWidth: border width
color: border color
text: a string to be placed where you want it to be
textPaddingX: x-position of the text
textPaddingY: y-position of the text
font: text font */
function drawGroupRectangle(rectangle) {
// Draw rectangle
rectangle.ctx.beginPath();
rectangle.ctx.lineWidth = rectangle.lineWidth;
rectangle.ctx.strokeStyle = rectangle.color;
rectangle.ctx.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
rectangle.ctx.stroke();
// Draw text
rectangle.ctx.font = rectangle.font;
rectangle.ctx.fillStyle = rectangle.color;
rectangle.ctx.fillText(rectangle.text, rectangle.x + rectangle.textPaddingX, rectangle.y + rectangle.textPaddingY);
allRectangles.push({category: rectangle.category, id: rectangle.id, x1: rectangle.x, y1: rectangle.y, x2: rectangle.x + rectangle.width, y2: rectangle.y + rectangle.height, border: rectangle.lineWidth})
}
/* Draw all rectangles of a given group (site/location//virtualchassis)
rectParams expects an object that consists of the following keys:
lineWidth: border width (string)
color: border color (string)
paddingX: rectangle x-padding, calculated from the center of a node (int)
paddingY: rectangle y-padding, calculated from the center of a node (int)
textPaddingX: text x-padding, calculated from the lower left point of the text (int)
textPaddingY: text y-padding, calculated from the lower left point of the text (int)
font: css-like font size and font (string) */
function drawGroupRectangles(canvascontext, groupedNodes, rectParams) {
for(let value of Object.entries(groupedNodes)) {
const rectangles = [];
const xValues = [];
const yValues = [];
const yValuesWithLabel = [];
const labelLineHeight = 16;
// Get coordinates for every node in a given group
for(let val of value[1]) {
xValues.push(graph.getPosition(val[0]).x);
yValues.push(graph.getPosition(val[0]).y);
yValuesWithLabel.push(yValues[yValues.length -1] + val[3] * labelLineHeight);
}
const minX = Math.min(...xValues);
const maxX = Math.max(...xValues);
const minY = Math.min(...yValues);
const maxY = Math.max(...yValuesWithLabel);
const rectX = minX - rectParams.paddingX;
const rectY = minY - rectParams.paddingY;
const rectSizeX = maxX - minX + 2*rectParams.paddingX;
const rectSizeY = maxY - minY + 2*rectParams.paddingY;
rectangles.push({
ctx: canvascontext,
x: rectX,
y: rectY,
width: rectSizeX,
height: rectSizeY,
lineWidth: rectParams.lineWidth,
color: rectParams.color,
text: value[1][0][2],
textPaddingX: rectParams.textPaddingX,
textPaddingY: rectParams.textPaddingY,
font: rectParams.font,
id: value[1][0][1],
category: rectParams.category
});
rectangles.forEach(function(rectangle) {
drawGroupRectangle(rectangle);
});
}
}
let groupedNodeSites = combineNodeInfo('site_id', 'site');
let siteRectParams = {
lineWidth: "5",
color: "red",
paddingX: 84,
paddingY: 84,
textPaddingX: 8,
textPaddingY: -8,
font: "14px helvetica",
category: "Site"
}
let groupedNodeLocations = combineNodeInfo('location_id', 'location');
let locationRectParams = {
lineWidth: "5",
color: "#337ab7",
paddingX: 77,
paddingY: 77,
textPaddingX: 22,
textPaddingY: 29,
font: "14px helvetica",
category: "Location"
}
let groupedNodeRacks = combineNodeInfo('rack_id', 'rack');
let rackRectParams = {
lineWidth: "5",
color: "green",
paddingX: 70,
paddingY: 70,
textPaddingX: 15,
textPaddingY: 36,
font: "14px helvetica",
category: "Rack"
}
let groupedNodeVirtualchassis = combineNodeInfo('virtual_chassis_id', 'virtual_chassis');
let virtualchassisRectParams = {
lineWidth: "5",
color: "orange",
paddingX: 63,
paddingY: 63,
textPaddingX: 8,
textPaddingY: 43,
font: "14px helvetica",
category: "Virtual Chassis"
}
})()
// Download Graph
@@ -157,12 +567,12 @@ function performXmlDownload() {
if (curr_url.includes(sites_prefix)) {
var site_id = curr_url.split(sites_prefix)[1];
site_id = site_id.split('/')[0]
xml_search_options = 'site_id=' + site_id + '&show_cables=on&show_unconnected=on'
xml_search_options = 'site_id=' + site_id + '&show_cables=True&show_unconnected=True'
}
else if (curr_url.includes(location_prefix)) {
var location_id = curr_url.split(location_prefix)[1];
location_id = location_id.split('/')[0]
xml_search_options = 'location_id=' + location_id + '&show_cables=on&show_unconnected=on'
xml_search_options = 'location_id=' + location_id + '&show_cables=True&show_unconnected=True'
}
}
else {
@@ -191,17 +601,17 @@ const observer = new MutationObserver((mutations) =>
if (
!graph ||
mutation.type !== 'attributes' ||
mutation.attributeName !== 'data-netbox-color-mode' ||
mutation.attributeName !== 'data-bs-theme' ||
!(mutation.target instanceof HTMLElement)
)
return
const { netboxColorMode } = mutation.target.dataset
const netboxColorMode = mutation.target.dataset.bsTheme
options.nodes.font.color = netboxColorMode === 'dark' ? '#fff' : '#000'
graph.setOptions(options)
})
)
observer.observe(document.documentElement, {
observer.observe(document.body, {
attributes: true,
attributeFilter: ['data-netbox-color-mode']
attributeFilter: ['data-bs-theme']
})
@@ -1,8 +1,6 @@
import { getCookie } from './csrftoken.js'
import { toast } from './toast.js'
const mapping = {}
const csrftoken = getCookie('csrftoken')
document.querySelector('form#images').addEventListener('submit', async (e) => {
e.preventDefault()
@@ -11,13 +9,13 @@ document.querySelector('form#images').addEventListener('submit', async (e) => {
method: 'POST',
body: JSON.stringify(mapping),
headers: {
'X-CSRFToken': csrftoken,
'X-CSRFToken': window.CSRF_TOKEN,
'Content-Type': 'application/json'
}
})
if (!res.ok) throw new Error(await res.text())
toast.success('Saved settings')
toast.success(window.topologyI18n?.savedSettings ?? 'Saved settings')
} catch (err) {
console.dir(err)
toast.error(err.message)
File diff suppressed because it is too large. Load diff
@@ -1,22 +1,22 @@
{
"private": true,
"name": "netbox_topology_views",
"version": "3.7.0",
"version": "4.5.1",
"scripts": {
"bundle": "node bundle.js",
"bundle:styles": "node bundle.js --styles",
"bundle:scripts": "node bundle.js --scripts"
},
"dependencies": {
"vis-data": "^7.1.6",
"vis-network": "^9.1.6",
"vis-util": "^5.0.3"
"vis-data": "^7.1.9",
"vis-network": "^9.1.9",
"vis-util": "^5.0.7"
},
"devDependencies": {
"@egjs/hammerjs": "^2.0.0",
"component-emitter": "^1.3.0",
"esbuild": "^0.12.24",
"esbuild-sass-plugin": "^1.5.2",
"esbuild": "^0.25.0",
"esbuild-sass-plugin": "^3.3.1",
"keycharm": "^0.4.0",
"timsort": "^0.3.0",
"uuid": "^8.0.0"
+45 -3
View File
@@ -1,19 +1,62 @@
import django_tables2 as tables
from django.utils.translation import gettext_lazy as _
from netbox.tables import NetBoxTable, ChoiceFieldColumn
from netbox_topology_views.models import CoordinateGroup, Coordinate
from netbox_topology_views.models import CoordinateGroup, Coordinate, CircuitCoordinate, PowerPanelCoordinate, PowerFeedCoordinate
class CoordinateGroupListTable(NetBoxTable):
name = tables.Column(
linkify=True
)
devices = tables.Column()
devices = tables.Column(verbose_name=_('Devices'))
class Meta(NetBoxTable.Meta):
model = CoordinateGroup
fields = ('pk', 'id', 'name', 'description', 'devices')
default_columns = ('name', 'description', 'devices')
class CircuitCoordinateListTable(NetBoxTable):
group = tables.Column(
linkify=True
)
device = tables.Column(
linkify=True
)
class Meta(NetBoxTable.Meta):
model = CircuitCoordinate
fields = ('pk', 'id', 'group', 'device', 'x', 'y')
default_columns = ('id', 'group', 'device', 'x', 'y')
class PowerPanelCoordinateListTable(NetBoxTable):
group = tables.Column(
linkify=True
)
device = tables.Column(
linkify=True
)
class Meta(NetBoxTable.Meta):
model = PowerPanelCoordinate
fields = ('pk', 'id', 'group', 'device', 'x', 'y')
default_columns = ('id', 'group', 'device', 'x', 'y')
class PowerFeedCoordinateListTable(NetBoxTable):
group = tables.Column(
linkify=True
)
device = tables.Column(
linkify=True
)
class Meta(NetBoxTable.Meta):
model = PowerFeedCoordinate
fields = ('pk', 'id', 'group', 'device', 'x', 'y')
default_columns = ('id', 'group', 'device', 'x', 'y')
class CoordinateListTable(NetBoxTable):
group = tables.Column(
linkify=True
@@ -27,4 +70,3 @@ class CoordinateListTable(NetBoxTable):
model = Coordinate
fields = ('pk', 'id', 'group', 'device', 'x', 'y')
default_columns = ('id', 'group', 'device', 'x', 'y')
-20
View File
@@ -1,20 +0,0 @@
from extras.plugins import PluginTemplateExtension
from django.conf import settings
from packaging import version
NETBOX_CURRENT_VERSION = version.parse(settings.VERSION)
class SiteButtons(PluginTemplateExtension):
model = 'dcim.site'
def buttons(self):
return self.render('netbox_topology_views/site_button.html')
class LocationButtons(PluginTemplateExtension):
model = 'dcim.location'
def buttons(self):
return self.render('netbox_topology_views/location_button.html')
template_extensions = [SiteButtons, LocationButtons]
@@ -0,0 +1,43 @@
{% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %}
{% load plugins %}
{% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">
<div class="card">
<h5 class="card-header">
{% trans "Coordinates" %}
</h5>
<div class="card-body">
<table class="table table-hover attr-table">
<tr>
<th scope="row">{% trans "Group" %}</th>
<td>{{ object.group|linkify }}</td>
</tr>
<tr>
<th scope="row">{% trans "Circuit" %}</th>
<td>{{ object.device|linkify }}</td>
</tr>
<tr>
<th scope="row">{% trans "X-Coordinate" %}</th>
<td>{{ object.x }}</td>
</tr>
<tr>
<th scope="row">{% trans "Y-Coordinate" %}</th>
<td>{{ object.y }}</td>
</tr>
</table>
</div>
</div>
{% plugin_left_page object %}
</div>
<div class="col col-md-6">
{% include 'inc/panels/custom_fields.html' %}
{% plugin_right_page object %}
</div>
</div>
{% endblock content %}
@@ -0,0 +1,4 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Add new Circuit Coordinates" %}{% endblock title %}
@@ -0,0 +1,4 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Edit Circuit Coordinates" %}{% endblock title %}
@@ -0,0 +1,4 @@
{% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}{% trans "Circuit Coordinates" %}{% endblock title %}
@@ -1,32 +1,33 @@
{% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %}
{% load plugins %}
{% block title %}Topology Views Coordinates{% endblock title %}
{% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">
<div class="card">
<h5 class="card-header">
Coordinates
{% trans "Coordinates" %}
</h5>
<div class="card-body">
<table class="table table-hover attr-table">
<tr>
<th scope="row">Group</th>
<th scope="row">{% trans "Group" %}</th>
<td>{{ object.group|linkify }}</td>
</tr>
<tr>
<th scope="row">Device</th>
<th scope="row">{% trans "Device" %}</th>
<td>{{ object.device|linkify }}</td>
</tr>
<tr>
<th scope="row">X-Coordinate</th>
<th scope="row">{% trans "X-Coordinate" %}</th>
<td>{{ object.x }}</td>
</tr>
<tr>
<th scope="row">Y-Coordinate</th>
<th scope="row">{% trans "Y-Coordinate" %}</th>
<td>{{ object.y }}</td>
</tr>
</table>
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Add new Device Coordinates{% endblock title %}
{% block title %}{% trans "Add new Device Coordinates" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Edit Device Coordinates{% endblock title %}
{% block title %}{% trans "Edit Device Coordinates" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}Device Coordinates{% endblock title %}
{% block title %}{% trans "Device Coordinates" %}{% endblock title %}
@@ -1,25 +1,26 @@
{% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %}
{% load plugins %}
{% load render_table from django_tables2 %}
{% block title %}Topology Views Coordinate Group{% endblock title %}
{% block title %}{% trans "Topology Views Coordinate Group" %}{% endblock title %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">
<div class="card">
<h5 class="card-header">
Coordinate Group
{% trans "Coordinate Group" %}
</h5>
<div class="card-body">
<table class="table table-hover attr-table">
<tr>
<th scope="row">Name</th>
<th scope="row">{% trans "Name" %}</th>
<td>{{ object.name }}</td>
</tr>
<tr>
<th scope="row">Description</th>
<th scope="row">{% trans "Description" %}</th>
<td>{{ object.description|placeholder }}</td>
</tr>
</table>
@@ -32,10 +33,34 @@
{% plugin_right_page object %}
</div>
</div>
<div class="row">
<div class="row mb-3">
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">Coordinates</h5>
<h5 class="card-header">{% trans "Circuit Coordinates" %}</h5>
<div class="card-body table-responsive">
{% render_table circuitcoordinates_table %}
</div>
</div>
</div>
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">{% trans "Power Panel Coordinates" %}</h5>
<div class="card-body table-responsive">
{% render_table powerpanelcoordinates_table %}
</div>
</div>
</div>
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">{% trans "Power Feed Coordinates" %}</h5>
<div class="card-body table-responsive">
{% render_table powerfeedcoordinates_table %}
</div>
</div>
</div>
<div class="col col-md-12">
<div class="card">
<h5 class="card-header">{% trans "Device Coordinates" %}</h5>
<div class="card-body table-responsive">
{% render_table coordinates_table %}
</div>
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Add a new Coordinate Group{% endblock title %}
{% block title %}{% trans "Add a new Coordinate Group" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Edit Coordinate Group{% endblock title %}
{% block title %}{% trans "Edit Coordinate Group" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}Coordinate Groups{% endblock title %}
{% block title %}{% trans "Coordinate Groups" %}{% endblock title %}
@@ -1,44 +0,0 @@
{% load static %}
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/vendor.css' %}">
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/app.css' %}">
<div class="modal-header">
<h5 class="modal-title">Topology Views</h5>
<div class="controls">
<div class="control-group">
{% block extra_controls %}{% endblock %}
<a id="btnDownloadXml" class="btn btn-sm btn-info" href="#">
<i class="mdi mdi-download"></i>
Download XML
</a>
<a id="btnDownloadImage" class="btn btn-sm btn-info" href="#">
<i class="mdi mdi-download"></i>
Download PNG
</a>
<a class="btn btn-sm btn-danger" data-bs-dismiss="modal">
<i class="mdi mdi-close-thick"></i>
Close
</a>
</div>
</div>
</div>
<div class="panel-body" >
<div style="max-width: 900px; height: 500px;">
<div id="visgraph" style="width: 100%; height: 100%;">
</div>
</div>
</div>
<style type="text/css">
.modal-dialog {
max-width: 902px !important;
}
</style>
<script type="text/javascript">
var is_htmx = true;
var brokenImage = '{{ broken_image }}';
var topologyData = {{ topology_data | safe }};
</script>
<script src="{% static 'netbox_topology_views/js/app.js' %}?ver={{ epoch }} " defer></script>
@@ -1,16 +1,17 @@
{% extends 'base/layout.html' %}
{% load i18n %}
{% load buttons %}
{% load render_table from django_tables2 %}
{% load helpers %}
{% load static %}
{% block title %}Topology Views Images{% endblock %}
{% block title %}{% trans "Topology Views Images" %}{% endblock %}
{% block head %}
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/app.css' %}">
{% endblock %}
{% block content-wrapper %}
{% block content %}
<form id="images" class="container py-4">
<div class="d-flex flex-wrap justify-content-center gap-3 mb-2">
{% for role in roles %}
@@ -20,7 +21,7 @@
{% if role.image %}
<img src="{{ role.image }}" />
{% else %}
Image
{% trans "Image" %}
{% endif %}
</button>
<div class="dropdown-menu mt-2" aria-labelledby="dropdownMenuButton{{ role.id }}">
@@ -36,14 +37,15 @@
{% endfor %}
</div>
<button class="btn btn-primary" type="submit">Save</button>
<button class="btn btn-primary" type="submit">{% trans "Save" %}</button>
</form>
{% include 'netbox_topology_views/toasts.html' %}
{% endblock content-wrapper %}
{% endblock content %}
{% block javascript %}
<script type="text/javascript">
const basePath = '{{ basepath }}';
window.topologyI18n = {savedSettings: '{{ _("Saved settings")|escapejs }}'};
</script>
<script src="{% static 'netbox_topology_views/js/images.js' %}" defer></script>
{% endblock javascript %}
@@ -1,11 +1,12 @@
{% extends 'base/layout.html' %}
{% extends 'generic/_base.html' %}
{% load i18n %}
{% load buttons %}
{% load render_table from django_tables2 %}
{% load static %}
{% load perms %}
{% load helpers %}
{% block title %}Topology Views{% endblock %}
{% block title %}{% trans "Topology Views" %}{% endblock %}
{% block head %}
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/vendor.css' %}">
@@ -16,30 +17,30 @@
<div class="controls">
<div class="control-group">
{% block extra_controls %}{% endblock %}
<a id="btnDownloadXml" class="btn btn-sm btn-info" href="#">
<a id="btnDownloadXml" class="btn btn-info" href="#">
<i class="mdi mdi-download"></i>
Download XML
{% trans "Download XML" %}
</a>
<a id="btnDownloadImage" class="btn btn-sm btn-info" href="#">
<a id="btnDownloadImage" class="btn btn-info" href="#">
<i class="mdi mdi-download"></i>
Download PNG
{% trans "Download PNG" %}
</a>
</div>
</div>
{% endblock controls %}
{% block tabs %}
<ul class="nav nav-tabs px-3">
<ul class="nav nav-tabs" id="tabswrapper">
{% block tab_items %}
<li class="nav-item" role="presentation">
<button class="nav-link active" id="network-tab" data-bs-toggle="tab" data-bs-target="#networks" type="button" role="tab" aria-controls="filters-form" aria-selected="true">
Network
{% trans "Network" %}
</button>
</li>
{% if filter_form %}
<li class="nav-item" role="presentation">
<button class="nav-link" id="filters-form-tab" data-bs-toggle="tab" data-bs-target="#filters-form" type="button" role="tab" aria-controls="object-list" aria-selected="false">
Filters
{% trans "Filters" %}
{% if filter_form %}{% badge filter_form.changed_data|length bg_color="blue" %}{% endif %}
</button>
</li>
@@ -48,17 +49,26 @@
</ul>
{% endblock tabs %}
{% block content-wrapper %}
{% block content %}
{% with config=settings.PLUGINS_CONFIG.netbox_topology_views %}
<div class="tab-content">
<div class="tab-content" id="tabcontentwrapper">
{# Applied filters #}
{% if filter_form %}
{% applied_filters model filter_form request.GET %}
<div id="filterwrapper">
{% applied_filters model filter_form request.GET %}
</div>
{% endif %}
<div class="tab-pane show active" id="networks" role="tabpanel" aria-labelledby="network-tab">
<div class="panel-body">
{% if filter_required %}
<div class="bg-warning text-white p-2">{% trans 'Nothing to display! Set filters and hit search button or set "Draw Default Layout" in your individual options.' %}</div>
{% endif %}
{% if empty_result %}
<div class="bg-warning text-white p-2">{% trans "Empty result set! Please review your filter settings." %}</div>
<div class="bg-info text-white p-2">{% trans 'Hint: Some options may produce an empty result. Use at least "Show Unconnected/Cables/Logical Connections".' %}</div>
{% endif %}
<div id="visgraph"></div>
</div>
</div>
@@ -71,13 +81,42 @@
</div>
{% endwith %}
{% endblock content-wrapper %}
{% endblock content %}
{% block javascript %}
<script type="text/javascript">
const brokenImage = '{{ broken_image }}';
const topologyData = {{ topology_data | safe }};
const basePath = '{{ basepath }}';
</script>
window.addEventListener("resize", resizeCanvas);
resizeCanvas();
function resizeCanvas() {
heightToSubtract = getElementHeight('.page-header') +
getElementHeight('#tabswrapper') +
getElementHeight('#filterwrapper') +
getElementHeight('.footer') +
getElementPadding('#tabcontentwrapper');
document.getElementById("visgraph").style.height = "calc(100vh - " + heightToSubtract + "px)";
}
function getElementPadding(element) {
el = document.querySelector(element);
els = getComputedStyle(el);
padding = parseInt(els.paddingTop) + parseInt(els.paddingBottom);
return padding;
}
function getElementHeight(element) {
el = document.querySelector(element);
els = getComputedStyle(el);
height = el.offsetHeight + parseInt(els.marginTop) + parseInt(els.marginBottom);
return height;
}
</script>
<script src="{% static 'netbox_topology_views/js/app.js' %}" defer></script>
{% endblock javascript %}
@@ -1,5 +1,6 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Topology Views Individual Options{% endblock %}
{% block title %}{% trans "Topology Views Individual Options" %}{% endblock %}
{% block tabs %} {% endblock tabs %}
@@ -1,4 +1,5 @@
<a role="button" class="btn btn-sm btn-primary" title="Topology" href="#" hx-get="/plugins/netbox_topology_views/topology/?location_id={{ object.id }}&show_cables=on&show_unconnected=on" hx-target="#htmx-modal-content" data-bs-toggle="modal" data-bs-target="#htmx-modal">
{% load i18n %}
<a role="button" class="btn btn-primary" title="{% trans "Topology" %}" href="#" hx-get="/plugins/netbox_topology_views/topology/?location_id={{ object.id }}&show_cables=True&show_unconnected=True" hx-target="#htmx-modal-content" data-bs-toggle="modal" data-bs-target="#htmx-modal">
<i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i>
Topology
{% trans "Topology" %}
</a>
@@ -0,0 +1,43 @@
{% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %}
{% load plugins %}
{% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">
<div class="card">
<h5 class="card-header">
{% trans "Coordinates" %}
</h5>
<div class="card-body">
<table class="table table-hover attr-table">
<tr>
<th scope="row">{% trans "Group" %}</th>
<td>{{ object.group|linkify }}</td>
</tr>
<tr>
<th scope="row">{% trans "Power Feed" %}</th>
<td>{{ object.device|linkify }}</td>
</tr>
<tr>
<th scope="row">{% trans "X-Coordinate" %}</th>
<td>{{ object.x }}</td>
</tr>
<tr>
<th scope="row">{% trans "Y-Coordinate" %}</th>
<td>{{ object.y }}</td>
</tr>
</table>
</div>
</div>
{% plugin_left_page object %}
</div>
<div class="col col-md-6">
{% include 'inc/panels/custom_fields.html' %}
{% plugin_right_page object %}
</div>
</div>
{% endblock content %}
@@ -0,0 +1,4 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Add new Power Feed Coordinates" %}{% endblock title %}
@@ -0,0 +1,4 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Edit Power Feed Coordinates" %}{% endblock title %}
@@ -0,0 +1,4 @@
{% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}{% trans "Power Feed Coordinates" %}{% endblock title %}
@@ -0,0 +1,43 @@
{% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %}
{% load plugins %}
{% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %}
{% block content %}
<div class="row mb-3">
<div class="col col-md-6">
<div class="card">
<h5 class="card-header">
{% trans "Coordinates" %}
</h5>
<div class="card-body">
<table class="table table-hover attr-table">
<tr>
<th scope="row">{% trans "Group" %}</th>
<td>{{ object.group|linkify }}</td>
</tr>
<tr>
<th scope="row">{% trans "Power Panel" %}</th>
<td>{{ object.device|linkify }}</td>
</tr>
<tr>
<th scope="row">{% trans "X-Coordinate" %}</th>
<td>{{ object.x }}</td>
</tr>
<tr>
<th scope="row">{% trans "Y-Coordinate" %}</th>
<td>{{ object.y }}</td>
</tr>
</table>
</div>
</div>
{% plugin_left_page object %}
</div>
<div class="col col-md-6">
{% include 'inc/panels/custom_fields.html' %}
{% plugin_right_page object %}
</div>
</div>
{% endblock content %}
@@ -0,0 +1,4 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Add new Power Panel Coordinates" %}{% endblock title %}
@@ -0,0 +1,4 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Edit Power Panel Coordinates" %}{% endblock title %}
@@ -0,0 +1,4 @@
{% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}{% trans "Power Panel Coordinates" %}{% endblock title %}
@@ -0,0 +1,656 @@
{% extends 'generic/_base.html' %}
{% load helpers %}
{% load i18n %}
{% load static %}
{% block title %}{% trans "Rack view" %}{% endblock %}
{% block head %}
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/app.css' %}">
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/rack_elevation.css' %}">
{% endblock %}
{% block content %}
<div class="card mb-3">
<div class="card-header"><strong>{% trans "Select racks" %}</strong></div>
<div class="card-body">
<form method="get">
<div class="row g-3">
{% for field in filter_form %}
<div class="col-md-3">
<label class="form-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
{{ field }}
{% if field.help_text %}<div class="form-hint">{{ field.help_text }}</div>{% endif %}
{% for error in field.errors %}<div class="text-danger small">{{ error }}</div>{% endfor %}
</div>
{% endfor %}
</div>
<div class="mt-3">
<button class="btn btn-primary" type="submit"><i class="mdi mdi-magnify"></i> {% trans "Show" %}</button>
<a class="btn btn-outline-secondary" href="{% url 'plugins:netbox_topology_views:rack_elevation' %}">{% trans "Reset" %}</a>
</div>
</form>
</div>
</div>
{% if racks %}
<div class="d-flex justify-content-end align-items-center gap-2 mb-3 flex-wrap">
<strong class="me-2">{% trans "Export all racks:" %}</strong>
<button class="btn btn-sm btn-outline-primary rack-export" data-format="svg" data-scope="all">SVG</button>
<button class="btn btn-sm btn-outline-primary rack-export" data-format="png" data-scope="all">PNG</button>
<button class="btn btn-sm btn-outline-primary rack-export" data-format="drawio" data-scope="all">draw.io</button>
</div>
<div class="rack-elevation-grid">
{% for rack in racks %}
<section class="rack-card" data-rack-id="{{ rack.pk }}" data-rack-units="{{ rack.u_height }}">
<header>
<div><a href="{{ rack.get_absolute_url }}"><strong>{{ rack.name }}</strong></a><br>
<small>{{ rack.site }}{% if rack.location %} · {{ rack.location }}{% endif %} · {{ rack.u_height }}U</small></div>
<div class="btn-group" aria-label="{% blocktrans with name=rack.name %}Export {{ name }}{% endblocktrans %}">
<button class="btn btn-sm btn-outline-secondary rack-export" data-format="svg" data-scope="{{ rack.pk }}">SVG</button>
<button class="btn btn-sm btn-outline-secondary rack-export" data-format="png" data-scope="{{ rack.pk }}">PNG</button>
<button class="btn btn-sm btn-outline-secondary rack-export" data-format="drawio" data-scope="{{ rack.pk }}">draw.io</button>
</div>
</header>
<div class="rack-faces">
{% for face, face_label in faces %}
<div class="rack-face">
<div class="rack-face-title">{{ face_label }}</div>
<div class="rack-frame" style="--rack-units: {{ rack.u_height }}">
<div class="rack-unit-labels">
{% for unit in rack.elevation_unit_labels %}<span>{{ unit }}</span>{% endfor %}
</div>
<div class="rack-device-area">
{% for device in rack.elevation_devices %}
{% if device.elevation_face == face %}
<a class="rack-device" href="{{ device.get_absolute_url }}"
data-face="{{ face }}" data-device-name="{{ device.name|default:device.device_type.model }}"
data-device-type="{{ device.device_type }}" data-position="{{ device.position|default:1 }}"
data-device-height="{{ device.device_type.u_height|default:1 }}" data-device-color="#{{ device.role.color|default:'1685fc' }}"
style="bottom: {{ device.elevation_bottom }}%; height: {{ device.elevation_height }}%; border-color: #{{ device.role.color }}"
title="{{ device.name }} · {{ device.device_type }} · U{{ device.position }}">
<span>{{ device.name|default:device.device_type.model }}</span>
<small>U{{ device.position }} · {{ device.device_type }}</small>
</a>
{% endif %}
{% endfor %}
</div>
</div>
</div>
{% endfor %}
</div>
</section>
{% endfor %}
</div>
<div id="rack-topology-card" class="card mt-4">
<div class="card-header d-flex justify-content-between align-items-center">
<strong>{% trans "Cable topology" %}</strong>
<div class="d-flex gap-2 align-items-center">
<div class="d-flex gap-3 align-items-center rack-topology-kind-toggles">
<div class="form-check form-check-inline mb-0">
<input class="form-check-input" type="checkbox" id="rack-topology-show-wireless" checked>
<label class="form-check-label" for="rack-topology-show-wireless">{% trans "Wireless/WLAN" %}</label>
</div>
<div class="form-check form-check-inline mb-0">
<input class="form-check-input" type="checkbox" id="rack-topology-show-power" checked>
<label class="form-check-label" for="rack-topology-show-power">{% trans "Power" %}</label>
</div>
</div>
<div class="btn-group">
<button class="btn btn-sm btn-outline-primary topology-export" data-format="svg">SVG</button>
<button class="btn btn-sm btn-outline-primary topology-export" data-format="png">PNG</button>
<button class="btn btn-sm btn-outline-primary topology-export" data-format="drawio">draw.io</button>
</div>
<div class="btn-group" aria-label="{% trans "Zoom topology" %}">
<button id="rack-topology-zoom-out" class="btn btn-sm btn-outline-secondary" type="button" title="{% trans "Zoom out" %}"><i class="mdi mdi-minus"></i></button>
<button id="rack-topology-zoom-reset" class="btn btn-sm btn-outline-secondary" type="button" title="{% trans "Reset zoom" %}"><span id="rack-topology-zoom-label">100%</span></button>
<button id="rack-topology-zoom-in" class="btn btn-sm btn-outline-secondary" type="button" title="{% trans "Zoom in" %}"><i class="mdi mdi-plus"></i></button>
</div>
<button id="rack-topology-reset" class="btn btn-sm btn-outline-secondary" type="button">
<i class="mdi mdi-restore"></i> {% trans "Reset positions" %}
</button>
<button id="rack-topology-fullscreen" class="btn btn-sm btn-outline-secondary" type="button">
<i class="mdi mdi-fullscreen"></i> {% trans "Full screen" %}
</button>
</div>
</div>
<div class="card-body">
<div id="rack-topology" class="rack-topology" aria-label="{% trans "Topology of the selected racks" %}">
<svg class="rack-topology-lines" aria-hidden="true"></svg>
<div class="rack-topology-columns"></div>
<div class="rack-topology-tooltip" role="tooltip"></div>
</div>
</div>
</div>
{{ rack_topology|json_script:"rack-topology-data" }}
{{ rack_export|json_script:"rack-export-data" }}
{{ i18n|json_script:"rack-i18n-data" }}
<div class="card mt-4">
<div class="card-header"><strong>{% trans "Cabling of the displayed racks" %}</strong> <span class="badge rack-cable-count">{{ cables|length }}</span></div>
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead><tr><th>{% trans "Cable" %}</th><th>{% trans "A side" %}</th><th>{% trans "B side" %}</th><th>{% trans "Type" %}</th><th>{% trans "Status" %}</th></tr></thead>
<tbody>
{% for row in cables %}
<tr>
<td><a href="{{ row.cable.get_absolute_url }}">{{ row.cable.label|default:row.cable }}</a></td>
<td>{% if row.a %}<strong>{{ row.a.device_name }}</strong><br><small>{{ row.a.name }}</small>{% else %}—{% endif %}</td>
<td>{% if row.b %}<strong>{{ row.b.device_name }}</strong><br><small>{{ row.b.name }}</small>{% else %}—{% endif %}</td>
<td>{{ row.cable.type|default:'—' }}</td><td>{{ row.cable.get_status_display }}</td>
</tr>
{% empty %}<tr><td colspan="5" class="text-muted text-center py-4">{% trans "No cabling found." %}</td></tr>{% endfor %}
</tbody>
</table>
</div>
</div>
{% elif has_selection %}
<div class="alert alert-warning">{% trans "No occupied racks were found for this selection. Enable “Include empty racks” to show empty racks as well." %}</div>
{% else %}
<div class="alert alert-info">{% trans "Select one or more racks, or narrow the view by site and location." %}</div>
{% endif %}
{% endblock %}
{% block javascript %}
<script>
(() => {
const root = document.getElementById('rack-topology');
const source = document.getElementById('rack-topology-data');
if (!root || !source) return;
const data = JSON.parse(source.textContent);
const t = JSON.parse(document.getElementById('rack-i18n-data').textContent);
const isWirelessEdge = edge => edge.kind === 'wireless' || edge.kind === 'wireless-lan';
const isPowerEdge = edge => edge.kind === 'power';
const showWirelessCheckbox = document.getElementById('rack-topology-show-wireless');
const showPowerCheckbox = document.getElementById('rack-topology-show-power');
const isEdgeVisible = edge => {
if (isWirelessEdge(edge)) return showWirelessCheckbox ? showWirelessCheckbox.checked : true;
if (isPowerEdge(edge)) return showPowerCheckbox ? showPowerCheckbox.checked : true;
return true;
};
const applyKindVisibility = () => {
const showWireless = showWirelessCheckbox ? showWirelessCheckbox.checked : true;
root.querySelectorAll('.rack-topology-node').forEach(node => {
if (node.dataset.kind === 'wireless-lan') {
node.style.display = showWireless ? '' : 'none';
}
});
drawEdges();
};
const rackData = JSON.parse(document.getElementById('rack-export-data').textContent);
const columns = root.querySelector('.rack-topology-columns');
const svg = root.querySelector('svg');
const tooltip = root.querySelector('.rack-topology-tooltip');
const resetButton = document.getElementById('rack-topology-reset');
const fullscreenButton = document.getElementById('rack-topology-fullscreen');
const topologyCard = document.getElementById('rack-topology-card');
const zoomInButton = document.getElementById('rack-topology-zoom-in');
const zoomOutButton = document.getElementById('rack-topology-zoom-out');
const zoomResetButton = document.getElementById('rack-topology-zoom-reset');
const zoomLabel = document.getElementById('rack-topology-zoom-label');
let topologyZoom = 1;
const activeNetBoxTheme = () => {
for (const element of [topologyCard, document.body, document.documentElement]) {
const match = getComputedStyle(element).backgroundColor.match(/[\d.]+/g);
if (match && match.length >= 3 && (match.length < 4 || Number(match[3]) > 0)) {
const [red, green, blue] = match.map(Number);
return (.2126 * red + .7152 * green + .0722 * blue) < 140 ? 'dark' : 'light';
}
}
return document.body.dataset.bsTheme || document.documentElement.dataset.bsTheme || 'light';
};
const topologyHighlightColor = () => activeNetBoxTheme() === 'dark' ? '#ffffff' : '#16a34a';
const applyTopologyTheme = () => {
root.style.setProperty('--topology-highlight-color', topologyHighlightColor());
root.querySelectorAll('.rack-topology-edge.is-highlighted').forEach(path => {
path.style.setProperty('stroke', topologyHighlightColor(), 'important');
path.style.setProperty('filter', `drop-shadow(0 0 5px ${topologyHighlightColor()})`, 'important');
});
};
applyTopologyTheme();
const topologyThemeObserver = new MutationObserver(() => requestAnimationFrame(applyTopologyTheme));
topologyThemeObserver.observe(document.body, {attributes: true, attributeFilter: ['data-bs-theme']});
topologyThemeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-bs-theme', 'data-netbox-color-mode'],
});
const storageKey = `netbox-rack-topology-v3:${window.location.pathname}${window.location.search}`;
let storedPositions = {};
try { storedPositions = JSON.parse(localStorage.getItem(storageKey) || '{}'); } catch (_) {}
const groups = new Map();
data.nodes.forEach(node => {
const groupKey = node.rack_id ? `rack-${node.rack_id}` : `external-${node.rack_name || t.external}`;
if (!groups.has(groupKey)) groups.set(groupKey, {
name: node.rack_name || t.external,
rackUnits: node.rack_u_height || null,
descUnits: Boolean(node.rack_desc_units),
nodes: [],
});
groups.get(groupKey).nodes.push(node);
});
groups.forEach(group => {
const column = document.createElement('section');
column.className = 'rack-topology-column';
const heading = document.createElement('h4');
heading.textContent = group.name;
column.appendChild(heading);
const nodeContainer = document.createElement('div');
nodeContainer.className = 'rack-topology-device-list';
nodeContainer.style.display = 'flex';
nodeContainer.style.flexDirection = 'column';
nodeContainer.style.gap = '20px';
nodeContainer.style.rowGap = '20px';
column.appendChild(nodeContainer);
group.nodes.sort((a, b) => group.descUnits
? (a.position || 0) - (b.position || 0)
: (b.position || 0) - (a.position || 0)
).forEach(node => {
const item = document.createElement(node.url ? 'a' : 'div');
item.className = 'rack-topology-node';
item.id = `topology-${node.node_id}`;
item.style.setProperty('--node-color', `#${node.color}`);
item.dataset.nodeId = node.node_id;
if (node.kind) item.dataset.kind = node.kind;
if (node.url) item.href = node.url;
const nameElement = document.createElement('strong');
nameElement.textContent = node.device_name;
const portElement = document.createElement('small');
portElement.textContent = node.subtitle || node.name;
item.append(nameElement, portElement);
const saved = storedPositions[node.node_id];
if (saved) item.style.transform = `translate(${saved.x}px, ${saved.y}px)`;
nodeContainer.appendChild(item);
});
columns.appendChild(column);
});
const showTooltip = (html, anchor) => {
tooltip.innerHTML = html;
tooltip.classList.add('is-visible');
const rootBounds = root.getBoundingClientRect();
const anchorBounds = anchor.getBoundingClientRect();
tooltip.style.left = `${anchorBounds.right - rootBounds.left + root.scrollLeft + 10}px`;
tooltip.style.top = `${anchorBounds.top - rootBounds.top + root.scrollTop}px`;
};
const hideTooltip = () => tooltip.classList.remove('is-visible');
const escapeHtml = value => {
const element = document.createElement('span');
element.textContent = value == null ? '—' : String(value);
return element.innerHTML;
};
const setEdgeHighlighted = (path, highlighted) => {
path.classList.toggle('is-highlighted', highlighted);
if (highlighted) {
path.style.setProperty('stroke', topologyHighlightColor(), 'important');
path.style.setProperty('filter', `drop-shadow(0 0 5px ${topologyHighlightColor()})`, 'important');
} else {
path.style.removeProperty('stroke');
path.style.removeProperty('filter');
}
};
const drawEdges = () => {
const bounds = root.getBoundingClientRect();
let width = Math.max(root.clientWidth, columns.scrollWidth * topologyZoom + 32);
let height = Math.max(root.clientHeight, columns.scrollHeight * topologyZoom + 32);
svg.style.width = `${width}px`;
svg.style.height = `${height}px`;
svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
svg.replaceChildren();
data.edges.forEach(edge => {
if (!isEdgeVisible(edge)) return;
const from = document.getElementById(`topology-${edge.from}`);
const to = document.getElementById(`topology-${edge.to}`);
if (!from || !to) return;
const a = from.getBoundingClientRect(), b = to.getBoundingClientRect();
const x1 = a.left + a.width / 2 - bounds.left + root.scrollLeft;
const y1 = a.top + a.height / 2 - bounds.top + root.scrollTop;
const x2 = b.left + b.width / 2 - bounds.left + root.scrollLeft;
const y2 = b.top + b.height / 2 - bounds.top + root.scrollTop;
const bend = Math.max(30, Math.abs(x2 - x1) * .35);
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', `M ${x1} ${y1} C ${x1 + bend} ${y1}, ${x2 - bend} ${y2}, ${x2} ${y2}`);
path.setAttribute('stroke', edge.color);
path.classList.add('rack-topology-edge');
if (isWirelessEdge(edge)) path.classList.add('is-wireless');
if (isPowerEdge(edge)) path.classList.add('is-power');
path.dataset.from = edge.from;
path.dataset.to = edge.to;
const title = document.createElementNS('http://www.w3.org/2000/svg', 'title');
title.textContent = edge.label;
path.appendChild(title);
if (edge.url) path.addEventListener('click', () => window.location.href = edge.url);
path.addEventListener('mouseenter', event => {
setEdgeHighlighted(path, true);
showTooltip(
`<strong>${isWirelessEdge(edge) ? 'WLAN · ' : isPowerEdge(edge) ? `${t.power} · ` : ''}${escapeHtml(edge.label)}</strong>` +
`<span>${escapeHtml(edge.from_device)} · ${escapeHtml(edge.from_port)}</span>` +
`<span>↔ ${escapeHtml(edge.to_device)} · ${escapeHtml(edge.to_port)}</span>`,
event.target
);
});
path.addEventListener('mouseleave', () => {
setEdgeHighlighted(path, false);
hideTooltip();
});
svg.appendChild(path);
});
};
const connectedEdges = nodeId => data.edges.filter(edge => isEdgeVisible(edge) && (edge.from === nodeId || edge.to === nodeId));
root.querySelectorAll('.rack-topology-node').forEach(node => {
const nodeId = node.dataset.nodeId;
node.addEventListener('mouseenter', () => {
const connections = connectedEdges(nodeId);
svg.querySelectorAll('.rack-topology-edge').forEach(path => {
const connected = path.dataset.from === nodeId || path.dataset.to === nodeId;
setEdgeHighlighted(path, connected);
path.classList.toggle('is-dimmed', !connected);
});
const rows = connections.map(edge => {
const outgoing = edge.from === nodeId;
const localPort = outgoing ? edge.from_port : edge.to_port;
const remoteDevice = outgoing ? edge.to_device : edge.from_device;
const remotePort = outgoing ? edge.to_port : edge.from_port;
return `<li><strong>${escapeHtml(localPort)}</strong><span>→ ${escapeHtml(remoteDevice)} · ${escapeHtml(remotePort)}</span><small>${isWirelessEdge(edge) ? 'WLAN · ' : isPowerEdge(edge) ? `${t.power} · ` : ''}${escapeHtml(edge.label)}</small></li>`;
}).join('');
showTooltip(`<strong>${escapeHtml(t.connections)} (${connections.length})</strong><ul>${rows || `<li>${escapeHtml(t.noConnections)}</li>`}</ul>`, node);
});
node.addEventListener('mouseleave', () => {
svg.querySelectorAll('.rack-topology-edge').forEach(path => {
setEdgeHighlighted(path, false);
path.classList.remove('is-dimmed');
});
hideTooltip();
});
let drag = null;
node.addEventListener('pointerdown', event => {
if (event.button !== 0) return;
const saved = storedPositions[nodeId] || {x: 0, y: 0};
drag = {startX: event.clientX, startY: event.clientY, x: saved.x, y: saved.y, moved: false};
node.setPointerCapture(event.pointerId);
node.classList.add('is-dragging');
event.preventDefault();
});
node.addEventListener('pointermove', event => {
if (!drag) return;
const x = drag.x + (event.clientX - drag.startX) / topologyZoom;
const y = drag.y + (event.clientY - drag.startY) / topologyZoom;
drag.moved ||= Math.abs(x - drag.x) > 3 || Math.abs(y - drag.y) > 3;
node.style.transform = `translate(${x}px, ${y}px)`;
storedPositions[nodeId] = {x, y};
drawEdges();
});
node.addEventListener('pointerup', event => {
if (!drag) return;
const moved = drag.moved;
drag = null;
node.releasePointerCapture(event.pointerId);
node.classList.remove('is-dragging');
localStorage.setItem(storageKey, JSON.stringify(storedPositions));
if (moved) node.dataset.suppressClick = 'true';
});
node.addEventListener('click', event => {
if (node.dataset.suppressClick === 'true') {
event.preventDefault();
delete node.dataset.suppressClick;
}
});
});
resetButton?.addEventListener('click', () => {
storedPositions = {};
localStorage.removeItem(storageKey);
root.querySelectorAll('.rack-topology-node').forEach(node => node.style.transform = '');
drawEdges();
});
fullscreenButton?.addEventListener('click', async () => {
if (document.fullscreenElement === topologyCard) await document.exitFullscreen();
else await topologyCard.requestFullscreen();
});
document.addEventListener('fullscreenchange', () => {
const active = document.fullscreenElement === topologyCard;
fullscreenButton.innerHTML = active
? `<i class="mdi mdi-fullscreen-exit"></i> ${escapeHtml(t.exitFullScreen)}`
: `<i class="mdi mdi-fullscreen"></i> ${escapeHtml(t.fullScreen)}`;
requestAnimationFrame(drawEdges);
});
const setTopologyZoom = value => {
topologyZoom = Math.min(2, Math.max(.5, Math.round(value * 10) / 10));
columns.style.zoom = topologyZoom;
zoomLabel.textContent = `${Math.round(topologyZoom * 100)}%`;
requestAnimationFrame(drawEdges);
};
zoomInButton?.addEventListener('click', () => setTopologyZoom(topologyZoom + .1));
zoomOutButton?.addEventListener('click', () => setTopologyZoom(topologyZoom - .1));
zoomResetButton?.addEventListener('click', () => setTopologyZoom(1));
const xmlEscape = value => String(value ?? '').replace(/[&<>"']/g, char => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;'
})[char]);
const safeName = value => String(value || 'export').replace(/[^a-z0-9._-]+/gi, '-').replace(/^-|-$/g, '');
const exportPalette = () => {
const declaredTheme = activeNetBoxTheme();
const dark = declaredTheme === 'dark' || (!declaredTheme && window.matchMedia('(prefers-color-scheme: dark)').matches);
return dark ? {
frame: '#52606d', grid: '#667382', heading: '#8fc8ff', muted: '#a9b7c6',
deviceFill: '#162e45', deviceText: '#ffffff', deviceSubtext: '#cad5df',
} : {
frame: '#718096', grid: '#8b99a8', heading: '#0b69b7', muted: '#52606d',
deviceFill: '#eef6ff', deviceText: '#132238', deviceSubtext: '#52606d',
};
};
const svgDocument = (width, height, content) =>
`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${content}</svg>`;
const drawioDocument = cells =>
`<mxfile host="app.diagrams.net" type="device"><diagram name="Rack export"><mxGraphModel page="0" background="none" grid="1" guides="1" connect="1"><root><mxCell id="0"/><mxCell id="1" parent="0"/>${cells}</root></mxGraphModel></diagram></mxfile>`;
const renderedRackData = racks => racks.map(rack => {
const card = document.querySelector(`.rack-card[data-rack-id="${rack.id}"]`);
if (!card) return rack;
const rackUnits = Number.parseFloat(card.dataset.rackUnits) || rack.u_height || 1;
const devices = Array.from(card.querySelectorAll('.rack-device')).map(device => {
const bottom = Number.parseFloat(device.style.bottom) || 0;
const height = Number.parseFloat(device.style.height) || (100 / rackUnits);
const deviceHeight = Math.max(height / 100 * rackUnits, 1);
const bottomUnits = bottom / 100 * rackUnits;
const startingUnit = Number(rack.starting_unit) || 1;
return {
name: device.dataset.deviceName || device.querySelector('span')?.textContent || t.device,
type: device.dataset.deviceType || '',
position: rack.desc_units
? startingUnit + rackUnits - deviceHeight - bottomUnits
: startingUnit + bottomUnits,
height: deviceHeight,
face: device.dataset.face === 'rear' ? 'rear' : 'front',
color: device.dataset.deviceColor || '#1685fc',
};
});
return {...rack, devices};
});
const buildRackDrawio = racks => {
const palette = exportPalette();
const unit = 22, faceWidth = 250, labelWidth = 28, faceGap = 28, rackGap = 44, header = 55;
const rackWidth = labelWidth + faceWidth * 2 + faceGap;
let cells = '', cellId = 2;
const vertex = (value, style, x, y, width, height) => {
const id = cellId++;
cells += `<mxCell id="${id}" value="${xmlEscape(value)}" style="${style}" vertex="1" parent="1"><mxGeometry x="${x}" y="${y}" width="${width}" height="${height}" as="geometry"/></mxCell>`;
return id;
};
racks.forEach((rack, rackIndex) => {
const baseX = 10 + rackIndex * (rackWidth + rackGap);
const rackHeight = rack.u_height * unit;
const startingUnit = Number(rack.starting_unit) || 1;
vertex(rack.name, `text;html=1;strokeColor=none;fillColor=none;align=left;verticalAlign=middle;fontSize=16;fontStyle=1;fontColor=${palette.heading};`, baseX, 0, rackWidth, 25);
vertex(`${rack.site}${rack.location ? ` · ${rack.location}` : ''} · ${rack.u_height}U`, `text;html=1;strokeColor=none;fillColor=none;align=left;fontSize=10;fontColor=${palette.muted};`, baseX, 24, rackWidth, 20);
['front', 'rear'].forEach((face, faceIndex) => {
const x = baseX + labelWidth + faceIndex * (faceWidth + faceGap);
vertex(face === 'front' ? t.front.toUpperCase() : t.rear.toUpperCase(), `text;html=1;strokeColor=none;fillColor=none;align=center;fontSize=10;fontColor=${palette.muted};`, x, 38, faceWidth, 17);
vertex('', `rounded=0;html=1;fillColor=none;strokeColor=${palette.frame};strokeWidth=4;`, x, header, faceWidth, rackHeight);
for (let row = 0; row < rack.u_height; row++) {
const y = header + row * unit;
const unitLabel = rack.desc_units ? startingUnit + row : startingUnit + rack.u_height - 1 - row;
if (faceIndex === 0) vertex(String(unitLabel), `text;html=1;strokeColor=none;fillColor=none;align=right;fontSize=8;fontColor=${palette.muted};`, x - labelWidth, y, labelWidth - 4, unit);
}
rack.devices.filter(device => device.face === face).forEach(device => {
const positionOffset = device.position - startingUnit;
const y = rack.desc_units
? header + positionOffset * unit
: header + rackHeight - (positionOffset + device.height) * unit;
const h = Math.max(device.height * unit, 4);
const value = h >= 31 ? `${device.name}<br><font style="font-size:9px">U${device.position} · ${device.type}</font>` : device.name;
vertex(value, `rounded=1;html=1;whiteSpace=wrap;overflow=hidden;align=left;verticalAlign=top;spacingLeft=5;spacingTop=2;fillColor=${palette.deviceFill};strokeColor=${device.color};strokeWidth=2;fontColor=${palette.deviceText};fontSize=11;`, x + 3, y + 1, faceWidth - 6, h - 2);
});
});
});
return drawioDocument(cells);
};
const buildRackSvg = racks => {
const palette = exportPalette();
const unit = 22, faceWidth = 250, labelWidth = 28, faceGap = 28, rackGap = 44, header = 55;
const rackWidth = labelWidth + faceWidth * 2 + faceGap;
const maxUnits = Math.max(...racks.map(rack => rack.u_height || 1), 1);
const width = racks.length * rackWidth + Math.max(0, racks.length - 1) * rackGap + 20;
const height = header + maxUnits * unit + 25;
let content = '';
racks.forEach((rack, rackIndex) => {
const baseX = 10 + rackIndex * (rackWidth + rackGap);
const rackHeight = rack.u_height * unit;
const startingUnit = Number(rack.starting_unit) || 1;
content += `<text x="${baseX}" y="20" fill="${palette.heading}" font-family="sans-serif" font-size="16" font-weight="700">${xmlEscape(rack.name)}</text>`;
content += `<text x="${baseX}" y="39" fill="${palette.muted}" font-family="sans-serif" font-size="11">${xmlEscape(rack.site)}${rack.location ? ` · ${xmlEscape(rack.location)}` : ''} · ${rack.u_height}U</text>`;
['front', 'rear'].forEach((face, faceIndex) => {
const x = baseX + labelWidth + faceIndex * (faceWidth + faceGap);
content += `<text x="${x + faceWidth / 2}" y="51" text-anchor="middle" fill="${palette.muted}" font-family="sans-serif" font-size="10">${face === 'front' ? t.front.toUpperCase() : t.rear.toUpperCase()}</text>`;
content += `<rect x="${x}" y="${header}" width="${faceWidth}" height="${rackHeight}" fill="none" stroke="${palette.frame}" stroke-width="4"/>`;
for (let row = 0; row < rack.u_height; row++) {
const y = header + row * unit;
const unitLabel = rack.desc_units ? startingUnit + row : startingUnit + rack.u_height - 1 - row;
content += `<line x1="${x}" y1="${y}" x2="${x + faceWidth}" y2="${y}" stroke="${palette.grid}" stroke-opacity=".35"/>`;
if (faceIndex === 0) content += `<text x="${x - 6}" y="${y + 15}" text-anchor="end" fill="${palette.muted}" font-family="sans-serif" font-size="9">${unitLabel}</text>`;
}
rack.devices.filter(device => device.face === face).forEach(device => {
const positionOffset = device.position - startingUnit;
const y = rack.desc_units
? header + positionOffset * unit
: header + rackHeight - (positionOffset + device.height) * unit;
const h = Math.max(device.height * unit, 4);
content += `<rect x="${x + 3}" y="${y + 1}" width="${faceWidth - 6}" height="${h - 2}" rx="3" fill="${palette.deviceFill}" stroke="${xmlEscape(device.color)}" stroke-width="2"/>`;
if (h >= 13) content += `<text x="${x + 9}" y="${y + Math.min(15, h - 4)}" fill="${palette.deviceText}" font-family="sans-serif" font-size="11" font-weight="600">${xmlEscape(device.name.slice(0, 34))}</text>`;
if (h >= 31) content += `<text x="${x + 9}" y="${y + 28}" fill="${palette.deviceSubtext}" font-family="sans-serif" font-size="9">U${device.position} · ${xmlEscape(device.type.slice(0, 34))}</text>`;
});
});
});
return {svg: svgDocument(width, height, content), drawio: buildRackDrawio(racks), width, height};
};
const buildTopologySvg = () => {
const palette = exportPalette();
const rootBounds = root.getBoundingClientRect();
let width = Math.max(root.clientWidth, columns.scrollWidth * topologyZoom + 32);
let height = Math.max(root.clientHeight, columns.scrollHeight * topologyZoom + 32);
const positions = new Map();
const nodeCells = new Map();
let content = '';
let drawioCells = '', drawioId = 2;
root.querySelectorAll('.rack-topology-column').forEach(column => {
const heading = column.querySelector('h4');
const headingBounds = heading.getBoundingClientRect();
const headingX = headingBounds.left - rootBounds.left + root.scrollLeft;
const headingY = headingBounds.top - rootBounds.top + root.scrollTop;
content += `<text x="${headingX + headingBounds.width / 2}" y="${headingY + 15}" text-anchor="middle" fill="${palette.heading}" font-family="sans-serif" font-size="13" font-weight="600">${xmlEscape(heading.textContent)}</text>`;
drawioCells += `<mxCell id="group-${drawioId++}" value="${xmlEscape(heading.textContent)}" style="text;html=1;strokeColor=none;fillColor=none;align=center;fontStyle=1;fontColor=${palette.heading};" vertex="1" parent="1"><mxGeometry x="${headingX}" y="${headingY}" width="${headingBounds.width}" height="22" as="geometry"/></mxCell>`;
});
root.querySelectorAll('.rack-topology-node').forEach(node => {
if (node.style.display === 'none') return;
const bounds = node.getBoundingClientRect();
const x = bounds.left - rootBounds.left + root.scrollLeft;
const y = bounds.top - rootBounds.top + root.scrollTop;
width = Math.max(width, x + bounds.width + 20);
height = Math.max(height, y + bounds.height + 20);
positions.set(node.dataset.nodeId, {x: x + bounds.width / 2, y: y + bounds.height / 2});
const color = getComputedStyle(node).getPropertyValue('--node-color').trim() || '#1685fc';
const cellId = `node-${drawioId++}`;
nodeCells.set(node.dataset.nodeId, cellId);
drawioCells += `<mxCell id="${cellId}" value="${xmlEscape(node.querySelector('strong').textContent)}&lt;br&gt;&lt;font style=&quot;font-size:9px&quot;&gt;${xmlEscape(node.querySelector('small').textContent)}&lt;/font&gt;" style="rounded=1;html=1;whiteSpace=wrap;align=left;verticalAlign=middle;spacingLeft=8;fillColor=${palette.deviceFill};strokeColor=${xmlEscape(color)};strokeWidth=2;fontColor=${palette.deviceText};fontSize=12;" vertex="1" parent="1"><mxGeometry x="${x}" y="${y}" width="${bounds.width}" height="${bounds.height}" as="geometry"/></mxCell>`;
content += `<rect x="${x}" y="${y}" width="${bounds.width}" height="${bounds.height}" rx="6" fill="${palette.deviceFill}" stroke="${xmlEscape(color)}" stroke-width="2"/>`;
content += `<text x="${x + 10}" y="${y + 20}" fill="${palette.deviceText}" font-family="sans-serif" font-size="12" font-weight="600">${xmlEscape(node.querySelector('strong').textContent)}</text>`;
content += `<text x="${x + 10}" y="${y + 37}" fill="${palette.deviceSubtext}" font-family="sans-serif" font-size="9">${xmlEscape(node.querySelector('small').textContent)}</text>`;
});
let edgeContent = '';
data.edges.forEach(edge => {
if (!isEdgeVisible(edge)) return;
const a = positions.get(edge.from), b = positions.get(edge.to);
if (!a || !b) return;
const bend = Math.max(30, Math.abs(b.x - a.x) * .35);
const dashPattern = isWirelessEdge(edge) ? '7 7' : isPowerEdge(edge) ? '2 4' : null;
const edgeLabelPrefix = isWirelessEdge(edge) ? 'WLAN · ' : isPowerEdge(edge) ? `${t.power} · ` : '';
edgeContent += `<path d="M ${a.x} ${a.y} C ${a.x + bend} ${a.y}, ${b.x - bend} ${b.y}, ${b.x} ${b.y}" fill="none" stroke="${xmlEscape(edge.color)}" stroke-width="3"${dashPattern ? ` stroke-dasharray="${dashPattern}"` : ''}/>`;
const sourceId = nodeCells.get(edge.from), targetId = nodeCells.get(edge.to);
if (sourceId && targetId) {
drawioCells += `<mxCell id="edge-${drawioId++}" value="${xmlEscape(`${edgeLabelPrefix}${edge.label}`)}" style="edgeStyle=orthogonalEdgeStyle;rounded=1;orthogonalLoop=1;jettySize=auto;html=1;endArrow=none;endFill=0;strokeColor=${xmlEscape(edge.color)};strokeWidth=2;fontSize=9;${dashPattern ? `dashed=1;dashPattern=${dashPattern};` : ''}" edge="1" parent="1" source="${sourceId}" target="${targetId}"><mxGeometry relative="1" as="geometry"/></mxCell>`;
}
});
return {svg: svgDocument(width, height, edgeContent + content), drawio: drawioDocument(drawioCells), width, height};
};
const downloadBlob = (blob, filename) => {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
setTimeout(() => URL.revokeObjectURL(link.href), 1000);
};
const asDrawio = ({svg, drawio, width, height}) => {
if (drawio) return drawio;
const image = `data:image/svg+xml,${encodeURIComponent(svg)}`;
return `<mxfile host="app.diagrams.net" type="device"><diagram name="Rack export"><mxGraphModel page="0" background="none"><root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="2" value="" style="shape=image;imageAspect=0;aspect=fixed;image=${xmlEscape(image)};" vertex="1" parent="1"><mxGeometry x="0" y="0" width="${width}" height="${height}" as="geometry"/></mxCell></root></mxGraphModel></diagram></mxfile>`;
};
const exportGraphic = (graphic, format, filename) => {
if (format === 'svg') {
downloadBlob(new Blob([graphic.svg], {type: 'image/svg+xml'}), `${filename}.svg`);
} else if (format === 'drawio') {
downloadBlob(new Blob([asDrawio(graphic)], {type: 'application/xml'}), `${filename}.drawio`);
} else {
const image = new Image();
const url = URL.createObjectURL(new Blob([graphic.svg], {type: 'image/svg+xml'}));
image.onload = () => {
const scale = 2;
const canvas = document.createElement('canvas');
canvas.width = graphic.width * scale;
canvas.height = graphic.height * scale;
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.scale(scale, scale);
context.drawImage(image, 0, 0);
canvas.toBlob(blob => downloadBlob(blob, `${filename}.png`), 'image/png');
URL.revokeObjectURL(url);
};
image.src = url;
}
};
document.querySelectorAll('.rack-export').forEach(button => button.addEventListener('click', () => {
const selectedRacks = button.dataset.scope === 'all' ? rackData : rackData.filter(rack => String(rack.id) === button.dataset.scope);
const racks = renderedRackData(selectedRacks);
const name = button.dataset.scope === 'all' ? 'racks-all' : `rack-${safeName(racks[0]?.name)}`;
exportGraphic(buildRackSvg(racks), button.dataset.format, name);
}));
document.querySelectorAll('.topology-export').forEach(button => button.addEventListener('click', () => {
exportGraphic(buildTopologySvg(), button.dataset.format, 'rack-topology');
}));
showWirelessCheckbox?.addEventListener('change', applyKindVisibility);
showPowerCheckbox?.addEventListener('change', applyKindVisibility);
requestAnimationFrame(applyKindVisibility);
window.addEventListener('resize', drawEdges);
root.addEventListener('scroll', drawEdges, {passive: true});
})();
</script>
{% endblock %}
@@ -1,4 +0,0 @@
<a role="button" class="btn btn-sm btn-primary" title="Topology" href="#" hx-get="/plugins/netbox_topology_views/topology/?site_id={{ object.id }}&show_cables=on&show_unconnected=on" hx-target="#htmx-modal-content" data-bs-toggle="modal" data-bs-target="#htmx-modal">
<i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i>
Topology
</a>
@@ -1,3 +1,4 @@
{% load i18n %}
<div id="django-messages" class="toast-container">
<div
id="topology-plugin-error-toast"
@@ -10,13 +11,13 @@
<div class="d-flex">
<div class="toast-body">
😢
<span>Error</span>
<span>{% trans "Error" %}</span>
</div>
<button
type="button"
class="btn-close me-2 m-auto"
data-bs-dismiss="toast"
aria-label="Close"
aria-label="{% trans "Close" %}"
></button>
</div>
</div>
@@ -31,13 +32,13 @@
<div class="d-flex">
<div class="toast-body">
👍
<span>Success</span>
<span>{% trans "Success" %}</span>
</div>
<button
type="button"
class="btn-close me-2 m-auto"
data-bs-dismiss="toast"
aria-label="Close"
aria-label="{% trans "Close" %}"
></button>
</div>
</div>
+28
View File
@@ -8,6 +8,7 @@ from . import models, views
urlpatterns = (
path("", RedirectView.as_view(url="topology/", permanent=True)),
path("topology/", views.TopologyHomeView.as_view(), name="home"),
path("rack-elevation/", views.RackElevationView.as_view(), name="rack_elevation"),
path("images/", views.TopologyImagesView.as_view(), name="images"),
path("individualoptions/", views.TopologyIndividualOptionsView.as_view(), name="individualoptions"),
@@ -20,6 +21,33 @@ urlpatterns = (
path("coordinate-groups/<int:pk>/delete/", views.CoordinateGroupDeleteView.as_view(), name="coordinategroup_delete"),
path("coordinate-groups/<int:pk>/changelog/", ObjectChangeLogView.as_view(), name="coordinategroup_changelog", kwargs={'model': models.CoordinateGroup}),
# Circuit Coordinate
path("circuitcoordinate/", views.CircuitCoordinateListView.as_view(), name="circuitcoordinate_list"),
path("circuitcoordinate/add/", views.CircuitCoordinateAddView.as_view(), name="circuitcoordinate_add"),
path('circuitcoordinate/import/', views.CircuitCoordinateBulkImportView.as_view(), name='circuitcoordinate_import'),
path("circuitcoordinate/<int:pk>/", views.CircuitCoordinateView.as_view(), name="circuitcoordinate"),
path("circuitcoordinate/<int:pk>/edit/", views.CircuitCoordinateEditView.as_view(), name="circuitcoordinate_edit"),
path("circuitcoordinate/<int:pk>/delete/", views.CircuitCoordinateDeleteView.as_view(), name="circuitcoordinate_delete"),
path("circuitcoordinate/<int:pk>/changelog/", ObjectChangeLogView.as_view(), name="circuitcoordinate_changelog", kwargs={'model': models.CircuitCoordinate}),
# Power Panel Coordinate
path("powerpanelcoordinate/", views.PowerPanelCoordinateListView.as_view(), name="powerpanelcoordinate_list"),
path("powerpanelcoordinate/add/", views.PowerPanelCoordinateAddView.as_view(), name="powerpanelcoordinate_add"),
path('powerpanelcoordinate/import/', views.PowerPanelCoordinateBulkImportView.as_view(), name='powerpanelcoordinate_import'),
path("powerpanelcoordinate/<int:pk>/", views.PowerPanelCoordinateView.as_view(), name="powerpanelcoordinate"),
path("powerpanelcoordinate/<int:pk>/edit/", views.PowerPanelCoordinateEditView.as_view(), name="powerpanelcoordinate_edit"),
path("powerpanelcoordinate/<int:pk>/delete/", views.PowerPanelCoordinateDeleteView.as_view(), name="powerpanelcoordinate_delete"),
path("powerpanelcoordinate/<int:pk>/changelog/", ObjectChangeLogView.as_view(), name="powerpanelcoordinate_changelog", kwargs={'model': models.PowerPanelCoordinate}),
# Power Feed Coordinate
path("powerfeedcoordinate/", views.PowerFeedCoordinateListView.as_view(), name="powerfeedcoordinate_list"),
path("powerfeedcoordinate/add/", views.PowerFeedCoordinateAddView.as_view(), name="powerfeedcoordinate_add"),
path('powerfeedcoordinate/import/', views.PowerFeedCoordinateBulkImportView.as_view(), name='powerfeedcoordinate_import'),
path("powerfeedcoordinate/<int:pk>/", views.PowerFeedCoordinateView.as_view(), name="powerfeedcoordinate"),
path("powerfeedcoordinate/<int:pk>/edit/", views.PowerFeedCoordinateEditView.as_view(), name="powerfeedcoordinate_edit"),
path("powerfeedcoordinate/<int:pk>/delete/", views.PowerFeedCoordinateDeleteView.as_view(), name="powerfeedcoordinate_delete"),
path("powerfeedcoordinate/<int:pk>/changelog/", ObjectChangeLogView.as_view(), name="powerfeedcoordinate_changelog", kwargs={'model': models.PowerFeedCoordinate}),
# Coordinate
path("coordinate/", views.CoordinateListView.as_view(), name="coordinate_list"),
path("coordinate/add/", views.CoordinateAddView.as_view(), name="coordinate_add"),
+71 -16
View File
@@ -12,6 +12,7 @@ from django.db.models import Model
from django.templatetags.static import static
from django.utils.text import camel_case_to_spaces, re_camel_case
from django.contrib import messages
from django.utils.translation import gettext as _
IMAGE_DIR = Path(settings.STATIC_ROOT) / "netbox_topology_views/img"
if sys.version_info >= (3,9,0):
@@ -29,9 +30,8 @@ else:
def image_static_url(path: Path) -> str:
return static(
f"/{path.relative_to(Path(settings.STATIC_ROOT))}"
)
# No leading slash: static file finders (e.g. the debug toolbar's) reject absolute paths.
return static(path.relative_to(Path(settings.STATIC_ROOT)).as_posix())
def get_image_from_url(url: str) -> str:
@@ -107,59 +107,114 @@ def get_model_role(model: Type[Model]) -> Role:
)
def get_query_settings(request):
filter_id = ''
if "filter_id" in request.GET:
filter_id = request.GET["filter_id"]
save_coords = False
if "save_coords" in request.GET:
if request.GET["save_coords"] == "on":
if request.GET["save_coords"] == "True":
save_coords = True
# General options overrides
if save_coords == True and settings.PLUGINS_CONFIG["netbox_topology_views"]["allow_coordinates_saving"] == False:
save_coords = False
messages.warning(request, "Coordinate saving not allowed. Setting has been overridden")
messages.warning(request, _("Coordinate saving not allowed. Setting has been overridden"))
elif settings.PLUGINS_CONFIG["netbox_topology_views"]["always_save_coordinates"] == True:
save_coords = True
# Individual options
ignore_cable_type = ()
if "ignore_cable_type" in request.GET:
ignore_cable_type = request.GET.getlist('ignore_cable_type')
show_unconnected = False
if "show_unconnected" in request.GET:
if request.GET["show_unconnected"] == "on":
if request.GET["show_unconnected"] == "True":
show_unconnected = True
show_power = False
if "show_power" in request.GET:
if request.GET["show_power"] == "on":
if request.GET["show_power"] == "True":
show_power = True
show_circuit = False
if "show_circuit" in request.GET:
if request.GET["show_circuit"] == "on":
if request.GET["show_circuit"] == "True":
show_circuit = True
show_logical_connections = False
if "show_logical_connections" in request.GET:
if request.GET["show_logical_connections"] == "on" :
if request.GET["show_logical_connections"] == "True" :
show_logical_connections = True
show_single_cable_logical_conns = False
if "show_single_cable_logical_conns" in request.GET:
if request.GET["show_single_cable_logical_conns"] == "on" :
if request.GET["show_single_cable_logical_conns"] == "True" :
show_single_cable_logical_conns = True
show_cables = False
if "show_cables" in request.GET:
if request.GET["show_cables"] == "on" :
if request.GET["show_cables"] == "True" :
show_cables = True
show_wireless = False
if "show_wireless" in request.GET:
if request.GET["show_wireless"] == "on" :
if request.GET["show_wireless"] == "True" :
show_wireless = True
group_sites = False
if "group_sites" in request.GET:
if request.GET["group_sites"] == "True" :
group_sites = True
group_locations = False
if "group_locations" in request.GET:
if request.GET["group_locations"] == "True" :
group_locations = True
group_racks = False
if "group_racks" in request.GET:
if request.GET["group_racks"] == "True" :
group_racks = True
group_virtualchassis = False
if "group_virtualchassis" in request.GET:
if request.GET["group_virtualchassis"] == "True" :
group_virtualchassis = True
group = False
if "group" in request.GET:
group = request.GET["group"]
show_neighbors = False
if "show_neighbors" in request.GET:
if request.GET["show_neighbors"] == "on" :
if request.GET["show_neighbors"] == "True" :
show_neighbors = True
return save_coords, show_unconnected, show_power, show_circuit, show_logical_connections, show_single_cable_logical_conns, show_cables, show_wireless, show_neighbors
straight_cables = False
if "straight_cables" in request.GET:
if request.GET["straight_cables"] == "True":
straight_cables = True
draw_termination_labels = False
if "draw_termination_labels" in request.GET:
if request.GET["draw_termination_labels"] == "True":
draw_termination_labels = True
draw_cable_labels = False
if "draw_cable_labels" in request.GET:
if request.GET["draw_cable_labels"] == "True":
draw_cable_labels = True
grid_size = 0
if "grid_size" in request.GET:
grid_size = request.GET.getlist('grid_size')
node_label_items = ()
if "node_label_items" in request.GET:
node_label_items = request.GET.getlist('node_label_items')
return filter_id, ignore_cable_type, save_coords, show_unconnected, show_power, show_circuit, show_logical_connections, show_single_cable_logical_conns, show_cables, show_wireless, group_sites, group_locations, group_racks, group_virtualchassis, group, show_neighbors, straight_cables, draw_termination_labels, draw_cable_labels, grid_size, node_label_items
class LinePattern():
wireless = [2, 10, 2, 10]
@@ -289,7 +344,7 @@ def export_data_to_xml(data: dict):
if noPositionX > 0:
mxcell = doc.createElement('mxCell')
mxcell.setAttribute('id', 'noPositionWarning')
mxcell.setAttribute('value', 'One or more icons are misplaced. This happens if no coordinates are stored for a device. Turn on coordinates saving and make sure to drag all icons in the topology to a specific position before exporting to XML.')
mxcell.setAttribute('value', _('One or more icons are misplaced. This happens if no coordinates are stored for a device. Turn on coordinates saving and make sure to drag all icons in the topology to a specific position before exporting to XML.'))
mxcell.setAttribute('style', 'text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontColor=#FF0000;fontStyle=0;fontSize=35;labelBackgroundColor=#FFFF99;labelBorderColor=none;strokeWidth=20;')
mxcell.setAttribute('vertex', '1')
mxcell.setAttribute('parent', '1')
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -7,8 +7,8 @@ long_description = readme.read_text()
setup(
name="netbox-topology-views",
version="3.7.0",
description="An NetBox plugin to create Topology maps",
version="4.5.2",
description="A NetBox plugin to create Topology maps",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/mattieserver/netbox-topology-views",
+37
View File
@@ -0,0 +1,37 @@
"""Keeps the NetBox range in README.md in sync with the PluginConfig."""
import ast
import re
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def plugin_versions():
tree = ast.parse((ROOT / "netbox_topology_views" / "__init__.py").read_text())
values = {}
for node in ast.walk(tree):
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in ("min_version", "max_version"):
values[target.id] = node.value.value
return values["min_version"], values["max_version"]
def expected_range(min_version, max_version):
upper = re.sub(r"\.99$", ".x", max_version)
if min_version.endswith(".0") and upper == min_version[:-2] + ".x":
return f"`{upper}`"
return f"`{min_version}` – `{upper}`"
class MetadataTest(unittest.TestCase):
def test_readme_matches_plugin_config(self):
readme = (ROOT / "README.md").read_text()
expected = expected_range(*plugin_versions())
self.assertIn(f"| **NetBox** | {expected} |", readme)
self.assertIn(f"- NetBox {expected}", readme)
if __name__ == "__main__":
unittest.main()