Compare commits

..
Author SHA1 Message Date
mvanhaverbeke 2ca128a76b v4.3.0 2025-05-28 16:18:39 +02:00
66 changed files with 548 additions and 3019 deletions

No files matched your search

-1
View File
@@ -2,4 +2,3 @@ recursive-include netbox_topology_views/static *
recursive-include netbox_topology_views/templates * recursive-include netbox_topology_views/templates *
recursive-include netbox_topology_views/api * 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
+164 -185
View File
@@ -1,240 +1,219 @@
# MRB NetBox Topology Views # Netbox Topology Views Plugin
A customised fork of **NetBox Topology Views** with extended rack views, ![Version](https://img.shields.io/pypi/v/netbox-topology-views) ![Downloads](https://img.shields.io/pypi/dm/netbox-topology-views)
interactive cable tracing and additional network icons.
The plugin builds topologies from the devices, ports and cables maintained in Create topology views/maps from your devices in NetBox.
NetBox. In addition to the classic topology, this fork provides a complete view The connections are based on the cables you created in NetBox.
of one or more racks including front, rear and cabling. Support to filter on name, site, tag and device role.
Options to export to xml (for draw.io/diagrams.net) or png.
| | | ## 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> |
## Screenshots ![Topology with light mode](doc/img/topology_light.png)
![Topology with dark mode](doc/img/topology_dark.png)
Cable topology of a site, arranged with a coordinate group: ## Install
![Topology view](docs/screenshots/topology.png) **_NOTE:_** For Docker please see: [Docker install](https://github.com/netbox-community/netbox-docker/wiki/Using-Netbox-Plugins)
Rack view with front and rear elevations: **_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](docs/screenshots/rack-view.png) The plugin is available as a Python package and can be installed with pip.
## Features First run `source /opt/netbox/venv/bin/activate` to enter the Python virtual environment.
- 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
### 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
Then run:
```bash ```bash
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \ cd /opt/netbox/netbox
"git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop" pip3 install netbox-topology-views
python3 manage.py migrate netbox_topology_views
python3 manage.py collectstatic --no-input
``` ```
For reproducible production installs, replace `develop` with a release tag or a 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:
full commit ID.
### 2. Add the plugin to `local_requirements.txt` ```no-highlight
echo netbox-topology-views >> /opt/netbox/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 Once installed, the plugin needs to be enabled in your `configuration.py`:
or an SSH key. Do not store credentials in `local_requirements.txt`. ```no-highlight
vim /opt/netbox/netbox/netbox/configuration.py
### 3. Enable the plugin ```
In `/opt/netbox/netbox/netbox/configuration.py`:
```python ```python
PLUGINS = [ PLUGINS = ["netbox_topology_views"]
"netbox_topology_views", ```
]
Finally, restart NetBox:
```no-highlight
systemctl restart netbox
```
### Versions
> [!NOTE]
> If the version of netbox is not listed here the plugin will most likely not work. Remove the plugin if you want to update netbox before this plugin has released an update for that netbox version.
| netbox version | netbox-topology-views version |
| -------------- | ----------------------------- |
| = 4.3.X | = v4.3.0 |
| = 4.2.1 | = v4.2.1 |
| = 4.2.0 | = v4.2.0 |
| = 4.1.X | = v4.1.0 |
| = 4.0.X | = v4.0.0 |
| = 3.7.0 | = v3.9.0 |
| = 3.6.4 | = v3.8.1 |
| = 3.6.0 | = v3.7.0 |
| = 3.5.0 | = v3.6.2 |
### 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 = { PLUGINS_CONFIG = {
"netbox_topology_views": { 'netbox_topology_views': {
"static_image_directory": "netbox_topology_views/img", 'static_image_directory': 'netbox_topology_views/img',
"allow_coordinates_saving": True, 'allow_coordinates_saving': True,
"always_save_coordinates": False, 'always_save_coordinates': True
}, }
} }
``` ```
If other plugins are already configured, add `netbox_topology_views` to the | Setting | Default value | Description |
existing list and dictionary instead of replacing them. | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| 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. |
### 4. Apply migrations, collect static files, restart ### Custom field: coordinates
```bash There is also support for custom fields.
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
```
After changes to CSS or icons a hard reload in the browser (`Ctrl+F5`) may be >**_Note:_** The custom field "coordinates" is deprecated and will be removed in the future. Please use Coordinate Groups instead.
necessary.
## Update 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.
```bash The coordinates are stored as: "X;Y".
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \
"git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop"
cd /opt/netbox/netbox > Please read the "Configure" chapter to set the `allow_coordinates_saving` option to True.
/opt/netbox/venv/bin/python manage.py migrate netbox_topology_views You might also set the `always_save_coordinates` option to True.
/opt/netbox/venv/bin/python manage.py collectstatic --no-input
sudo systemctl restart netbox netbox-rq
```
`--force-reinstall` is required because the fork still uses the internal ### Convert custom field to Coordinate Groups
package version `4.5.2`.
When NetBox itself is upgraded, `upgrade.sh` reinstalls the plugin from 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:
`local_requirements.txt` and runs migrations and `collectstatic`: + 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.
```bash ### Custom Images
sudo /opt/netbox/upgrade.sh
sudo systemctl restart netbox netbox-rq
```
## Uninstall 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.
1. Remove `"netbox_topology_views"` from `PLUGINS` and `PLUGINS_CONFIG`. ![Images](doc/img/topology_images.png)
2. Remove the line from `/opt/netbox/local_requirements.txt`.
3. Uninstall the package and restart NetBox:
```bash ## Use
/opt/netbox/venv/bin/pip uninstall netbox-topology-views
sudo systemctl restart netbox netbox-rq
```
## Usage Go to the plugins tab in the navbar and click topology or go to `$NETBOX_URL/plugins/netbox_topology_views/` to view your topologies
### Classic topology Select your options for the topology view:
**Plugins → Topology Views → Topology** provides the original, filterable ![Filter Options](doc/img/topology_filter_options.png)
topology view. It supports physical cables, logical connections, neighbour
devices, circuit terminations, power feeds, wireless links, coordinate groups,
and PNG and XML export.
### Rack view <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>
**Plugins → Topology Views → More views → Rack view** ### Coordinates and Coordinate Groups
Select a single rack or several racks via site, location and rack; empty racks Netbox Topology Views stores the position of the devices. In order to allow different representations for the topology, Coordinate Groups are supported.
can be shown optionally. Devices are rendered according to position, height and
rack face. Below the elevations follow:
1. the interactive cable topology, and > Please read the "Configure" chapter to set the `allow_coordinates_saving` option to True.
2. a table of all involved cables. You might also set the `always_save_coordinates` option to True.
In the cable topology, devices can be moved via drag and drop. Hovering a device 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.
highlights its cables and lists all connected ports; hovering a cable shows both
terminations. A click opens the NetBox object.
The export buttons save a single rack, all displayed racks or the cable topology 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".
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.
Positions are stored in the browser's `localStorage` and apply only to that > **_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.
browser and the specific rack/filter selection.
With [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) ### Permissions
installed, partial-width devices are rendered side by side in the rack view.
## Device icons 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
Icons are assigned by device role slug. This fork additionally ships: To save `Coordinates` when moving icons:
+ netbox_topology_views | coordinate | change
| Device role slug | Icon file | To view `/plugins/netbox_topology-views/images`:
| --- | --- | + dcim | site | view
| `network-switch` | `network-switch.svg` | + dcim | device role | view
| `leaf-switch` | `leaf-switch.svg` | + dcim | device role | add
| `spine-switch` | `spine-switch.svg` | + dcim | device role | change
| `aggregation-switch` | `aggregation-switch.svg` |
Custom images can still be assigned on the **Images** page. The default path is To view `/plugins/netbox_topology-views/individualoptions`:
`netbox_topology_views/img` within `STATIC_ROOT`. + netbox_topology_views | individual options | change
## Permissions Set `Coordinate Groups` according to your needs:
+ netbox_topology_views | coordinate groups | view/add/change/delete
Classic topology: `dcim.view_site`, `dcim.view_device`. Set `Coordinates` according to your needs:
+ netbox_topology_views | coordinate | view/add/change/delete
Rack view: `dcim.view_rack`, `dcim.view_device`, `dcim.view_cable`. Set `Power Feed Coordinates` according to your needs:
+ netbox_topology_views | power feed coordinate | view/add/change/delete
Saving classic topology coordinates additionally requires the corresponding Set `Power Panel Coordinates` according to your needs:
permissions on `netbox_topology_views.coordinate`. + netbox_topology_views | power panel coordinate | view/add/change/delete
## Origin and credits Set `Circuit Coordinates` according to your needs:
+ netbox_topology_views | circuit coordinate | view/add/change/delete
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.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

+1 -7
View File
@@ -1,15 +1,9 @@
version: 0.1 version: 0.1
package_name: netbox-topology-views package_name: netbox-topology-views
compatibility: 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 - release: 4.3.0
netbox_min: 4.3.0 netbox_min: 4.3.0
netbox_max: 4.3.7 netbox_max: 4.3.1
- release: 4.2.0 - release: 4.2.0
netbox_min: 4.2.0 netbox_min: 4.2.0
netbox_max: 4.2.1 netbox_max: 4.2.1
+4 -7
View File
@@ -1,17 +1,14 @@
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginConfig from netbox.plugins import PluginConfig
class TopologyViewsConfig(PluginConfig): class TopologyViewsConfig(PluginConfig):
name = "netbox_topology_views" name = "netbox_topology_views"
verbose_name = _("Topology views") verbose_name = "Topology views"
description = _("A plugin to render topology maps") description = "An plugin to render topology maps"
version = "4.5.2" version = "4.3.0"
author = "Mattijs Vanhaverbeke, Codex & Claude" author = "Mattijs Vanhaverbeke"
author_email = "[email protected]" author_email = "[email protected]"
base_url = "netbox_topology_views" base_url = "netbox_topology_views"
min_version = "4.7.0"
max_version = "4.7.99"
required_settings = [] required_settings = []
default_settings = { default_settings = {
"static_image_directory": "netbox_topology_views/img", "static_image_directory": "netbox_topology_views/img",
+1 -4
View File
@@ -50,7 +50,4 @@ class PowerFeedCoordinateSerializer(NetBoxModelSerializer):
class IndividualOptionsSerializer(NetBoxModelSerializer): class IndividualOptionsSerializer(NetBoxModelSerializer):
class Meta: class Meta:
model = IndividualOptions model = IndividualOptions
fields = ("ignore_cable_type", "save_coords", "show_unconnected", "show_cables", "show_logical_connections", 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", "grid_size", "node_label_items")
"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")
+2 -6
View File
@@ -114,7 +114,7 @@ class ExportTopoToXML(BaseViewSet, ViewSet):
if request.GET: if request.GET:
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) 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, grid_size, node_label_items = get_query_settings(request)
# Read options from saved filters as NetBox does not handle custom plugin filters # Read options from saved filters as NetBox does not handle custom plugin filters
if "filter_id" in request.GET and request.GET["filter_id"] != '': if "filter_id" in request.GET and request.GET["filter_id"] != '':
@@ -136,9 +136,7 @@ class ExportTopoToXML(BaseViewSet, ViewSet):
if group_racks == False and 'group_racks' in saved_filter_params: group_racks = saved_filter_params['group_racks'] 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 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 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 straight_cables == False and 'straight_cables' in saved_filter_params: show_neighbors = 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 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'] 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 except SavedFilter.DoesNotExist: # filter_id not found
@@ -172,8 +170,6 @@ class ExportTopoToXML(BaseViewSet, ViewSet):
group_virtualchassis=group_virtualchassis, group_virtualchassis=group_virtualchassis,
group_id=group_id, group_id=group_id,
straight_cables=straight_cables, straight_cables=straight_cables,
draw_termination_labels=draw_termination_labels,
draw_cable_labels=draw_cable_labels,
grid_size=grid_size, grid_size=grid_size,
node_label_items=node_label_items, node_label_items=node_label_items,
) )
+4 -27
View File
@@ -1,37 +1,14 @@
from django.utils.translation import gettext_lazy as _
from utilities.choices import ChoiceSet from utilities.choices import ChoiceSet
class NodeLabelItems(ChoiceSet): class NodeLabelItems(ChoiceSet):
DEVICE_NAME = 'devicename' DEVICE_NAME = 'devicename'
DEVICE_TYPE = 'devicetype'
ROLE = 'role'
DESCRIPTION = 'description'
PRIMARY_IPV4 = 'primaryipv4' PRIMARY_IPV4 = 'primaryipv4'
PRIMARY_IPV6 = 'primaryipv6' PRIMARY_IPV6 = 'primaryipv6'
OUT_OF_BAND_IP = 'outofbandip' OUT_OF_BAND_IP = 'outofbandip'
PLATFORM = 'platform'
SERIAL = 'serial'
TENANT = 'tenant'
SITE = 'site'
LOCATION = 'location'
RACK = 'rack'
VIRTUAL_CHASSIS = 'virtualchassis'
ASSET_TAG = 'assettag'
CHOICES = [ CHOICES = [
(DEVICE_NAME, _('Device Name')), (DEVICE_NAME, 'Device Name'),
(DEVICE_TYPE, _('Device Type')), (PRIMARY_IPV4, 'Primary IPv4'),
(ROLE, _('Role')), (PRIMARY_IPV6, 'Primary IPv6'),
(DESCRIPTION, _('Description')), (OUT_OF_BAND_IP, 'Out-of-band IP'),
(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')),
] ]
+22 -23
View File
@@ -3,7 +3,6 @@ from circuits.models import Circuit
from dcim.choices import DeviceStatusChoices from dcim.choices import DeviceStatusChoices
from dcim.models import Device, DeviceRole, Location, Rack, Region, Site, SiteGroup, Manufacturer, DeviceType, Platform, PowerPanel, PowerFeed from dcim.models import Device, DeviceRole, Location, Rack, Region, Site, SiteGroup, Manufacturer, DeviceType, Platform, PowerPanel, PowerFeed
from django.db.models import Q from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from extras.filtersets import LocalConfigContextFilterSet from extras.filtersets import LocalConfigContextFilterSet
from extras.models import ConfigTemplate from extras.models import ConfigTemplate
from netbox.filtersets import NetBoxModelFilterSet from netbox.filtersets import NetBoxModelFilterSet
@@ -14,58 +13,58 @@ from netbox_topology_views.models import CoordinateGroup, Coordinate, CircuitCoo
class DeviceFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet, LocalConfigContextFilterSet): class DeviceFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet, LocalConfigContextFilterSet):
q = django_filters.CharFilter( q = django_filters.CharFilter(
method="search", method="search",
label=_("Search"), label="Search",
) )
manufacturer_id = django_filters.ModelMultipleChoiceFilter( manufacturer_id = django_filters.ModelMultipleChoiceFilter(
field_name='device_type__manufacturer', field_name='device_type__manufacturer',
queryset=Manufacturer.objects.all(), queryset=Manufacturer.objects.all(),
label=_("Manufacturer (ID)"), label="Manufacturer (ID)",
) )
manufacturer = django_filters.ModelMultipleChoiceFilter( manufacturer = django_filters.ModelMultipleChoiceFilter(
field_name='device_type__manufacturer__slug', field_name='device_type__manufacturer__slug',
queryset=Manufacturer.objects.all(), queryset=Manufacturer.objects.all(),
to_field_name='slug', to_field_name='slug',
label=_("Manufacturer (slug)"), label="Manufacturer (slug)",
) )
device_type_id = django_filters.ModelMultipleChoiceFilter( device_type_id = django_filters.ModelMultipleChoiceFilter(
queryset=DeviceType.objects.all(), queryset=DeviceType.objects.all(),
label=_("Device type (ID)"), label="Device type (ID)",
) )
role_id = django_filters.ModelMultipleChoiceFilter( role_id = django_filters.ModelMultipleChoiceFilter(
field_name="role_id", field_name="role_id",
queryset=DeviceRole.objects.all(), queryset=DeviceRole.objects.all(),
label=_("Role (ID)"), label="Role (ID)",
) )
platform_id = django_filters.ModelMultipleChoiceFilter( platform_id = django_filters.ModelMultipleChoiceFilter(
queryset=Platform.objects.all(), queryset=Platform.objects.all(),
label=_("Platform (ID)"), label="Platform (ID)",
) )
region_id = TreeNodeMultipleChoiceFilter( region_id = TreeNodeMultipleChoiceFilter(
queryset=Region.objects.all(), queryset=Region.objects.all(),
field_name="site__region", field_name="site__region",
lookup_expr="in", lookup_expr="in",
label=_("Region (ID)"), label="Region (ID)",
) )
site_group_id = TreeNodeMultipleChoiceFilter( site_group_id = TreeNodeMultipleChoiceFilter(
queryset=SiteGroup.objects.all(), queryset=SiteGroup.objects.all(),
field_name="site__group", field_name="site__group",
lookup_expr="in", lookup_expr="in",
label=_("Site Group (ID)"), label="Site Group (ID)",
) )
site_id = django_filters.ModelMultipleChoiceFilter( site_id = django_filters.ModelMultipleChoiceFilter(
queryset=Site.objects.all(), queryset=Site.objects.all(),
label=_("Site (ID)"), label="Site (ID)",
) )
location_id = TreeNodeMultipleChoiceFilter( location_id = TreeNodeMultipleChoiceFilter(
queryset=Location.objects.all(), queryset=Location.objects.all(),
field_name="location", field_name="location",
lookup_expr="in", lookup_expr="in",
label=_("Location (ID)"), label="Location (ID)",
) )
rack_id = django_filters.ModelMultipleChoiceFilter( rack_id = django_filters.ModelMultipleChoiceFilter(
queryset=Rack.objects.all(), queryset=Rack.objects.all(),
field_name="rack_id", field_name="rack_id",
label=_("Rack (ID)"), label="Rack (ID)",
) )
status = django_filters.MultipleChoiceFilter( status = django_filters.MultipleChoiceFilter(
choices=DeviceStatusChoices, choices=DeviceStatusChoices,
@@ -73,50 +72,50 @@ class DeviceFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilter
) )
mac_address = MultiValueMACAddressFilter( mac_address = MultiValueMACAddressFilter(
field_name='interfaces__mac_addresses__mac_address', field_name='interfaces__mac_addresses__mac_address',
label=_("MAC address"), label="MAC address",
) )
serial = MultiValueCharFilter( serial = MultiValueCharFilter(
lookup_expr='iexact' lookup_expr='iexact'
) )
console_ports = django_filters.BooleanFilter( console_ports = django_filters.BooleanFilter(
method='_console_ports', method='_console_ports',
label=_("Has console ports"), label="Has console ports",
) )
console_server_ports = django_filters.BooleanFilter( console_server_ports = django_filters.BooleanFilter(
method='_console_server_ports', method='_console_server_ports',
label=_("Has console server ports"), label="Has console server ports",
) )
power_ports = django_filters.BooleanFilter( power_ports = django_filters.BooleanFilter(
method='_power_ports', method='_power_ports',
label=_("Has power ports"), label="Has power ports",
) )
power_outlets = django_filters.BooleanFilter( power_outlets = django_filters.BooleanFilter(
method='_power_outlets', method='_power_outlets',
label=_("Has power outlets"), label="Has power outlets",
) )
interfaces = django_filters.BooleanFilter( interfaces = django_filters.BooleanFilter(
method='_interfaces', method='_interfaces',
label=_("Has interfaces"), label="Has interfaces",
) )
pass_through_ports = django_filters.BooleanFilter( pass_through_ports = django_filters.BooleanFilter(
method='_pass_through_ports', method='_pass_through_ports',
label=_("Has pass-through ports"), label="Has pass-through ports",
) )
config_template_id = django_filters.ModelMultipleChoiceFilter( config_template_id = django_filters.ModelMultipleChoiceFilter(
queryset=ConfigTemplate.objects.all(), queryset=ConfigTemplate.objects.all(),
label=_("Config template (ID)"), label="Config template (ID)",
) )
has_primary_ip = django_filters.BooleanFilter( has_primary_ip = django_filters.BooleanFilter(
method='_has_primary_ip', method='_has_primary_ip',
label=_("Has a primary IP"), label="Has a primary IP",
) )
has_oob_ip = django_filters.BooleanFilter( has_oob_ip = django_filters.BooleanFilter(
method='_has_oob_ip', method='_has_oob_ip',
label=_("Has an out-of-band IP"), label="Has an out-of-band IP",
) )
virtual_chassis_member = django_filters.BooleanFilter( virtual_chassis_member = django_filters.BooleanFilter(
method='_virtual_chassis_member', method='_virtual_chassis_member',
label=_("Is a virtual chassis member"), label="Is a virtual chassis member",
) )
class Meta: class Meta:
+57 -117
View File
@@ -1,3 +1,4 @@
from cProfile import label
from django import forms from django import forms
from django.conf import settings from django.conf import settings
@@ -34,13 +35,9 @@ class DeviceFilterForm(
fieldsets = ( fieldsets = (
FieldSet('q', 'filter_id', 'tag'), FieldSet('q', 'filter_id', 'tag'),
FieldSet( FieldSet(
'group', 'ignore_cable_type', 'save_coords', 'show_unconnected', 'show_cables', 'show_wireless', 'group', 'ignore_cable_type', 'save_coords', 'show_unconnected', 'show_cables', 'show_logical_connections',
'show_logical_connections', 'show_single_cable_logical_conns', 'show_neighbors', 'show_single_cable_logical_conns', 'show_neighbors', 'show_circuit', 'show_power', 'show_wireless',
'group_sites', 'group_locations', 'group_racks', 'group_virtualchassis', 'straight_cables', 'group_sites', 'group_locations', 'group_racks', 'group_virtualchassis', 'straight_cables', 'grid_size', 'node_label_items', name=_("Options")
'draw_termination_labels', 'draw_cable_labels', 'grid_size', 'node_label_items', name=_("Options")
),
FieldSet(
'show_circuit', 'show_power', name=_("Additional filter-independent types (non-devices)")
), ),
FieldSet('id', name=_("Device")), FieldSet('id', name=_("Device")),
FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_("Location")), FieldSet('region_id', 'site_group_id', 'site_id', 'location_id', 'rack_id', name=_("Location")),
@@ -158,7 +155,7 @@ class DeviceFilterForm(
platform_id = DynamicModelMultipleChoiceField( platform_id = DynamicModelMultipleChoiceField(
queryset=Platform.objects.all(), queryset=Platform.objects.all(),
required=False, required=False,
null_option=_('None'), null_option='None',
label=_('Platform') label=_('Platform')
) )
console_ports = forms.NullBooleanField( console_ports = forms.NullBooleanField(
@@ -229,6 +226,7 @@ class DeviceFilterForm(
choices=BOOLEAN_WITH_BLANK_CHOICES choices=BOOLEAN_WITH_BLANK_CHOICES
) )
) )
tag = TagFilterField(model) tag = TagFilterField(model)
# options # options
@@ -263,12 +261,7 @@ class DeviceFilterForm(
choices=BOOLEAN_WITH_BLANK_CHOICES choices=BOOLEAN_WITH_BLANK_CHOICES
) )
) )
show_wireless = forms.NullBooleanField(
label =_('Show Wireless Links'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_logical_connections = forms.NullBooleanField( show_logical_connections = forms.NullBooleanField(
label =_('Show Logical Connections'), required=False, initial=False, label =_('Show Logical Connections'), required=False, initial=False,
widget=forms.Select( widget=forms.Select(
@@ -287,6 +280,24 @@ class DeviceFilterForm(
choices=BOOLEAN_WITH_BLANK_CHOICES choices=BOOLEAN_WITH_BLANK_CHOICES
) )
) )
show_circuit = forms.NullBooleanField(
label=_('Show Circuit Terminations'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_power = forms.NullBooleanField(
label=_('Show Power Feeds'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
show_wireless = forms.NullBooleanField(
label =_('Show Wireless Links'), required=False, initial=False,
widget=forms.Select(
choices=BOOLEAN_WITH_BLANK_CHOICES
)
)
group_sites = forms.NullBooleanField( group_sites = forms.NullBooleanField(
label =_('Group Sites'), required=False, initial=False, label =_('Group Sites'), required=False, initial=False,
widget=forms.Select( widget=forms.Select(
@@ -317,18 +328,6 @@ class DeviceFilterForm(
choices=BOOLEAN_WITH_BLANK_CHOICES 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( grid_size = forms.IntegerField(
label=_('Grid Size'), label=_('Grid Size'),
required=False, required=False,
@@ -343,43 +342,6 @@ class DeviceFilterForm(
choices=NodeLabelItems 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): class CoordinateGroupsForm(NetBoxModelForm):
fieldsets = ( fieldsets = (
FieldSet('name', 'description', name=_("Group Details")), FieldSet('name', 'description', name=_("Group Details")),
@@ -560,27 +522,21 @@ class IndividualOptionsForm(NetBoxModelForm):
'save_coords', 'save_coords',
'show_unconnected', 'show_unconnected',
'show_cables', 'show_cables',
'show_wireless',
'show_logical_connections', 'show_logical_connections',
'show_single_cable_logical_conns', 'show_single_cable_logical_conns',
'show_neighbors', 'show_neighbors',
'show_circuit',
'show_power',
'show_wireless',
'group_sites', 'group_sites',
'group_locations', 'group_locations',
'group_racks', 'group_racks',
'group_virtualchassis', 'group_virtualchassis',
'draw_default_layout', 'draw_default_layout',
'straight_cables', 'straight_cables',
'draw_termination_labels',
'draw_cable_labels',
'grid_size', 'grid_size',
'node_label_items', 'node_label_items',
), ),
FieldSet
(
'show_circuit',
'show_power',
name=_("Additional filter-independent types (non-devices)")
),
) )
user_id = forms.CharField(widget=forms.HiddenInput()) user_id = forms.CharField(widget=forms.HiddenInput())
@@ -632,13 +588,6 @@ class IndividualOptionsForm(NetBoxModelForm):
'with one or more cables. These connections are displayed as solid ' 'with one or more cables. These connections are displayed as solid '
'lines in the color of the cable.') '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( show_logical_connections = forms.BooleanField(
label =_('Show Logical Connections'), label =_('Show Logical Connections'),
required=False, required=False,
@@ -648,7 +597,7 @@ class IndividualOptionsForm(NetBoxModelForm):
'are displayed as yellow dotted lines.') 'are displayed as yellow dotted lines.')
) )
show_single_cable_logical_conns = forms.BooleanField( show_single_cable_logical_conns = forms.BooleanField(
label = _('Show redundant Cable and Logical Connection'), label = ('Show redundant Cable and Logical Connection'),
required = False, required = False,
initial=False, initial=False,
help_text=_('Shows a logical connection (in addition to a cable), ' help_text=_('Shows a logical connection (in addition to a cable), '
@@ -664,6 +613,28 @@ class IndividualOptionsForm(NetBoxModelForm):
'Link peers will be added if \'Show Cables\' is ticked, far-end ' 'Link peers will be added if \'Show Cables\' is ticked, far-end '
'terminations will be added if \'Show Logical Connections\' is ticked.') '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.')
)
group_sites = forms.BooleanField( group_sites = forms.BooleanField(
label =_('Group Sites'), label =_('Group Sites'),
required=False, required=False,
@@ -693,32 +664,19 @@ class IndividualOptionsForm(NetBoxModelForm):
'same virtual chassis.') 'same virtual chassis.')
) )
draw_default_layout = forms.BooleanField( draw_default_layout = forms.BooleanField(
label = _('Draw Default Layout'), label = ('Draw Default Layout'),
required=False, required=False,
initial=False, initial=False,
help_text=_('Enable this option if you want to draw the topology on ' help_text=_('Enable this option if you want to draw the topology on '
'the initial load (when you go to the topology plugin page).') 'the initial load (when you go to the topology plugin page).')
) )
straight_cables = forms.BooleanField( straight_cables = forms.BooleanField(
label=_('Use Straight Cables'), label=('Use Straight Cables'),
required=False, required=False,
initial=False, initial=False,
help_text=_('Enable this option if you want to draw cables as straight lines ' help_text=_('Enable this option if you want to draw cables as straight lines '
'instead of curves.') '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( grid_size = forms.IntegerField(
label=_('Grid Size'), label=_('Grid Size'),
required=True, required=True,
@@ -735,31 +693,13 @@ class IndividualOptionsForm(NetBoxModelForm):
choices=NodeLabelItems, choices=NodeLabelItems,
help_text=_('Choose Label Items that you want to be displayed.') 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: class Meta:
model = IndividualOptions model = IndividualOptions
fields = [ fields = [
'user_id', 'ignore_cable_type', 'preselected_device_roles', 'preselected_tags', 'user_id', 'ignore_cable_type', 'preselected_device_roles', 'preselected_tags',
'save_coords', 'show_unconnected', 'show_cables', 'show_wireless', 'save_coords', 'show_unconnected', 'show_cables', 'show_logical_connections',
'show_logical_connections', 'show_single_cable_logical_conns', 'show_neighbors', 'show_single_cable_logical_conns', 'show_neighbors', 'show_circuit', 'show_power',
'group_sites', 'group_locations', 'group_racks', 'group_virtualchassis', 'show_wireless', 'group_sites', 'group_locations', 'group_racks', 'group_virtualchassis', 'draw_default_layout',
'draw_default_layout', 'straight_cables', 'draw_termination_labels', 'draw_cable_labels', 'straight_cables', 'grid_size', 'node_label_items'
'grid_size', 'node_label_items', 'show_circuit', 'show_power'
] ]
File diff suppressed because it is too large. Load diff
@@ -1,18 +0,0 @@
# 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),
),
]
@@ -1,18 +0,0 @@
# 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),
),
]
+33 -66
View File
@@ -9,7 +9,6 @@ from django.contrib.contenttypes.models import ContentType
from django.db import models from django.db import models
from django.templatetags.static import static from django.templatetags.static import static
from django.urls import reverse from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from netbox.models import NetBoxModel from netbox.models import NetBoxModel
from netbox.models.features import ( from netbox.models.features import (
ChangeLoggingMixin, ChangeLoggingMixin,
@@ -30,15 +29,13 @@ from netbox_topology_views.choices import NodeLabelItems
class RoleImage(ChangeLoggingMixin, ExportTemplatesMixin, EventRulesMixin): class RoleImage(ChangeLoggingMixin, ExportTemplatesMixin, EventRulesMixin):
class Meta: class Meta:
verbose_name = _('role image')
verbose_name_plural = _('role images')
indexes = [ indexes = [
models.Index(fields=["content_type", "object_id"]), models.Index(fields=["content_type", "object_id"]),
] ]
objects: "models.Manager[RoleImage]" 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) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField(null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True)
@@ -108,13 +105,11 @@ class CoordinateGroup(NetBoxModel):
This allows different visualizations with the same devices. This allows different visualizations with the same devices.
""" """
name = models.CharField( name = models.CharField(
verbose_name=_('name'),
max_length=100, max_length=100,
unique=True, unique=True,
) )
description = models.CharField( description = models.CharField(
verbose_name=_('description'),
max_length=255, max_length=255,
blank = True, blank = True,
) )
@@ -123,8 +118,6 @@ class CoordinateGroup(NetBoxModel):
class Meta: class Meta:
ordering = ['name'] ordering = ['name']
verbose_name = _('coordinate group')
verbose_name_plural = _('coordinate groups')
def __str__(self): def __str__(self):
return self.name return self.name
@@ -138,18 +131,16 @@ class Coordinate(NetBoxModel):
position. Devices belong to one or more coordinate groups. They have to position. Devices belong to one or more coordinate groups. They have to
be unique together. be unique together.
""" """
device = models.ForeignKey(Device, on_delete=models.CASCADE, verbose_name=_('device')) device = models.ForeignKey(Device, on_delete=models.CASCADE)
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group')) group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE)
x = models.IntegerField( x = models.IntegerField(
verbose_name=_('X'), help_text='X-coordinate of the device (horizontal) on the canvas. '
help_text=_('X-coordinate of the device (horizontal) on the canvas. ' 'Smaller values correspond to a position further to the left on the monitor.',
'Smaller values correspond to a position further to the left on the monitor.'),
) )
y = models.IntegerField( y = models.IntegerField(
verbose_name=_('Y'), help_text='Y-coordinate of the device (vertical) on the canvas. '
help_text=_('Y-coordinate of the device (vertical) on the canvas. ' 'Smaller values correspond to a position further up on the monitor.',
'Smaller values correspond to a position further up on the monitor.'),
) )
_netbox_private = True _netbox_private = True
@@ -165,9 +156,9 @@ class Coordinate(NetBoxModel):
else: else:
group = CoordinateGroup( group = CoordinateGroup(
name="default", 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 " "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.save()
group_id = group.pk group_id = group.pk
@@ -178,8 +169,6 @@ class Coordinate(NetBoxModel):
class Meta: class Meta:
ordering = ['group', 'device'] ordering = ['group', 'device']
unique_together = ('device', 'group') unique_together = ('device', 'group')
verbose_name = _('device coordinate')
verbose_name_plural = _('device coordinates')
def __str__(self): def __str__(self):
return f'{self.x};{self.y}' return f'{self.x};{self.y}'
@@ -193,18 +182,16 @@ class CircuitCoordinate(NetBoxModel):
position. Devices belong to one or more coordinate groups. They have to position. Devices belong to one or more coordinate groups. They have to
be unique together. be unique together.
""" """
device = models.ForeignKey(Circuit, on_delete=models.CASCADE, verbose_name=_('circuit')) device = models.ForeignKey(Circuit, on_delete=models.CASCADE)
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group')) group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE)
x = models.IntegerField( x = models.IntegerField(
verbose_name=_('X'), help_text='X-coordinate of the device (horizontal) on the canvas. '
help_text=_('X-coordinate of the device (horizontal) on the canvas. ' 'Smaller values correspond to a position further to the left on the monitor.',
'Smaller values correspond to a position further to the left on the monitor.'),
) )
y = models.IntegerField( y = models.IntegerField(
verbose_name=_('Y'), help_text='Y-coordinate of the device (vertical) on the canvas. '
help_text=_('Y-coordinate of the device (vertical) on the canvas. ' 'Smaller values correspond to a position further up on the monitor.',
'Smaller values correspond to a position further up on the monitor.'),
) )
_netbox_private = True _netbox_private = True
@@ -220,9 +207,9 @@ class CircuitCoordinate(NetBoxModel):
else: else:
group = CoordinateGroup( group = CoordinateGroup(
name="default", 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 " "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.save()
group_id = group.pk group_id = group.pk
@@ -233,8 +220,6 @@ class CircuitCoordinate(NetBoxModel):
class Meta: class Meta:
ordering = ['group', 'device'] ordering = ['group', 'device']
unique_together = ('device', 'group') unique_together = ('device', 'group')
verbose_name = _('circuit coordinate')
verbose_name_plural = _('circuit coordinates')
def __str__(self): def __str__(self):
return f'{self.x};{self.y}' return f'{self.x};{self.y}'
@@ -248,18 +233,16 @@ class PowerPanelCoordinate(NetBoxModel):
position. Devices belong to one or more coordinate groups. They have to position. Devices belong to one or more coordinate groups. They have to
be unique together. be unique together.
""" """
device = models.ForeignKey(PowerPanel, on_delete=models.CASCADE, verbose_name=_('power panel')) device = models.ForeignKey(PowerPanel, on_delete=models.CASCADE)
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group')) group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE)
x = models.IntegerField( x = models.IntegerField(
verbose_name=_('X'), help_text='X-coordinate of the device (horizontal) on the canvas. '
help_text=_('X-coordinate of the device (horizontal) on the canvas. ' 'Smaller values correspond to a position further to the left on the monitor.',
'Smaller values correspond to a position further to the left on the monitor.'),
) )
y = models.IntegerField( y = models.IntegerField(
verbose_name=_('Y'), help_text='Y-coordinate of the device (vertical) on the canvas. '
help_text=_('Y-coordinate of the device (vertical) on the canvas. ' 'Smaller values correspond to a position further up on the monitor.',
'Smaller values correspond to a position further up on the monitor.'),
) )
_netbox_private = True _netbox_private = True
@@ -275,9 +258,9 @@ class PowerPanelCoordinate(NetBoxModel):
else: else:
group = CoordinateGroup( group = CoordinateGroup(
name="default", 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 " "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.save()
group_id = group.pk group_id = group.pk
@@ -288,8 +271,6 @@ class PowerPanelCoordinate(NetBoxModel):
class Meta: class Meta:
ordering = ['group', 'device'] ordering = ['group', 'device']
unique_together = ('device', 'group') unique_together = ('device', 'group')
verbose_name = _('power panel coordinate')
verbose_name_plural = _('power panel coordinates')
def __str__(self): def __str__(self):
return f'{self.x};{self.y}' return f'{self.x};{self.y}'
@@ -303,18 +284,16 @@ class PowerFeedCoordinate(NetBoxModel):
position. Devices belong to one or more coordinate groups. They have to position. Devices belong to one or more coordinate groups. They have to
be unique together. be unique together.
""" """
device = models.ForeignKey(PowerFeed, on_delete=models.CASCADE, verbose_name=_('power feed')) device = models.ForeignKey(PowerFeed, on_delete=models.CASCADE)
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group')) group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE)
x = models.IntegerField( x = models.IntegerField(
verbose_name=_('X'), help_text='X-coordinate of the device (horizontal) on the canvas. '
help_text=_('X-coordinate of the device (horizontal) on the canvas. ' 'Smaller values correspond to a position further to the left on the monitor.',
'Smaller values correspond to a position further to the left on the monitor.'),
) )
y = models.IntegerField( y = models.IntegerField(
verbose_name=_('Y'), help_text='Y-coordinate of the device (vertical) on the canvas. '
help_text=_('Y-coordinate of the device (vertical) on the canvas. ' 'Smaller values correspond to a position further up on the monitor.',
'Smaller values correspond to a position further up on the monitor.'),
) )
_netbox_private = True _netbox_private = True
@@ -330,9 +309,9 @@ class PowerFeedCoordinate(NetBoxModel):
else: else:
group = CoordinateGroup( group = CoordinateGroup(
name="default", 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 " "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.save()
group_id = group.pk group_id = group.pk
@@ -343,8 +322,6 @@ class PowerFeedCoordinate(NetBoxModel):
class Meta: class Meta:
ordering = ['group', 'device'] ordering = ['group', 'device']
unique_together = ('device', 'group') unique_together = ('device', 'group')
verbose_name = _('power feed coordinate')
verbose_name_plural = _('power feed coordinates')
def __str__(self): def __str__(self):
return f'{self.x};{self.y}' return f'{self.x};{self.y}'
@@ -428,12 +405,6 @@ class IndividualOptions(NetBoxModel):
straight_cables = models.BooleanField( straight_cables = models.BooleanField(
default=False default=False
) )
draw_termination_labels = models.BooleanField(
default=False
)
draw_cable_labels = models.BooleanField(
default=False
)
grid_size = models.PositiveSmallIntegerField( grid_size = models.PositiveSmallIntegerField(
default=0 default=0
) )
@@ -444,9 +415,5 @@ class IndividualOptions(NetBoxModel):
_netbox_private = True _netbox_private = True
class Meta:
verbose_name = _('individual options')
verbose_name_plural = _('individual options')
def __str___(self): def __str___(self):
return f"{self.user_id}" return f"{self.user_id}"
+22 -28
View File
@@ -1,16 +1,15 @@
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginMenu, PluginMenuItem, PluginMenuButton from netbox.plugins import PluginMenu, PluginMenuItem, PluginMenuButton
coordinategroup_buttons = ( coordinategroup_buttons = (
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:coordinategroup_add', link='plugins:netbox_topology_views:coordinategroup_add',
title=_('Add'), title='Add',
icon_class='mdi mdi-plus-thick', icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinategroup'] permissions=['netbox_topology_views.add_coordinategroup']
), ),
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:coordinategroup_import', link='plugins:netbox_topology_views:coordinategroup_import',
title=_('Import'), title='Import',
icon_class='mdi mdi-upload', icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinategroup'] permissions=['netbox_topology_views.add_coordinategroup']
) )
@@ -19,13 +18,13 @@ coordinategroup_buttons = (
circuitcoordinate_buttons = ( circuitcoordinate_buttons = (
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:circuitcoordinate_add', link='plugins:netbox_topology_views:circuitcoordinate_add',
title=_('Add'), title='Add',
icon_class='mdi mdi-plus-thick', icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
), ),
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:circuitcoordinate_import', link='plugins:netbox_topology_views:circuitcoordinate_import',
title=_('Import'), title='Import',
icon_class='mdi mdi-upload', icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
) )
@@ -34,13 +33,13 @@ circuitcoordinate_buttons = (
powerpanelcoordinate_buttons = ( powerpanelcoordinate_buttons = (
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:powerpanelcoordinate_add', link='plugins:netbox_topology_views:powerpanelcoordinate_add',
title=_('Add'), title='Add',
icon_class='mdi mdi-plus-thick', icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
), ),
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:powerpanelcoordinate_import', link='plugins:netbox_topology_views:powerpanelcoordinate_import',
title=_('Import'), title='Import',
icon_class='mdi mdi-upload', icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
) )
@@ -49,13 +48,13 @@ powerpanelcoordinate_buttons = (
powerfeedcoordinate_buttons = ( powerfeedcoordinate_buttons = (
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:powerfeedcoordinate_add', link='plugins:netbox_topology_views:powerfeedcoordinate_add',
title=_('Add'), title='Add',
icon_class='mdi mdi-plus-thick', icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
), ),
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:powerfeedcoordinate_import', link='plugins:netbox_topology_views:powerfeedcoordinate_import',
title=_('Import'), title='Import',
icon_class='mdi mdi-upload', icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
) )
@@ -64,45 +63,40 @@ powerfeedcoordinate_buttons = (
coordinate_buttons = ( coordinate_buttons = (
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:coordinate_add', link='plugins:netbox_topology_views:coordinate_add',
title=_('Add'), title='Add',
icon_class='mdi mdi-plus-thick', icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
), ),
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:coordinate_import', link='plugins:netbox_topology_views:coordinate_import',
title=_('Import'), title='Import',
icon_class='mdi mdi-upload', icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
) )
) )
menu = PluginMenu( menu = PluginMenu(
label=_('Topology Views'), label='Topology Views',
icon_class="mdi mdi-sitemap", icon_class="mdi mdi-sitemap",
groups=( 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:home", link_text="Topology", permissions=["dcim.view_site", "dcim.view_device"]),
), ),
), ),
(_('More views'), ('COORDINATES',
( (
PluginMenuItem(link="plugins:netbox_topology_views:rack_elevation", link_text=_("Rack view"), permissions=["dcim.view_rack", "dcim.view_device", "dcim.view_cable"]), 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']),
), ),
), ),
(_('Coordinates'), ('PREFERENCES',
( (
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:images", link_text="Images", permissions=[ "dcim.view_site","dcim.view_devicerole"]),
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:individualoptions", link_text="Individual Options", permissions=['netbox_topology_views.change_individualoptions']),
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;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}} #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}
@@ -1,159 +0,0 @@
.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 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 510 B

@@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 508 B

@@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 525 B

@@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 522 B

@@ -1,6 +1,6 @@
(()=>{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 (()=>{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,be=(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 Us=(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((Va,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 me(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,Xs=["","webkit","Moz","MS","ms","o"],Bn=typeof document=="undefined"?{style:{}}:document.createElement("div"),An="function",Je=Math.round,Ue=Math.abs,bi=Date.now;function zt(r,e){for(var t,s,o=e[0].toUpperCase()+e.slice(1),n=0;n<Xs.length;){if(t=Xs[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 `+t+` AT
`;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 `;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=ge,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=Xe,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}(),qa=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
`: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: `: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=` `){let o=`
@@ -11,7 +11,7 @@
`;for(let n=0;n<e.length+1;n++){for(let a=0;a<e.length-n;a++)o+=" ";o+=`} `;for(let n=0;n<e.length+1;n++){for(let a=0;a<e.length-n;a++)o+=" ";o+=`}
`}return 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 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 `}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,Uo=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 Xo=/^(?:[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"&&Xo.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)}},Ut=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)===` `||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!=` `||Re.charAt(e)===""){for(;B!=""&&B!=`
`;)J();r=!0}}if(B==="/"&&nt()==="/"){for(;B!=""&&B!=` `;)J();r=!0}}if(B==="/"&&nt()==="/"){for(;B!=""&&B!=`
@@ -20,7 +20,7 @@
`,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 `,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,` `),e=e.replace(/\r/g,`
`);let s=String(e).split(` `);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 `),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: /*! Bundled license information:
@egjs/hammerjs/dist/hammer.esm.js: @egjs/hammerjs/dist/hammer.esm.js:
@@ -1 +1 @@
(()=>{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();})(); (()=>{var l=(o,t)=>()=>(o&&(t=o(o=0)),t);var k=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var d=(o,t,e)=>new Promise((n,r)=>{var c=s=>{try{i(e.next(s))}catch(a){r(a)}},y=s=>{try{i(e.throw(s))}catch(a){r(a)}},i=s=>s.done?n(s.value):Promise.resolve(s.value).then(c,y);i((e=e.apply(o,t)).next())});var g,m=l(()=>{g=o=>{if(!document.cookie)return;let t=null,e=document.cookie.split(";");for(let n=0;n<e.length;n++){let r=e[n].trim();if(r.substring(0,o.length+1)===o+"="){t=decodeURIComponent(r.substring(o.length+1));break}}return t}});var u,p=l(()=>{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 S=k(w=>{m();p();var f={},h=g("csrftoken");document.querySelector("form#images").addEventListener("submit",o=>d(null,null,function*(){o.preventDefault();try{let t=yield fetch("/"+basePath+"api/plugins/netbox_topology_views/images/save/",{method:"POST",body:JSON.stringify(f),headers:{"X-CSRFToken":h,"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(o=>{o.addEventListener("click",t=>{var c;if(!(t.currentTarget instanceof HTMLElement))return;let{dataset:{role:e,image:n}}=t.currentTarget;f[e]=n;let r=(c=t.currentTarget.closest(".dropdown"))==null?void 0:c.querySelector(`#dropdownMenuButton${e}`);r&&(r.innerHTML=`<img src="${n}" />`)})})});S();})();
@@ -1,6 +1,6 @@
{ {
"version": 3, "version": 3,
"sources": ["../../../static_dev/js/toast.js", "../../../static_dev/js/images.js"], "sources": ["../../../static_dev/js/csrftoken.js", "../../../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", "mappings": "oTAAA,IAAaA,EAAbC,EAAAC,EAAA,KAAaF,EAAaG,GAAS,CAC/B,GAAI,CAAC,SAAS,OAAQ,OAEtB,IAAIC,EAAc,KACZC,EAAU,SAAS,OAAO,MAAM,GAAG,EAEzC,QAASC,EAAI,EAAGA,EAAID,EAAQ,OAAQC,IAAK,CACrC,IAAMC,EAASF,EAAQC,CAAC,EAAE,KAAK,EAE/B,GAAIC,EAAO,UAAU,EAAGJ,EAAK,OAAS,CAAC,IAAMA,EAAO,IAAK,CACrDC,EAAc,mBAAmBG,EAAO,UAAUJ,EAAK,OAAS,CAAC,CAAC,EAClE,KACJ,CACJ,CAEA,OAAOC,CACX,IChBA,IAAaI,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,IACAC,IAEA,IAAMC,EAAU,CAAC,EACXC,EAAYC,EAAU,WAAW,EAEvC,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,UAAUL,CAAO,EAC5B,QAAS,CACL,cAAeC,EACf,eAAgB,kBACpB,CACJ,CAAC,EAED,GAAI,CAACI,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,CA3BxC,IAAAM,EA4BQ,GAAI,EAAEN,EAAE,yBAAyB,aAAc,OAC/C,GAAM,CACF,QAAS,CAAE,KAAAO,EAAM,MAAAC,CAAM,CAC3B,EAAIR,EAAE,cAENH,EAAQU,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"] "names": ["getCookie", "init_csrftoken", "__esmMin", "name", "cookieValue", "cookies", "i", "cookie", "toast", "init_toast", "__esmMin", "message", "el", "content", "require_images", "__commonJSMin", "exports", "init_csrftoken", "init_toast", "mapping", "csrftoken", "getCookie", "e", "__async", "res", "toast", "err", "el", "_a", "role", "image", "button"]
} }
@@ -26,69 +26,3 @@ html[data-netbox-color-mode=dark] #visgraph {
cursor: pointer; 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; }
}
@@ -0,0 +1,17 @@
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
}
+6 -54
View File
@@ -1,43 +1,6 @@
import { DataSet } from 'vis-data/esnext' import { DataSet } from 'vis-data/esnext'
import { Network } from 'vis-network/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 = { const options = {
interaction: { interaction: {
@@ -73,6 +36,9 @@ const options = {
} }
} }
// Load CSRF token
const csrftoken = getCookie('csrftoken')
// Render vis graph // Render vis graph
let graph = null // vis graph instance let graph = null // vis graph instance
@@ -100,21 +66,7 @@ const coordSaveCheckbox = document.querySelector('#id_save_coords')
const edges = new DataSet( const edges = new DataSet(
topologyData.edges.map((node) => ({ topologyData.edges.map((node) => ({
...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)
}
}
})
})) }))
) )
@@ -276,7 +228,7 @@ const coordSaveCheckbox = document.querySelector('#id_save_coords')
{ {
method: 'PATCH', method: 'PATCH',
headers: { headers: {
'X-CSRFToken': window.CSRF_TOKEN, 'X-CSRFToken': csrftoken,
Accept: 'application/json', Accept: 'application/json',
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
@@ -1,6 +1,8 @@
import { getCookie } from './csrftoken.js'
import { toast } from './toast.js' import { toast } from './toast.js'
const mapping = {} const mapping = {}
const csrftoken = getCookie('csrftoken')
document.querySelector('form#images').addEventListener('submit', async (e) => { document.querySelector('form#images').addEventListener('submit', async (e) => {
e.preventDefault() e.preventDefault()
@@ -9,13 +11,13 @@ document.querySelector('form#images').addEventListener('submit', async (e) => {
method: 'POST', method: 'POST',
body: JSON.stringify(mapping), body: JSON.stringify(mapping),
headers: { headers: {
'X-CSRFToken': window.CSRF_TOKEN, 'X-CSRFToken': csrftoken,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}) })
if (!res.ok) throw new Error(await res.text()) if (!res.ok) throw new Error(await res.text())
toast.success(window.topologyI18n?.savedSettings ?? 'Saved settings') toast.success('Saved settings')
} catch (err) { } catch (err) {
console.dir(err) console.dir(err)
toast.error(err.message) toast.error(err.message)
+9 -11
View File
@@ -1,12 +1,12 @@
{ {
"name": "netbox_topology_views", "name": "netbox_topology_views",
"version": "4.5.0", "version": "4.3.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "netbox_topology_views", "name": "netbox_topology_views",
"version": "4.5.0", "version": "4.3.0",
"dependencies": { "dependencies": {
"vis-data": "^7.1.9", "vis-data": "^7.1.9",
"vis-network": "^9.1.9", "vis-network": "^9.1.9",
@@ -904,11 +904,10 @@
} }
}, },
"node_modules/immutable": { "node_modules/immutable": {
"version": "5.1.5", "version": "5.1.2",
"resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.5.tgz", "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.2.tgz",
"integrity": "sha512-t7xcm2siw+hlUM68I+UEOK+z84RzmN59as9DZ7P1l0994DKUWV7UXBMQZVxaoMSRQ+PBZbHCOoBt7a2wxOMt+A==", "integrity": "sha512-qHKXW1q6liAk1Oys6umoaZbDRqjcjgSrbnrifHsfsttza7zcvRAsL7mMV6xWcyhwQy7Xj5v4hhbr6b+iDYwlmQ==",
"dev": true, "dev": true
"license": "MIT"
}, },
"node_modules/is-core-module": { "node_modules/is-core-module": {
"version": "2.16.1", "version": "2.16.1",
@@ -991,11 +990,10 @@
"dev": true "dev": true
}, },
"node_modules/picomatch": { "node_modules/picomatch": {
"version": "2.3.2", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true, "dev": true,
"license": "MIT",
"optional": true, "optional": true,
"engines": { "engines": {
"node": ">=8.6" "node": ">=8.6"
@@ -1,7 +1,7 @@
{ {
"private": true, "private": true,
"name": "netbox_topology_views", "name": "netbox_topology_views",
"version": "4.5.1", "version": "4.3.0",
"scripts": { "scripts": {
"bundle": "node bundle.js", "bundle": "node bundle.js",
"bundle:styles": "node bundle.js --styles", "bundle:styles": "node bundle.js --styles",
+1 -2
View File
@@ -1,5 +1,4 @@
import django_tables2 as tables import django_tables2 as tables
from django.utils.translation import gettext_lazy as _
from netbox.tables import NetBoxTable, ChoiceFieldColumn from netbox.tables import NetBoxTable, ChoiceFieldColumn
from netbox_topology_views.models import CoordinateGroup, Coordinate, CircuitCoordinate, PowerPanelCoordinate, PowerFeedCoordinate from netbox_topology_views.models import CoordinateGroup, Coordinate, CircuitCoordinate, PowerPanelCoordinate, PowerFeedCoordinate
@@ -8,7 +7,7 @@ class CoordinateGroupListTable(NetBoxTable):
name = tables.Column( name = tables.Column(
linkify=True linkify=True
) )
devices = tables.Column(verbose_name=_('Devices')) devices = tables.Column()
class Meta(NetBoxTable.Meta): class Meta(NetBoxTable.Meta):
model = CoordinateGroup model = CoordinateGroup
+20
View File
@@ -0,0 +1,20 @@
from netbox.plugins import PluginTemplateExtension
from django.conf import settings
from packaging import version
NETBOX_CURRENT_VERSION = version.parse(settings.RELEASE.version)
class SiteButtons(PluginTemplateExtension):
models = ('dcim.site', )
def buttons(self):
return self.render('netbox_topology_views/site_button.html')
class LocationButtons(PluginTemplateExtension):
models = ('dcim.location', )
def buttons(self):
return self.render('netbox_topology_views/location_button.html')
template_extensions = [SiteButtons, LocationButtons]
@@ -1,33 +1,32 @@
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %} {% block title %}Topology Views Coordinates{% endblock title %}
{% block content %} {% block content %}
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-6"> <div class="col col-md-6">
<div class="card"> <div class="card">
<h5 class="card-header"> <h5 class="card-header">
{% trans "Coordinates" %} Coordinates
</h5> </h5>
<div class="card-body"> <div class="card-body">
<table class="table table-hover attr-table"> <table class="table table-hover attr-table">
<tr> <tr>
<th scope="row">{% trans "Group" %}</th> <th scope="row">Group</th>
<td>{{ object.group|linkify }}</td> <td>{{ object.group|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "Circuit" %}</th> <th scope="row">Circuit</th>
<td>{{ object.device|linkify }}</td> <td>{{ object.device|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "X-Coordinate" %}</th> <th scope="row">X-Coordinate</th>
<td>{{ object.x }}</td> <td>{{ object.x }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "Y-Coordinate" %}</th> <th scope="row">Y-Coordinate</th>
<td>{{ object.y }}</td> <td>{{ object.y }}</td>
</tr> </tr>
</table> </table>
@@ -1,4 +1,3 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Add new Circuit Coordinates" %}{% endblock title %} {% block title %}Add new Circuit Coordinates{% endblock title %}
@@ -1,4 +1,3 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Edit Circuit Coordinates" %}{% endblock title %} {% block title %}Edit Circuit Coordinates{% endblock title %}
@@ -1,4 +1,3 @@
{% extends 'generic/object_list.html' %} {% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}{% trans "Circuit Coordinates" %}{% endblock title %} {% block title %}Circuit Coordinates{% endblock title %}
@@ -1,33 +1,32 @@
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %} {% block title %}Topology Views Coordinates{% endblock title %}
{% block content %} {% block content %}
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-6"> <div class="col col-md-6">
<div class="card"> <div class="card">
<h5 class="card-header"> <h5 class="card-header">
{% trans "Coordinates" %} Coordinates
</h5> </h5>
<div class="card-body"> <div class="card-body">
<table class="table table-hover attr-table"> <table class="table table-hover attr-table">
<tr> <tr>
<th scope="row">{% trans "Group" %}</th> <th scope="row">Group</th>
<td>{{ object.group|linkify }}</td> <td>{{ object.group|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "Device" %}</th> <th scope="row">Device</th>
<td>{{ object.device|linkify }}</td> <td>{{ object.device|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "X-Coordinate" %}</th> <th scope="row">X-Coordinate</th>
<td>{{ object.x }}</td> <td>{{ object.x }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "Y-Coordinate" %}</th> <th scope="row">Y-Coordinate</th>
<td>{{ object.y }}</td> <td>{{ object.y }}</td>
</tr> </tr>
</table> </table>
@@ -1,4 +1,3 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Add new Device Coordinates" %}{% endblock title %} {% block title %}Add new Device Coordinates{% endblock title %}
@@ -1,4 +1,3 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Edit Device Coordinates" %}{% endblock title %} {% block title %}Edit Device Coordinates{% endblock title %}
@@ -1,4 +1,3 @@
{% extends 'generic/object_list.html' %} {% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}{% trans "Device Coordinates" %}{% endblock title %} {% block title %}Device Coordinates{% endblock title %}
@@ -1,26 +1,25 @@
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% load render_table from django_tables2 %} {% load render_table from django_tables2 %}
{% block title %}{% trans "Topology Views Coordinate Group" %}{% endblock title %} {% block title %}Topology Views Coordinate Group{% endblock title %}
{% block content %} {% block content %}
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-6"> <div class="col col-md-6">
<div class="card"> <div class="card">
<h5 class="card-header"> <h5 class="card-header">
{% trans "Coordinate Group" %} Coordinate Group
</h5> </h5>
<div class="card-body"> <div class="card-body">
<table class="table table-hover attr-table"> <table class="table table-hover attr-table">
<tr> <tr>
<th scope="row">{% trans "Name" %}</th> <th scope="row">Name</th>
<td>{{ object.name }}</td> <td>{{ object.name }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "Description" %}</th> <th scope="row">Description</th>
<td>{{ object.description|placeholder }}</td> <td>{{ object.description|placeholder }}</td>
</tr> </tr>
</table> </table>
@@ -36,7 +35,7 @@
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-12"> <div class="col col-md-12">
<div class="card"> <div class="card">
<h5 class="card-header">{% trans "Circuit Coordinates" %}</h5> <h5 class="card-header">Circuit Coordinates</h5>
<div class="card-body table-responsive"> <div class="card-body table-responsive">
{% render_table circuitcoordinates_table %} {% render_table circuitcoordinates_table %}
</div> </div>
@@ -44,7 +43,7 @@
</div> </div>
<div class="col col-md-12"> <div class="col col-md-12">
<div class="card"> <div class="card">
<h5 class="card-header">{% trans "Power Panel Coordinates" %}</h5> <h5 class="card-header">Power Panel Coordinates</h5>
<div class="card-body table-responsive"> <div class="card-body table-responsive">
{% render_table powerpanelcoordinates_table %} {% render_table powerpanelcoordinates_table %}
</div> </div>
@@ -52,7 +51,7 @@
</div> </div>
<div class="col col-md-12"> <div class="col col-md-12">
<div class="card"> <div class="card">
<h5 class="card-header">{% trans "Power Feed Coordinates" %}</h5> <h5 class="card-header">Power Feed Coordinates</h5>
<div class="card-body table-responsive"> <div class="card-body table-responsive">
{% render_table powerfeedcoordinates_table %} {% render_table powerfeedcoordinates_table %}
</div> </div>
@@ -60,7 +59,7 @@
</div> </div>
<div class="col col-md-12"> <div class="col col-md-12">
<div class="card"> <div class="card">
<h5 class="card-header">{% trans "Device Coordinates" %}</h5> <h5 class="card-header">Device Coordinates</h5>
<div class="card-body table-responsive"> <div class="card-body table-responsive">
{% render_table coordinates_table %} {% render_table coordinates_table %}
</div> </div>
@@ -1,4 +1,3 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Add a new Coordinate Group" %}{% endblock title %} {% block title %}Add a new Coordinate Group{% endblock title %}
@@ -1,4 +1,3 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Edit Coordinate Group" %}{% endblock title %} {% block title %}Edit Coordinate Group{% endblock title %}
@@ -1,4 +1,3 @@
{% extends 'generic/object_list.html' %} {% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}{% trans "Coordinate Groups" %}{% endblock title %} {% block title %}Coordinate Groups{% endblock title %}
@@ -0,0 +1,45 @@
{% 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-info" href="#">
<i class="mdi mdi-download"></i>
Download XML
</a>
<a id="btnDownloadImage" class="btn btn-info" href="#">
<i class="mdi mdi-download"></i>
Download PNG
</a>
<a class="btn 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 }};
const basePath = '{{ basepath }}';
</script>
<script src="{% static 'netbox_topology_views/js/app.js' %}?ver={{ epoch }} " defer></script>
@@ -1,11 +1,10 @@
{% extends 'base/layout.html' %} {% extends 'base/layout.html' %}
{% load i18n %}
{% load buttons %} {% load buttons %}
{% load render_table from django_tables2 %} {% load render_table from django_tables2 %}
{% load helpers %} {% load helpers %}
{% load static %} {% load static %}
{% block title %}{% trans "Topology Views Images" %}{% endblock %} {% block title %}Topology Views Images{% endblock %}
{% block head %} {% block head %}
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/app.css' %}"> <link rel="stylesheet" href="{% static 'netbox_topology_views/css/app.css' %}">
@@ -21,7 +20,7 @@
{% if role.image %} {% if role.image %}
<img src="{{ role.image }}" /> <img src="{{ role.image }}" />
{% else %} {% else %}
{% trans "Image" %} Image
{% endif %} {% endif %}
</button> </button>
<div class="dropdown-menu mt-2" aria-labelledby="dropdownMenuButton{{ role.id }}"> <div class="dropdown-menu mt-2" aria-labelledby="dropdownMenuButton{{ role.id }}">
@@ -37,7 +36,7 @@
{% endfor %} {% endfor %}
</div> </div>
<button class="btn btn-primary" type="submit">{% trans "Save" %}</button> <button class="btn btn-primary" type="submit">Save</button>
</form> </form>
{% include 'netbox_topology_views/toasts.html' %} {% include 'netbox_topology_views/toasts.html' %}
{% endblock content %} {% endblock content %}
@@ -45,7 +44,6 @@
{% block javascript %} {% block javascript %}
<script type="text/javascript"> <script type="text/javascript">
const basePath = '{{ basepath }}'; const basePath = '{{ basepath }}';
window.topologyI18n = {savedSettings: '{{ _("Saved settings")|escapejs }}'};
</script> </script>
<script src="{% static 'netbox_topology_views/js/images.js' %}" defer></script> <script src="{% static 'netbox_topology_views/js/images.js' %}" defer></script>
{% endblock javascript %} {% endblock javascript %}
@@ -1,12 +1,11 @@
{% extends 'generic/_base.html' %} {% extends 'generic/_base.html' %}
{% load i18n %}
{% load buttons %} {% load buttons %}
{% load render_table from django_tables2 %} {% load render_table from django_tables2 %}
{% load static %} {% load static %}
{% load perms %} {% load perms %}
{% load helpers %} {% load helpers %}
{% block title %}{% trans "Topology Views" %}{% endblock %} {% block title %}Topology Views{% endblock %}
{% block head %} {% block head %}
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/vendor.css' %}"> <link rel="stylesheet" href="{% static 'netbox_topology_views/css/vendor.css' %}">
@@ -19,11 +18,11 @@
{% block extra_controls %}{% endblock %} {% block extra_controls %}{% endblock %}
<a id="btnDownloadXml" class="btn btn-info" href="#"> <a id="btnDownloadXml" class="btn btn-info" href="#">
<i class="mdi mdi-download"></i> <i class="mdi mdi-download"></i>
{% trans "Download XML" %} Download XML
</a> </a>
<a id="btnDownloadImage" class="btn btn-info" href="#"> <a id="btnDownloadImage" class="btn btn-info" href="#">
<i class="mdi mdi-download"></i> <i class="mdi mdi-download"></i>
{% trans "Download PNG" %} Download PNG
</a> </a>
</div> </div>
</div> </div>
@@ -34,13 +33,13 @@
{% block tab_items %} {% block tab_items %}
<li class="nav-item" role="presentation"> <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"> <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">
{% trans "Network" %} Network
</button> </button>
</li> </li>
{% if filter_form %} {% if filter_form %}
<li class="nav-item" role="presentation"> <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"> <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">
{% trans "Filters" %} Filters
{% if filter_form %}{% badge filter_form.changed_data|length bg_color="blue" %}{% endif %} {% if filter_form %}{% badge filter_form.changed_data|length bg_color="blue" %}{% endif %}
</button> </button>
</li> </li>
@@ -62,13 +61,6 @@
<div class="tab-pane show active" id="networks" role="tabpanel" aria-labelledby="network-tab"> <div class="tab-pane show active" id="networks" role="tabpanel" aria-labelledby="network-tab">
<div class="panel-body"> <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 id="visgraph"></div>
</div> </div>
</div> </div>
@@ -1,6 +1,5 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Topology Views Individual Options" %}{% endblock %} {% block title %}Topology Views Individual Options{% endblock %}
{% block tabs %} {% endblock tabs %} {% block tabs %} {% endblock tabs %}
@@ -1,5 +1,4 @@
{% load i18n %} <a role="button" class="btn btn-primary" title="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">
<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> <i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i>
{% trans "Topology" %} Topology
</a> </a>
@@ -1,33 +1,32 @@
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %} {% block title %}Topology Views Coordinates{% endblock title %}
{% block content %} {% block content %}
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-6"> <div class="col col-md-6">
<div class="card"> <div class="card">
<h5 class="card-header"> <h5 class="card-header">
{% trans "Coordinates" %} Coordinates
</h5> </h5>
<div class="card-body"> <div class="card-body">
<table class="table table-hover attr-table"> <table class="table table-hover attr-table">
<tr> <tr>
<th scope="row">{% trans "Group" %}</th> <th scope="row">Group</th>
<td>{{ object.group|linkify }}</td> <td>{{ object.group|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "Power Feed" %}</th> <th scope="row">Power Feed</th>
<td>{{ object.device|linkify }}</td> <td>{{ object.device|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "X-Coordinate" %}</th> <th scope="row">X-Coordinate</th>
<td>{{ object.x }}</td> <td>{{ object.x }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "Y-Coordinate" %}</th> <th scope="row">Y-Coordinate</th>
<td>{{ object.y }}</td> <td>{{ object.y }}</td>
</tr> </tr>
</table> </table>
@@ -1,4 +1,3 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Add new Power Feed Coordinates" %}{% endblock title %} {% block title %}Add new Power Feed Coordinates{% endblock title %}
@@ -1,4 +1,3 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Edit Power Feed Coordinates" %}{% endblock title %} {% block title %}Edit Power Feed Coordinates{% endblock title %}
@@ -1,4 +1,3 @@
{% extends 'generic/object_list.html' %} {% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}{% trans "Power Feed Coordinates" %}{% endblock title %} {% block title %}Power Feed Coordinates{% endblock title %}
@@ -1,33 +1,32 @@
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %} {% block title %}Topology Views Coordinates{% endblock title %}
{% block content %} {% block content %}
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-6"> <div class="col col-md-6">
<div class="card"> <div class="card">
<h5 class="card-header"> <h5 class="card-header">
{% trans "Coordinates" %} Coordinates
</h5> </h5>
<div class="card-body"> <div class="card-body">
<table class="table table-hover attr-table"> <table class="table table-hover attr-table">
<tr> <tr>
<th scope="row">{% trans "Group" %}</th> <th scope="row">Group</th>
<td>{{ object.group|linkify }}</td> <td>{{ object.group|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "Power Panel" %}</th> <th scope="row">Power Panel</th>
<td>{{ object.device|linkify }}</td> <td>{{ object.device|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "X-Coordinate" %}</th> <th scope="row">X-Coordinate</th>
<td>{{ object.x }}</td> <td>{{ object.x }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">{% trans "Y-Coordinate" %}</th> <th scope="row">Y-Coordinate</th>
<td>{{ object.y }}</td> <td>{{ object.y }}</td>
</tr> </tr>
</table> </table>
@@ -1,4 +1,3 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Add new Power Panel Coordinates" %}{% endblock title %} {% block title %}Add new Power Panel Coordinates{% endblock title %}
@@ -1,4 +1,3 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}{% trans "Edit Power Panel Coordinates" %}{% endblock title %} {% block title %}Edit Power Panel Coordinates{% endblock title %}
@@ -1,4 +1,3 @@
{% extends 'generic/object_list.html' %} {% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}{% trans "Power Panel Coordinates" %}{% endblock title %} {% block title %}Power Panel Coordinates{% endblock title %}
@@ -1,656 +0,0 @@
{% 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 %}
@@ -0,0 +1,4 @@
<a role="button" class="btn btn-primary" title="Topology" href="#" hx-get="/plugins/netbox_topology_views/topology/?site_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
</a>
@@ -1,4 +1,3 @@
{% load i18n %}
<div id="django-messages" class="toast-container"> <div id="django-messages" class="toast-container">
<div <div
id="topology-plugin-error-toast" id="topology-plugin-error-toast"
@@ -11,13 +10,13 @@
<div class="d-flex"> <div class="d-flex">
<div class="toast-body"> <div class="toast-body">
😢 😢
<span>{% trans "Error" %}</span> <span>Error</span>
</div> </div>
<button <button
type="button" type="button"
class="btn-close me-2 m-auto" class="btn-close me-2 m-auto"
data-bs-dismiss="toast" data-bs-dismiss="toast"
aria-label="{% trans "Close" %}" aria-label="Close"
></button> ></button>
</div> </div>
</div> </div>
@@ -32,13 +31,13 @@
<div class="d-flex"> <div class="d-flex">
<div class="toast-body"> <div class="toast-body">
👍 👍
<span>{% trans "Success" %}</span> <span>Success</span>
</div> </div>
<button <button
type="button" type="button"
class="btn-close me-2 m-auto" class="btn-close me-2 m-auto"
data-bs-dismiss="toast" data-bs-dismiss="toast"
aria-label="{% trans "Close" %}" aria-label="Close"
></button> ></button>
</div> </div>
</div> </div>
-1
View File
@@ -8,7 +8,6 @@ from . import models, views
urlpatterns = ( urlpatterns = (
path("", RedirectView.as_view(url="topology/", permanent=True)), path("", RedirectView.as_view(url="topology/", permanent=True)),
path("topology/", views.TopologyHomeView.as_view(), name="home"), 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("images/", views.TopologyImagesView.as_view(), name="images"),
path("individualoptions/", views.TopologyIndividualOptionsView.as_view(), name="individualoptions"), path("individualoptions/", views.TopologyIndividualOptionsView.as_view(), name="individualoptions"),
+6 -16
View File
@@ -12,7 +12,6 @@ from django.db.models import Model
from django.templatetags.static import static from django.templatetags.static import static
from django.utils.text import camel_case_to_spaces, re_camel_case from django.utils.text import camel_case_to_spaces, re_camel_case
from django.contrib import messages from django.contrib import messages
from django.utils.translation import gettext as _
IMAGE_DIR = Path(settings.STATIC_ROOT) / "netbox_topology_views/img" IMAGE_DIR = Path(settings.STATIC_ROOT) / "netbox_topology_views/img"
if sys.version_info >= (3,9,0): if sys.version_info >= (3,9,0):
@@ -30,8 +29,9 @@ else:
def image_static_url(path: Path) -> str: def image_static_url(path: Path) -> str:
# No leading slash: static file finders (e.g. the debug toolbar's) reject absolute paths. return static(
return static(path.relative_to(Path(settings.STATIC_ROOT)).as_posix()) f"/{path.relative_to(Path(settings.STATIC_ROOT))}"
)
def get_image_from_url(url: str) -> str: def get_image_from_url(url: str) -> str:
@@ -118,7 +118,7 @@ def get_query_settings(request):
# General options overrides # General options overrides
if save_coords == True and settings.PLUGINS_CONFIG["netbox_topology_views"]["allow_coordinates_saving"] == False: if save_coords == True and settings.PLUGINS_CONFIG["netbox_topology_views"]["allow_coordinates_saving"] == False:
save_coords = 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: elif settings.PLUGINS_CONFIG["netbox_topology_views"]["always_save_coordinates"] == True:
save_coords = True save_coords = True
@@ -196,16 +196,6 @@ def get_query_settings(request):
if request.GET["straight_cables"] == "True": if request.GET["straight_cables"] == "True":
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 grid_size = 0
if "grid_size" in request.GET: if "grid_size" in request.GET:
grid_size = request.GET.getlist('grid_size') grid_size = request.GET.getlist('grid_size')
@@ -214,7 +204,7 @@ def get_query_settings(request):
if "node_label_items" in request.GET: if "node_label_items" in request.GET:
node_label_items = request.GET.getlist('node_label_items') 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 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, grid_size, node_label_items
class LinePattern(): class LinePattern():
wireless = [2, 10, 2, 10] wireless = [2, 10, 2, 10]
@@ -344,7 +334,7 @@ def export_data_to_xml(data: dict):
if noPositionX > 0: if noPositionX > 0:
mxcell = doc.createElement('mxCell') mxcell = doc.createElement('mxCell')
mxcell.setAttribute('id', 'noPositionWarning') 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('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('vertex', '1')
mxcell.setAttribute('parent', '1') mxcell.setAttribute('parent', '1')
+52 -303
View File
@@ -1,10 +1,10 @@
import json import json
from functools import reduce from functools import reduce
from typing import DefaultDict, Dict, Optional, Union from typing import DefaultDict, Dict, Optional, Union
import time
from itertools import chain from itertools import chain
from circuits.models import Circuit, CircuitTermination, ProviderNetwork from circuits.models import Circuit, CircuitTermination, ProviderNetwork
from dcim.choices import CableTypeChoices
from dcim.models import ( from dcim.models import (
Cable, Cable,
CableTermination, CableTermination,
@@ -16,7 +16,6 @@ from dcim.models import (
PowerFeed, PowerFeed,
PowerPanel, PowerPanel,
RearPort, RearPort,
Rack,
) )
from django.conf import settings from django.conf import settings
from django.contrib import messages from django.contrib import messages
@@ -26,10 +25,10 @@ from django.db.models import Q, QuerySet, Count
from django.db.models.functions import Lower from django.db.models.functions import Lower
from django.http import HttpRequest, HttpResponseRedirect, QueryDict from django.http import HttpRequest, HttpResponseRedirect, QueryDict
from django.shortcuts import render, get_object_or_404 from django.shortcuts import render, get_object_or_404
from django.utils.translation import gettext as _
from django.views.generic import View from django.views.generic import View
from extras.models import Tag, SavedFilter from extras.models import Tag, SavedFilter
from wireless.models import WirelessLAN, WirelessLink from wireless.models import WirelessLink
from utilities.htmx import htmx_partial
from netbox.views.generic import ( from netbox.views.generic import (
ObjectView, ObjectView,
ObjectListView, ObjectListView,
@@ -41,7 +40,6 @@ from netbox.views.generic import (
from netbox_topology_views.filters import DeviceFilterSet, CoordinatesFilterSet, CircuitCoordinatesFilterSet, PowerPanelCoordinatesFilterSet, PowerFeedCoordinatesFilterSet from netbox_topology_views.filters import DeviceFilterSet, CoordinatesFilterSet, CircuitCoordinatesFilterSet, PowerPanelCoordinatesFilterSet, PowerFeedCoordinatesFilterSet
from netbox_topology_views.forms import ( from netbox_topology_views.forms import (
DeviceFilterForm, DeviceFilterForm,
RackElevationFilterForm,
IndividualOptionsForm, IndividualOptionsForm,
CoordinateGroupsForm, CoordinateGroupsForm,
CircuitCoordinatesForm, CircuitCoordinatesForm,
@@ -113,20 +111,20 @@ def create_node(
if device.provider is not None: if device.provider is not None:
node_content += ( node_content += (
f"<tr><th>{_('Provider')}: </th><td>{device.provider.name}</td></tr>" f"<tr><th>Provider: </th><td>{device.provider.name}</td></tr>"
) )
if device.type is not None: if device.type is not None:
node_content += f"<tr><th>{_('Type')}: </th><td>{device.type.name}</td></tr>" node_content += f"<tr><th>Type: </th><td>{device.type.name}</td></tr>"
elif isinstance(device, PowerPanel): elif isinstance(device, PowerPanel):
dev_name = device.name dev_name = device.name
node["id"] = f"p{device.pk}" node["id"] = f"p{device.pk}"
model_name = 'PowerPanelCoordinate' model_name = 'PowerPanelCoordinate'
if device.site is not None: if device.site is not None:
node_content += f"<tr><th>{_('Site')}: </th><td>{device.site.name}</td></tr>" node_content += f"<tr><th>Site: </th><td>{device.site.name}</td></tr>"
if device.location is not None: if device.location is not None:
node_content += ( node_content += (
f"<tr><th>{_('Location')}: </th><td>{device.location.name}</td></tr>" f"<tr><th>Location: </th><td>{device.location.name}</td></tr>"
) )
elif isinstance(device, PowerFeed): elif isinstance(device, PowerFeed):
dev_name = device.name dev_name = device.name
@@ -135,18 +133,18 @@ def create_node(
if device.power_panel is not None: if device.power_panel is not None:
node_content += ( node_content += (
f"<tr><th>{_('Power Panel')}: </th><td>{device.power_panel.name}</td></tr>" f"<tr><th>Power Panel: </th><td>{device.power_panel.name}</td></tr>"
) )
if device.type is not None: if device.type is not None:
node_content += f"<tr><th>{_('Type')}: </th><td>{device.type}</td></tr>" node_content += f"<tr><th>Type: </th><td>{device.type}</td></tr>"
if device.supply is not None: if device.supply is not None:
node_content += f"<tr><th>{_('Supply')}: </th><td>{device.supply}</td></tr>" node_content += f"<tr><th>Supply: </th><td>{device.supply}</td></tr>"
if device.phase is not None: if device.phase is not None:
node_content += f"<tr><th>{_('Phase')}: </th><td>{device.phase}</td></tr>" node_content += f"<tr><th>Phase: </th><td>{device.phase}</td></tr>"
if device.amperage is not None: if device.amperage is not None:
node_content += f"<tr><th>{_('Amperage')}: </th><td>{device.amperage}</td></tr>" node_content += f"<tr><th>Amperage: </th><td>{device.amperage}</td></tr>"
if device.voltage is not None: if device.voltage is not None:
node_content += f"<tr><th>{_('Voltage')}: </th><td>{device.voltage}</td></tr>" node_content += f"<tr><th>Voltage: </th><td>{device.voltage}</td></tr>"
else: else:
model_name = 'Coordinate' model_name = 'Coordinate'
dev_name = device.name dev_name = device.name
@@ -155,32 +153,32 @@ def create_node(
if device.device_type is not None: if device.device_type is not None:
node_content += ( node_content += (
f"<tr><th>{_('Type')}: </th><td>{device.device_type.model}</td></tr>" f"<tr><th>Type: </th><td>{device.device_type.model}</td></tr>"
) )
if device.role.name is not None: if device.role.name is not None:
node_content += ( node_content += (
f"<tr><th>{_('Role')}: </th><td>{device.role.name}</td></tr>" f"<tr><th>Role: </th><td>{device.role.name}</td></tr>"
) )
if device.serial != "": if device.serial != "":
node_content += f"<tr><th>{_('Serial')}: </th><td>{device.serial}</td></tr>" node_content += f"<tr><th>Serial: </th><td>{device.serial}</td></tr>"
if device.primary_ip is not None: if device.primary_ip is not None:
node_content += ( node_content += (
f"<tr><th>{_('IP Address')}: </th><td>{device.primary_ip.address}</td></tr>" f"<tr><th>IP Address: </th><td>{device.primary_ip.address}</td></tr>"
) )
if device.site is not None: if device.site is not None:
node_content += f"<tr><th>{_('Site')}: </th><td>{device.site.name}</td></tr>" node_content += f"<tr><th>Site: </th><td>{device.site.name}</td></tr>"
if device.location is not None: if device.location is not None:
node_content += ( node_content += (
f"<tr><th>{_('Location')}: </th><td>{device.location.name}</td></tr>" f"<tr><th>Location: </th><td>{device.location.name}</td></tr>"
) )
if device.rack is not None: if device.rack is not None:
node_content += f"<tr><th>{_('Rack')}: </th><td>{device.rack.name}</td></tr>" node_content += f"<tr><th>Rack: </th><td>{device.rack.name}</td></tr>"
if device.position is not None: if device.position is not None:
if device.face is not None: if device.face is not None:
node_content += f"<tr><th>{_('Position')}: </th><td>{device.position} ({device.face})</td></tr>" node_content += f"<tr><th>Position: </th><td>{device.position} ({device.face})</td></tr>"
else: else:
node_content += ( node_content += (
f"<tr><th>{_('Position')}: </th><td>{device.position}</td></tr>" f"<tr><th>Position: </th><td>{device.position}</td></tr>"
) )
node["id"] = device.pk node["id"] = device.pk
@@ -238,25 +236,14 @@ def create_node(
# Create a list of possible label items. Omit None types # Create a list of possible label items. Omit None types
label_mapping = { label_mapping = {
NodeLabelItems.DEVICE_NAME: dev_name, NodeLabelItems.DEVICE_NAME: dev_name,
NodeLabelItems.DEVICE_TYPE: getattr(device, 'device_type', None),
NodeLabelItems.ROLE: getattr(device, 'role', None),
NodeLabelItems.DESCRIPTION: getattr(device, 'description', None),
NodeLabelItems.PRIMARY_IPV4: getattr(device, 'primary_ip4', None), NodeLabelItems.PRIMARY_IPV4: getattr(device, 'primary_ip4', None),
NodeLabelItems.PRIMARY_IPV6: getattr(device, 'primary_ip6', None), NodeLabelItems.PRIMARY_IPV6: getattr(device, 'primary_ip6', None),
NodeLabelItems.OUT_OF_BAND_IP: getattr(device, 'oob_ip', None), NodeLabelItems.OUT_OF_BAND_IP: getattr(device, 'oob_ip', None),
NodeLabelItems.PLATFORM: getattr(device, 'platform', None),
NodeLabelItems.SERIAL: getattr(device, 'serial', None),
NodeLabelItems.TENANT: getattr(device, 'tenant', None),
NodeLabelItems.SITE: getattr(device, 'site', None),
NodeLabelItems.LOCATION: getattr(device, 'location', None),
NodeLabelItems.RACK: getattr(device, 'rack', None),
NodeLabelItems.VIRTUAL_CHASSIS: getattr(device, 'virtual_chassis', None),
NodeLabelItems.ASSET_TAG: getattr(device, 'asset_tag', None),
} }
label_items = [] label_items = []
for item in node_label_items: for item in node_label_items:
if label_mapping[item] and label_mapping[item] is not None: if label_mapping[item] is not None:
label_items.append(str(label_mapping[item])) label_items.append(str(label_mapping[item]))
node_label = '\n'.join(label_items) node_label = '\n'.join(label_items)
@@ -274,8 +261,6 @@ def create_edge(
termination_a: Dict, termination_a: Dict,
termination_b: Dict, termination_b: Dict,
straight_cables: bool, straight_cables: bool,
draw_termination_labels: bool,
draw_cable_labels: bool,
circuit: Optional[Dict] = None, circuit: Optional[Dict] = None,
cable: Optional[Cable] = None, cable: Optional[Cable] = None,
wireless: Optional[Dict] = None, wireless: Optional[Dict] = None,
@@ -283,22 +268,22 @@ def create_edge(
interface: Optional[Interface] = None, interface: Optional[Interface] = None,
): ):
cable_a_name = ( cable_a_name = (
_("termination A name unknown") "device A name unknown"
if termination_a["termination_name"] is None if termination_a["termination_name"] is None
else termination_a["termination_name"] else termination_a["termination_name"]
) )
cable_a_dev_name = ( cable_a_dev_name = (
_("device A name unknown") "device A name unknown"
if termination_a["termination_device_name"] is None if termination_a["termination_device_name"] is None
else termination_a["termination_device_name"] else termination_a["termination_device_name"]
) )
cable_b_name = ( cable_b_name = (
_("termination B name unknown") "device A name unknown"
if termination_b["termination_name"] is None if termination_b["termination_name"] is None
else termination_b["termination_name"] else termination_b["termination_name"]
) )
cable_b_dev_name = ( cable_b_dev_name = (
_("device B name unknown") "cable B name unknown"
if termination_b["termination_device_name"] is None if termination_b["termination_device_name"] is None
else termination_b["termination_device_name"] else termination_b["termination_device_name"]
) )
@@ -308,43 +293,30 @@ def create_edge(
edge["from"] = termination_a["device_id"] edge["from"] = termination_a["device_id"]
edge["to"] = termination_b["device_id"] edge["to"] = termination_b["device_id"]
edge["color"] = '#2b7ce9' edge["color"] = '#2b7ce9'
title = _("Cable") title = "Cable"
if circuit is not None: if circuit is not None:
edge["dashes"] = True edge["dashes"] = True
title = _("Circuit provider: %(provider)s<br>Termination") % {"provider": circuit['provider_name']} title = f"Circuit provider: {circuit['provider_name']}<br>Termination"
elif wireless is not None: elif wireless is not None:
edge["dashes"] = LinePattern().wireless edge["dashes"] = LinePattern().wireless
title = _("Wireless Connection") title = "Wireless Connection"
elif power is not None: elif power is not None:
edge["dashes"] = LinePattern().power edge["dashes"] = LinePattern().power
title = _("Power Connection") title = "Power Connection"
elif interface is not None: elif interface is not None:
title = _("Interface Connection") title = "Interface Connection"
edge["width"] = 3 edge["width"] = 3
edge["dashes"] = LinePattern().logical edge["dashes"] = LinePattern().logical
edge["color"] = '#f1c232' edge["color"] = '#f1c232'
edge["href"] = interface.get_absolute_url() + "trace" edge["href"] = interface.get_absolute_url() + "trace"
if cable is not None and hasattr(cable, "label") and cable.label:
cable_label = "<br>" + _("Label: %(label)s") % {"label": cable.label}
if draw_cable_labels is True:
edge["label"] = cable.label
else:
cable_label = ""
edge[ edge[
"title" "title"
] = _("%(title)s between<br>%(device_a)s [%(termination_a)s]<br>%(device_b)s [%(termination_b)s]") % { ] = f"{title} between<br>{cable_a_dev_name} [{cable_a_name}]<br>{cable_b_dev_name} [{cable_b_name}]"
"title": title,
"device_a": cable_a_dev_name,
"termination_a": cable_a_name,
"device_b": cable_b_dev_name,
"termination_b": cable_b_name,
} + f" {cable_label}"
if cable is not None: if cable is not None:
edge["href"] = cable.get_absolute_url() edge["href"] = cable.get_absolute_url()
@@ -354,12 +326,6 @@ def create_edge(
# if straight_cables == True: edge["smooth"] = False # if straight_cables == True: edge["smooth"] = False
edge["smooth"] = not straight_cables edge["smooth"] = not straight_cables
if draw_termination_labels is True:
edge["drawTerminationLabel"] = True
edge["cable_a_name"] = cable_a_name
edge["cable_b_name"] = cable_b_name
return edge return edge
@@ -402,8 +368,6 @@ def get_topology_data(
group_virtualchassis: bool, group_virtualchassis: bool,
group_id, group_id,
straight_cables: bool, straight_cables: bool,
draw_termination_labels: bool,
draw_cable_labels: bool,
grid_size: list, grid_size: list,
node_label_items: list, node_label_items: list,
): ):
@@ -473,7 +437,7 @@ def get_topology_data(
termination_a = {} termination_a = {}
termination_b = {} termination_b = {}
circuit_model = {} circuit_model = {}
if circuit_termination.cable is not None and bool(circuit_termination.cable.a_terminations) and bool(circuit_termination.cable.b_terminations): if circuit_termination.cable is not None:
termination_a = create_circuit_termination( termination_a = create_circuit_termination(
circuit_termination.cable.a_terminations[0] circuit_termination.cable.a_terminations[0]
) )
@@ -502,8 +466,6 @@ def get_topology_data(
termination_a=termination_a, termination_a=termination_a,
termination_b=termination_b, termination_b=termination_b,
straight_cables=straight_cables, straight_cables=straight_cables,
draw_termination_labels=draw_termination_labels,
draw_cable_labels=draw_cable_labels,
) )
) )
@@ -574,8 +536,6 @@ def get_topology_data(
termination_b=termination_b, termination_b=termination_b,
power=True, power=True,
straight_cables=straight_cables, straight_cables=straight_cables,
draw_termination_labels=draw_termination_labels,
draw_cable_labels=draw_cable_labels,
) )
) )
@@ -614,7 +574,7 @@ def get_topology_data(
edge_ids += 1 edge_ids += 1
termination_a = { "termination_name": interface.name, "termination_device_name": interface.device.name, "device_id": interface.device.id } termination_a = { "termination_name": interface.name, "termination_device_name": interface.device.name, "device_id": interface.device.id }
termination_b = { "termination_name": destination.name, "termination_device_name": destination.device.name, "device_id": destination.device.id } termination_b = { "termination_name": destination.name, "termination_device_name": destination.device.name, "device_id": destination.device.id }
edges.append(create_edge(edge_id=edge_ids, termination_a=termination_a, termination_b=termination_b, interface=interface, straight_cables=straight_cables, draw_termination_labels=draw_termination_labels, draw_cable_labels=draw_cable_labels)) edges.append(create_edge(edge_id=edge_ids, termination_a=termination_a, termination_b=termination_b, interface=interface, straight_cables=straight_cables))
nodes_devices[interface.device.id] = interface.device nodes_devices[interface.device.id] = interface.device
nodes_devices[destination.device.id] = destination.device nodes_devices[destination.device.id] = destination.device
@@ -695,8 +655,6 @@ def get_topology_data(
termination_a=termination_a, termination_a=termination_a,
termination_b=termination_b, termination_b=termination_b,
straight_cables=straight_cables, straight_cables=straight_cables,
draw_termination_labels=draw_termination_labels,
draw_cable_labels=draw_cable_labels,
) )
) )
@@ -737,8 +695,6 @@ def get_topology_data(
termination_b=termination_b, termination_b=termination_b,
wireless=wireless, wireless=wireless,
straight_cables=straight_cables, straight_cables=straight_cables,
draw_termination_labels=draw_termination_labels,
draw_cable_labels=draw_cable_labels,
) )
) )
@@ -793,10 +749,7 @@ class TopologyHomeView(PermissionRequiredMixin, View):
if request.GET: if request.GET:
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) 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, grid_size, node_label_items = get_query_settings(request)
filter_required = True
empty_result = False
# Read options from saved filters as NetBox does not handle custom plugin filters # Read options from saved filters as NetBox does not handle custom plugin filters
if "filter_id" in request.GET and request.GET["filter_id"] != '': if "filter_id" in request.GET and request.GET["filter_id"] != '':
@@ -819,8 +772,6 @@ class TopologyHomeView(PermissionRequiredMixin, View):
if group_virtualchassis == False and 'group_virtualchassis' in saved_filter_params: group_virtualchassis = saved_filter_params['group_virtualchassis'] 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 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 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 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'] 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 except SavedFilter.DoesNotExist: # filter_id not found
@@ -837,8 +788,6 @@ class TopologyHomeView(PermissionRequiredMixin, View):
group_id = request.GET["group"] group_id = request.GET["group"]
if not "draw_init" in request.GET or "draw_init" in request.GET and request.GET["draw_init"].lower() == "true": if not "draw_init" in request.GET or "draw_init" in request.GET and request.GET["draw_init"].lower() == "true":
filter_required = False
topo_data = get_topology_data( topo_data = get_topology_data(
queryset=self.queryset, queryset=self.queryset,
individualOptions=individualOptions, individualOptions=individualOptions,
@@ -858,19 +807,14 @@ class TopologyHomeView(PermissionRequiredMixin, View):
group_virtualchassis=group_virtualchassis, group_virtualchassis=group_virtualchassis,
group_id=group_id, group_id=group_id,
straight_cables=straight_cables, straight_cables=straight_cables,
draw_termination_labels=draw_termination_labels,
draw_cable_labels=draw_cable_labels,
grid_size=grid_size, grid_size=grid_size,
node_label_items=node_label_items, node_label_items=node_label_items,
) )
if topo_data is None or not topo_data["nodes"]:
empty_result = True
else: else:
# No GET-Request in URL. We most likely came here from the navigation menu. # No GET-Request in URL. We most likely came here from the navigation menu.
preselected_device_roles = IndividualOptions.objects.get(id=individualOptions.id).preselected_device_roles.all().values_list('id', flat=True) preselected_device_roles = IndividualOptions.objects.get(id=individualOptions.id).preselected_device_roles.all().values_list('id', flat=True)
preselected_tags = IndividualOptions.objects.get(id=individualOptions.id).preselected_tags.all().values_list('slug', flat=True) preselected_tags = IndividualOptions.objects.get(id=individualOptions.id).preselected_tags.all().values_list(Lower('name'), flat=True)
ignore_cable_type = IndividualOptions.objects.get(id=individualOptions.id).ignore_cable_type.translate({ord(i): None for i in '[]\''}).split(', ') ignore_cable_type = IndividualOptions.objects.get(id=individualOptions.id).ignore_cable_type.translate({ord(i): None for i in '[]\''}).split(', ')
if ignore_cable_type == ['']: ignore_cable_type = [] if ignore_cable_type == ['']: ignore_cable_type = []
@@ -893,8 +837,6 @@ class TopologyHomeView(PermissionRequiredMixin, View):
if individualOptions.group_racks: q['group_racks'] = "True" if individualOptions.group_racks: q['group_racks'] = "True"
if individualOptions.group_virtualchassis: q['group_virtualchassis'] = "True" if individualOptions.group_virtualchassis: q['group_virtualchassis'] = "True"
if individualOptions.straight_cables: q['straight_cables'] = "True" if individualOptions.straight_cables: q['straight_cables'] = "True"
if individualOptions.draw_termination_labels: q['draw_termination_labels'] = "True"
if individualOptions.draw_cable_labels: q['draw_cable_labels'] = "True"
if individualOptions.grid_size: q['grid_size'] = individualOptions.grid_size if individualOptions.grid_size: q['grid_size'] = individualOptions.grid_size
node_label_items = IndividualOptions.objects.get(id=individualOptions.id).node_label_items.translate({ord(i): None for i in '[]\''}).split(', ') node_label_items = IndividualOptions.objects.get(id=individualOptions.id).node_label_items.translate({ord(i): None for i in '[]\''}).split(', ')
if node_label_items == ['']: node_label_items = [] if node_label_items == ['']: node_label_items = []
@@ -908,6 +850,20 @@ class TopologyHomeView(PermissionRequiredMixin, View):
query_string = q.urlencode() query_string = q.urlencode()
return HttpResponseRedirect(f"{request.path}?{query_string}") return HttpResponseRedirect(f"{request.path}?{query_string}")
if htmx_partial(request):
return render(
request,
"netbox_topology_views/htmx_topology.html",
{
"filter_form": DeviceFilterForm(request.GET, label_suffix=""),
"topology_data": json.dumps(topo_data),
"broken_image": find_image_url("role-unknown"),
"epoch": int(time.time()),
"basepath": settings.BASE_PATH,
},
)
return render( return render(
request, request,
"netbox_topology_views/index.html", "netbox_topology_views/index.html",
@@ -917,215 +873,10 @@ class TopologyHomeView(PermissionRequiredMixin, View):
"broken_image": find_image_url("role-unknown"), "broken_image": find_image_url("role-unknown"),
"model": self.model, "model": self.model,
"basepath": settings.BASE_PATH, "basepath": settings.BASE_PATH,
"filter_required": filter_required,
"empty_result": empty_result,
}, },
) )
def _rack_endpoint(termination):
"""Return a template-friendly representation of any cable termination."""
device = getattr(termination, "device", None)
return {
"node_id": f"device-{device.pk}" if device else f"external-{termination._meta.model_name}-{termination.pk}",
"device_id": getattr(device, "pk", None),
"device_name": getattr(device, "name", None) or _("External"),
"name": getattr(termination, "name", str(termination)),
"rack_id": getattr(device, "rack_id", None),
"rack_name": getattr(getattr(device, "rack", None), "name", None) or _("External"),
"url": device.get_absolute_url() if device else None,
"color": getattr(getattr(device, "role", None), "color", None) or "1685fc",
"position": float(device.position or 1) if device else None,
"height": float(max(getattr(getattr(device, "device_type", None), "u_height", 1) or 1, 1)) if device else 1,
"face": str(device.face or "front").lower() if device else "front",
"rack_u_height": getattr(getattr(device, "rack", None), "u_height", None),
"rack_desc_units": getattr(getattr(device, "rack", None), "desc_units", False),
"rack_starting_unit": getattr(getattr(device, "rack", None), "starting_unit", 1),
"subtitle": str(device.device_type) if device else getattr(termination, "name", str(termination)),
}
class RackElevationView(PermissionRequiredMixin, View):
"""Render one or more complete rack elevations and their physical cabling."""
permission_required = ("dcim.view_rack", "dcim.view_device", "dcim.view_cable")
def get(self, request):
racks = Rack.objects.restrict(request.user, "view").select_related("site", "location")
if not request.GET:
racks = racks.none()
selected_racks = request.GET.getlist("rack_id")
if selected_racks:
racks = racks.filter(pk__in=selected_racks)
else:
if request.GET.getlist("site_id"):
racks = racks.filter(site_id__in=request.GET.getlist("site_id"))
if request.GET.getlist("location_id"):
racks = racks.filter(location_id__in=request.GET.getlist("location_id"))
devices = Device.objects.restrict(request.user, "view").filter(
rack_id__in=racks.values("pk")
).select_related("device_type", "role", "rack")
if request.GET.get("include_empty") not in ("on", "True", "true", "1"):
racks = racks.filter(devices__in=devices).distinct()
rack_list = list(racks.order_by("site__name", "location__name", "name"))
rack_ids = {rack.pk for rack in rack_list}
rack_devices = {rack_id: [] for rack_id in rack_ids}
device_ids = []
for device in devices.filter(rack_id__in=rack_ids).order_by("rack_id", "position", "name"):
device_ids.append(device.pk)
height = float(max(getattr(device.device_type, "u_height", 1) or 1, 1))
rack_height = max(device.rack.u_height or 1, 1)
rack_start = float(device.rack.starting_unit or 1)
position_offset = float(device.position or rack_start) - rack_start
if device.rack.desc_units:
bottom_units = rack_height - position_offset - height
else:
bottom_units = position_offset
device.elevation_bottom = f"{max(bottom_units, 0) / rack_height * 100:.4f}"
device.elevation_height = f"{min(height / rack_height * 100, 100):.4f}"
device.elevation_face = str(device.face or "front").lower()
rack_devices[device.rack_id].append(device)
for rack in rack_list:
rack.elevation_devices = rack_devices[rack.pk]
rack_start = rack.starting_unit or 1
if rack.desc_units:
rack.elevation_unit_labels = range(rack_start, rack_start + (rack.u_height or 0))
else:
rack.elevation_unit_labels = range(
rack_start + (rack.u_height or 0) - 1,
rack_start - 1,
-1,
)
rack_export = []
for rack in rack_list:
rack_export.append({
"id": rack.pk, "name": rack.name, "u_height": rack.u_height,
"starting_unit": rack.starting_unit, "desc_units": rack.desc_units,
"site": str(rack.site), "location": str(rack.location or ""),
"devices": [{
"name": device.name or str(device.device_type),
"type": str(device.device_type),
"position": float(device.position or 1),
"height": float(max(device.device_type.u_height or 1, 1)),
"face": device.elevation_face,
"color": f"#{device.role.color}" if device.role.color else "#1685fc",
} for device in rack.elevation_devices],
})
power_component_models = {"powerport", "poweroutlet", "powerfeed"}
cable_rows = []
topology_nodes = {}
topology_edges = []
if device_ids:
cable_ids = CableTermination.objects.filter(
_device_id__in=device_ids
).values_list("cable_id", flat=True).distinct()
cables = Cable.objects.restrict(request.user, "view").filter(pk__in=cable_ids)
for cable in cables.order_by("label", "pk"):
a_terms, b_terms = list(cable.a_terminations), list(cable.b_terminations)
is_power_cable = cable.type == CableTypeChoices.TYPE_POWER or any(
term._meta.model_name in power_component_models for term in a_terms + b_terms
)
for index in range(max(len(a_terms), len(b_terms), 1)):
a = _rack_endpoint(a_terms[index]) if index < len(a_terms) else None
b = _rack_endpoint(b_terms[index]) if index < len(b_terms) else None
if (a and a["rack_id"] in rack_ids) or (b and b["rack_id"] in rack_ids):
cable_rows.append({"cable": cable, "a": a, "b": b})
for endpoint in (a, b):
if endpoint:
topology_nodes[endpoint["node_id"]] = endpoint
if a and b:
default_color = "#f59e0b" if is_power_cable else "#1685fc"
topology_edges.append({
"from": a["node_id"], "to": b["node_id"],
"from_device": a["device_name"], "to_device": b["device_name"],
"from_port": a["name"], "to_port": b["name"],
"label": cable.label or str(cable),
"color": f"#{cable.color}" if cable.color else default_color,
"url": cable.get_absolute_url(),
"kind": "power" if is_power_cable else "cable",
})
wireless_device_ids = set(device_ids) | {
node["device_id"] for node in topology_nodes.values() if node.get("device_id")
}
wireless_links = WirelessLink.objects.restrict(request.user, "view").filter(
Q(interface_a__device_id__in=wireless_device_ids) |
Q(interface_b__device_id__in=wireless_device_ids)
).select_related(
"interface_a__device__rack", "interface_a__device__role", "interface_a__device__device_type",
"interface_b__device__rack", "interface_b__device__role", "interface_b__device__device_type",
)
for wireless_link in wireless_links:
a = _rack_endpoint(wireless_link.interface_a)
b = _rack_endpoint(wireless_link.interface_b)
topology_nodes[a["node_id"]] = a
topology_nodes[b["node_id"]] = b
topology_edges.append({
"from": a["node_id"], "to": b["node_id"],
"from_device": a["device_name"], "to_device": b["device_name"],
"from_port": a["name"], "to_port": b["name"],
"label": wireless_link.ssid or str(wireless_link),
"color": "#8b5cf6", "url": wireless_link.get_absolute_url(),
"kind": "wireless",
})
wireless_lans = WirelessLAN.objects.restrict(request.user, "view").filter(
interfaces__device_id__in=device_ids
).distinct()
for wireless_lan in wireless_lans:
wlan_node_id = f"wlan-{wireless_lan.pk}"
topology_nodes[wlan_node_id] = {
"node_id": wlan_node_id, "device_id": None,
"device_name": f"WLAN · {wireless_lan.ssid}",
"name": wireless_lan.ssid, "subtitle": _("Multi-Access WLAN"),
"rack_id": None, "rack_name": _("Wireless networks"),
"url": wireless_lan.get_absolute_url(), "color": "8b5cf6",
"position": None, "height": 1, "face": "front", "rack_u_height": None,
"kind": "wireless-lan",
}
wlan_interfaces = Interface.objects.restrict(request.user, "view").filter(
wireless_lans=wireless_lan
).select_related("device__rack", "device__role", "device__device_type")
for interface in wlan_interfaces:
endpoint = _rack_endpoint(interface)
topology_nodes[endpoint["node_id"]] = endpoint
topology_edges.append({
"from": endpoint["node_id"], "to": wlan_node_id,
"from_device": endpoint["device_name"],
"to_device": f"WLAN · {wireless_lan.ssid}",
"from_port": endpoint["name"], "to_port": wireless_lan.ssid,
"label": wireless_lan.ssid, "color": "#8b5cf6",
"url": wireless_lan.get_absolute_url(), "kind": "wireless-lan",
})
return render(request, "netbox_topology_views/rack_elevation.html", {
"filter_form": RackElevationFilterForm(request.GET or None),
"racks": rack_list, "cables": cable_rows,
"rack_topology": {"nodes": list(topology_nodes.values()), "edges": topology_edges},
"rack_export": rack_export,
"faces": (("front", _("Front")), ("rear", _("Rear"))),
"has_selection": bool(request.GET),
# Labels for the inline script, which cannot use template tags
"i18n": {
"external": _("External"),
"power": _("Power"),
"connections": _("Connections"),
"noConnections": _("No connections"),
"fullScreen": _("Full screen"),
"exitFullScreen": _("Exit full screen"),
"device": _("Device"),
"front": _("Front"),
"rear": _("Rear"),
},
})
CONFIG = settings.PLUGINS_CONFIG["netbox_topology_views"] CONFIG = settings.PLUGINS_CONFIG["netbox_topology_views"]
ADDITIONAL_ROLES = (PowerPanel, PowerFeed, Circuit) ADDITIONAL_ROLES = (PowerPanel, PowerFeed, Circuit)
@@ -1419,7 +1170,7 @@ class TopologyIndividualOptionsView(PermissionRequiredMixin, View):
form = IndividualOptionsForm(request.POST, instance=instance) form = IndividualOptionsForm(request.POST, instance=instance)
if form.is_valid(): if form.is_valid():
form.save() form.save()
messages.success(request, _("Options have been successfully saved")) messages.success(request, "Options have been sucessfully saved")
else: else:
messages.error(request, form.errors) messages.error(request, form.errors)
@@ -1451,8 +1202,6 @@ class TopologyIndividualOptionsView(PermissionRequiredMixin, View):
'group_virtualchassis': queryset.group_virtualchassis, 'group_virtualchassis': queryset.group_virtualchassis,
'draw_default_layout': queryset.draw_default_layout, 'draw_default_layout': queryset.draw_default_layout,
'straight_cables': queryset.straight_cables, 'straight_cables': queryset.straight_cables,
'draw_termination_labels': queryset.draw_termination_labels,
'draw_cable_labels': queryset.draw_cable_labels,
'grid_size': queryset.grid_size, 'grid_size': queryset.grid_size,
'node_label_items': tuple(queryset.node_label_items.translate({ord(i): None for i in '[]\''}).split(', ')), 'node_label_items': tuple(queryset.node_label_items.translate({ord(i): None for i in '[]\''}).split(', ')),
}, },
+2 -2
View File
@@ -7,8 +7,8 @@ long_description = readme.read_text()
setup( setup(
name="netbox-topology-views", name="netbox-topology-views",
version="4.5.2", version="4.3.0",
description="A NetBox plugin to create Topology maps", description="An NetBox plugin to create Topology maps",
long_description=long_description, long_description=long_description,
long_description_content_type="text/markdown", long_description_content_type="text/markdown",
url="https://github.com/mattieserver/netbox-topology-views", url="https://github.com/mattieserver/netbox-topology-views",
-37
View File
@@ -1,37 +0,0 @@
"""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()