commit c4dc5d53ce5b793516bf92e0802f616b4285b6dc Author: Louis Date: Wed Nov 4 12:18:13 2026 +0100 Initial NetBox Floor Planner plugin Drag & drop SVG floor plan designer for NetBox 4.7.2+ with rack/device placement, smart snapping, undo/redo, view mode with status colouring, SVG/PNG export, REST layout API and English/German translations. Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8e75778 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +__pycache__/ +*.py[cod] +*.egg-info/ +build/ +dist/ +.venv/ diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..33d0ec8 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,4 @@ +include README.md +recursive-include netbox_floorplanner/templates * +recursive-include netbox_floorplanner/static * +recursive-include netbox_floorplanner/locale * diff --git a/README.md b/README.md new file mode 100644 index 0000000..48c97ee --- /dev/null +++ b/README.md @@ -0,0 +1,163 @@ +# NetBox Floor Planner + +`netbox_floorplanner` is a NetBox plugin that adds a modern, drag & drop floor plan designer for sites and locations: place racks, devices, walls, doors, windows, areas and infrastructure on a to-scale plan, then use it as an interactive map that links straight back into NetBox. + +It is a from-scratch alternative to the community `netbox-floorplan-plugin`, with a canvas-style editor in the spirit of draw.io instead of a form-based workflow. + +| | | +|---|---| +| **Package** | `netbox-floorplanner` | +| **Plugin name** | `netbox_floorplanner` | +| **NetBox** | 4.7.2 or newer | +| **Python** | 3.12 or newer | +| **Languages** | English, German (follows the NetBox user language) | + +## Requirements + +- NetBox **4.7.2 or newer**. Older versions are rejected at startup (`min_version = 4.7.2`). +- Python 3.12 or newer. +- No additional Python dependencies and no JavaScript build step. The designer is plain JavaScript and SVG and uses the Material Design Icons that ship with NetBox. + +## Installation and updates + +1. Install the package into the NetBox virtual environment. Pin a release tag or commit for production: + + ```bash + source /opt/netbox/venv/bin/activate + pip install "git+https:////netbox-floorplanner.git@v0.1.0" + ``` + +2. Add the same source to `local_requirements.txt`, so NetBox upgrades (`upgrade.sh`) reinstall the plugin automatically: + + ```text + git+https:////netbox-floorplanner.git@v0.1.0 + ``` + + For private repositories use a deploy token or SSH key and keep the credentials out of this file. + +3. Enable the plugin in `configuration.py`: + + ```python + PLUGINS = [ + 'netbox_floorplanner', + ] + + PLUGINS_CONFIG = { + 'netbox_floorplanner': { + # optional, see "Configuration" + }, + } + ``` + +4. Run the migrations, collect the static files and restart NetBox: + + ```bash + cd /opt/netbox/netbox + python manage.py migrate netbox_floorplanner + python manage.py collectstatic --no-input + sudo systemctl restart netbox netbox-rq + ``` + +Before updating, back up the database and try the update on a staging instance first. After every update, run `migrate` and `collectstatic` again. The static files are versioned, so browsers pick up the new designer automatically. + +## Main features + +- **Drag & drop designer:** drag shapes, racks and devices from the palette onto the plan, or click an entry to drop it in the middle of the view. +- **To-scale plans:** 1 unit = 1 cm. Racks are sized from their `outer_width` and `outer_depth` (mm or inch), with a configurable fallback. +- **Editing:** move, resize with 8 handles, free rotation with 15° snapping, multi-selection (Shift+click or rubber band), z-order, copy/paste/duplicate, arrow-key nudging and 100 undo/redo steps. +- **Smart snapping:** snaps to the grid, plus magnetic alignment to the edges of neighbouring items and room walls, with visible guide lines. Hold **Alt** to place freely. +- **Shape library:** wall, door (with swing arc), window, area/zone, column, cooling unit, power/UPS and free text labels, each with an editable colour. +- **NetBox integration:** + - The palette lists the site's racks (filtered by location) and its non-racked devices, such as access points and cameras. Objects already placed are marked and can only be placed once. + - A **Floor Plans** tab on Site and Location pages, with a pre-filled "Add floor plan" button. + - A **Show on floor plan** button on Rack and Device pages that opens the plan, zooms to the object and highlights it. +- **Interactive view mode:** pan, zoom, tooltips (status, role, tenant, height, device count), click to open the rack or device (Ctrl+click opens a new tab), colouring by type, status or role, and a search box that highlights matches. +- **Background drawings:** upload a CAD or architectural image per plan, stretched to the room size with adjustable opacity. +- **Export:** SVG (vector) and high-resolution PNG, with the background embedded. +- **NetBox native:** change logging, journaling, tags, custom fields, global search, CSV/YAML import, bulk delete, object permissions, REST API, dark mode and fullscreen. + +### Keyboard shortcuts (designer) + +| Key | Action | +|---|---| +| Drag / Shift+click / drag on empty space | Move / multi-select / rubber-band select | +| Alt (while dragging) | Disable snapping | +| Space+drag, middle mouse | Pan | +| Mouse wheel, `+` / `-` / `0` | Zoom / fit to screen | +| `R` / Shift+`R` | Rotate 90° clockwise / counter-clockwise | +| Arrow keys (Shift = one grid step) | Nudge by 1 cm | +| Del / Backspace | Delete | +| Ctrl+Z, Ctrl+Y / Ctrl+Shift+Z | Undo, redo | +| Ctrl+C / Ctrl+V / Ctrl+D / Ctrl+A | Copy / paste / duplicate / select all | +| Ctrl+S | Save | +| Esc | Clear selection | + +## Configuration + +All settings are optional and go under `PLUGINS_CONFIG['netbox_floorplanner']`. + +| Setting | Default | Description | +|---|---|---| +| `default_width` | `2000` | Initial width (cm) for new floor plans | +| `default_depth` | `1500` | Initial depth (cm) for new floor plans | +| `default_grid_size` | `50` | Initial grid size (cm) for new floor plans | +| `default_rack_width` | `60` | Rack footprint width (cm) when the rack has no `outer_width` | +| `default_rack_depth` | `120` | Rack footprint depth (cm) when the rack has no `outer_depth` | + +## REST API + +| Endpoint | Methods | Description | +|---|---|---| +| `/api/plugins/floorplanner/floorplans/` | GET, POST, PUT, PATCH, DELETE | Standard NetBox CRUD for floor plans | +| `/api/plugins/floorplanner/floorplans//layout/` | GET, PUT | Read or atomically replace the complete layout | + +Example layout payload: + +```json +{ + "settings": { "width": 2000, "depth": 1500, "grid_size": 50 }, + "items": [ + { "item_type": "rack", "x": 300, "y": 200, "width": 60, "height": 120, "rotation": 0, "rack": 12 }, + { "item_type": "wall", "x": 0, "y": 600, "width": 800, "height": 15, "rotation": 0 }, + { "item_type": "label", "label": "Cold aisle A", "x": 300, "y": 330, "width": 200, "height": 40 } + ] +} +``` + +`item_type` is one of `rack`, `device`, `wall`, `door`, `window`, `area`, `column`, `cooling`, `power` or `label`. `x` and `y` are the top-left corner of the unrotated shape in cm, and `rotation` is applied around its centre. + +## Important semantics + +- **Coordinates are centimetres.** The `height` field of an item is its depth on the floor (the Y extent), not its height in rack units. +- **The layout is saved as a whole.** Saving replaces all items of the plan in one transaction and writes a single change-log entry on the floor plan. Item IDs are not stable across saves, so reference racks and devices instead. +- **Racks and devices can be placed at most once per plan,** and must belong to the plan's site. Pasted copies of linked items become unlinked shapes. +- **Deleting a rack or device removes its item** from every floor plan. Deleting a site or location deletes its floor plans. +- **Permissions:** viewing a plan requires `view_floorplan`, and the designer and the layout `PUT` require `change_floorplan`. The rack and device lists in the palette follow the user's normal NetBox permissions. +- **The designer is a client-side editor.** Unsaved changes live only in the browser tab. The page warns before you navigate away from unsaved changes. + +## Translations + +The UI is in English and German and follows the language selected in the NetBox user preferences. The German catalogue is in `netbox_floorplanner/locale/de/LC_MESSAGES/`. After changing `django.po`, recompile it: + +```bash +cd netbox_floorplanner && django-admin compilemessages -l de +``` + +## Uninstall + +1. Optional: export the plans you want to keep (SVG/PNG or `GET …/layout/`). +2. Drop the plugin tables: + + ```bash + python manage.py migrate netbox_floorplanner zero + ``` + +3. Remove `netbox_floorplanner` from `PLUGINS` and `PLUGINS_CONFIG`, and its line from `local_requirements.txt`. +4. Uninstall the package and restart NetBox: + + ```bash + pip uninstall netbox-floorplanner + sudo systemctl restart netbox netbox-rq + ``` + +Uploaded background images stay in `MEDIA_ROOT/floorplanner/` and can be deleted manually. diff --git a/netbox_floorplanner/__init__.py b/netbox_floorplanner/__init__.py new file mode 100644 index 0000000..0bf544c --- /dev/null +++ b/netbox_floorplanner/__init__.py @@ -0,0 +1,26 @@ +from django.utils.translation import gettext_lazy as _ +from netbox.plugins import PluginConfig + +__version__ = '0.1.0' + + +class FloorPlannerConfig(PluginConfig): + name = 'netbox_floorplanner' + verbose_name = _('Floor Planner') + description = _('Drag & drop floor plan designer for sites and locations') + version = __version__ + author = 'Louis' + base_url = 'floorplanner' + min_version = '4.7.2' + default_settings = { + # Default dimensions (cm) for new floor plans + 'default_width': 2000, + 'default_depth': 1500, + 'default_grid_size': 50, + # Rack footprint (cm) used when a rack has no outer dimensions + 'default_rack_width': 60, + 'default_rack_depth': 120, + } + + +config = FloorPlannerConfig diff --git a/netbox_floorplanner/api/__init__.py b/netbox_floorplanner/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/netbox_floorplanner/api/serializers.py b/netbox_floorplanner/api/serializers.py new file mode 100644 index 0000000..2cc0926 --- /dev/null +++ b/netbox_floorplanner/api/serializers.py @@ -0,0 +1,109 @@ +from dcim.api.serializers import LocationSerializer, SiteSerializer +from dcim.choices import DeviceStatusChoices, RackStatusChoices +from dcim.models import Device, Rack +from django.utils.translation import gettext as _ +from netbox.api.serializers import NetBoxModelSerializer +from rest_framework import serializers + +from ..models import FloorPlan, FloorPlanItem + +__all__ = ('FloorPlanSerializer', 'FloorPlanItemSerializer', 'LayoutSerializer') + + +class FloorPlanSerializer(NetBoxModelSerializer): + url = serializers.HyperlinkedIdentityField(view_name='plugins-api:netbox_floorplanner-api:floorplan-detail') + site = SiteSerializer(nested=True) + location = LocationSerializer(nested=True, required=False, allow_null=True, default=None) + item_count = serializers.IntegerField(read_only=True, required=False) + + class Meta: + model = FloorPlan + fields = ( + 'id', 'url', 'display', 'name', 'site', 'location', 'width', 'depth', 'grid_size', + 'background_image', 'background_opacity', 'description', 'comments', 'item_count', + 'tags', 'custom_fields', 'created', 'last_updated', + ) + brief_fields = ('id', 'url', 'display', 'name', 'description') + + +def _object_info(obj, status_choices): + """Compact representation of a linked NetBox object for the designer.""" + role = getattr(obj, 'role', None) + tenant = getattr(obj, 'tenant', None) + info = { + 'id': obj.pk, + 'name': obj.name or str(obj), + 'url': obj.get_absolute_url(), + 'status': obj.status, + 'status_label': str(dict(status_choices).get(obj.status, obj.status)), + 'status_color': status_choices.colors.get(obj.status, 'gray'), + 'role': role.name if role else None, + 'role_color': f'#{role.color}' if role and role.color else None, + 'tenant': tenant.name if tenant else None, + } + if isinstance(obj, Rack): + info['u_height'] = obj.u_height + info['device_count'] = getattr(obj, 'device_count', None) + return info + + +class FloorPlanItemSerializer(serializers.ModelSerializer): + rack = serializers.PrimaryKeyRelatedField(queryset=Rack.objects.all(), required=False, allow_null=True) + device = serializers.PrimaryKeyRelatedField(queryset=Device.objects.all(), required=False, allow_null=True) + object = serializers.SerializerMethodField(read_only=True) + + class Meta: + model = FloorPlanItem + fields = ( + 'id', 'item_type', 'label', 'x', 'y', 'width', 'height', 'rotation', 'color', 'z_index', + 'rack', 'device', 'properties', 'object', + ) + read_only_fields = ('id',) + + def get_object(self, item): + if item.rack_id: + return _object_info(item.rack, RackStatusChoices) + if item.device_id: + return _object_info(item.device, DeviceStatusChoices) + return None + + def validate_color(self, value): + if value and not (len(value) == 7 and value.startswith('#')): + raise serializers.ValidationError(_('Color must be a hex value like #3b82f6.')) + return value + + def validate(self, data): + floorplan = self.context.get('floorplan') + for field in ('rack', 'device'): + obj = data.get(field) + if obj is not None and floorplan is not None and obj.site_id != floorplan.site_id: + raise serializers.ValidationError({field: _('{obj} does not belong to site {site}.').format( + obj=obj, site=floorplan.site, + )}) + if data.get('rack') and data.get('device'): + raise serializers.ValidationError(_('An item can be linked to a rack or a device, not both.')) + return data + + +class LayoutSettingsSerializer(serializers.ModelSerializer): + class Meta: + model = FloorPlan + fields = ('width', 'depth', 'grid_size') + + +class LayoutSerializer(serializers.Serializer): + settings = LayoutSettingsSerializer(required=False) + items = FloorPlanItemSerializer(many=True) + + def validate_items(self, items): + seen = set() + for item in items: + for field in ('rack', 'device'): + obj = item.get(field) + if obj is None: + continue + key = (field, obj.pk) + if key in seen: + raise serializers.ValidationError(_('{obj} is placed more than once.').format(obj=obj)) + seen.add(key) + return items diff --git a/netbox_floorplanner/api/urls.py b/netbox_floorplanner/api/urls.py new file mode 100644 index 0000000..46d1383 --- /dev/null +++ b/netbox_floorplanner/api/urls.py @@ -0,0 +1,10 @@ +from netbox.api.routers import NetBoxRouter + +from . import views + +app_name = 'netbox_floorplanner-api' + +router = NetBoxRouter() +router.register('floorplans', views.FloorPlanViewSet) + +urlpatterns = router.urls diff --git a/netbox_floorplanner/api/views.py b/netbox_floorplanner/api/views.py new file mode 100644 index 0000000..1a34291 --- /dev/null +++ b/netbox_floorplanner/api/views.py @@ -0,0 +1,58 @@ +from django.db import transaction +from django.db.models import Count +from netbox.api.viewsets import NetBoxModelViewSet +from rest_framework.decorators import action +from rest_framework.response import Response + +from .. import filtersets +from ..models import FloorPlan, FloorPlanItem +from .serializers import FloorPlanItemSerializer, FloorPlanSerializer, LayoutSerializer + + +class FloorPlanViewSet(NetBoxModelViewSet): + queryset = FloorPlan.objects.select_related('site', 'location').prefetch_related('tags').annotate( + item_count=Count('items') + ) + serializer_class = FloorPlanSerializer + filterset_class = filtersets.FloorPlanFilterSet + + @action(detail=True, methods=['get', 'put'], url_path='layout') + def layout(self, request, pk=None): + """ + GET returns all items of the floor plan; PUT replaces the complete layout + atomically. The queryset is restricted by NetBox according to the HTTP + method, so PUT requires the change permission on the floor plan. + """ + floorplan = self.get_object() + + if request.method == 'PUT': + serializer = LayoutSerializer(data=request.data, context={'floorplan': floorplan, 'request': request}) + serializer.is_valid(raise_exception=True) + with transaction.atomic(): + floorplan.snapshot() + for attr, value in serializer.validated_data.get('settings', {}).items(): + setattr(floorplan, attr, value) + floorplan.items.all().delete() + FloorPlanItem.objects.bulk_create([ + FloorPlanItem(floorplan=floorplan, **item) + for item in serializer.validated_data['items'] + ]) + floorplan.full_clean() + floorplan.save() + + items = floorplan.items.select_related( + 'rack__role', 'rack__tenant', 'device__role', 'device__tenant', + ).annotate(device_count=Count('rack__devices')) + # device_count is annotated on the item; expose it on the rack for the serializer + for item in items: + if item.rack_id: + item.rack.device_count = item.device_count + + return Response({ + 'settings': { + 'width': floorplan.width, + 'depth': floorplan.depth, + 'grid_size': floorplan.grid_size, + }, + 'items': FloorPlanItemSerializer(items, many=True, context={'request': request}).data, + }) diff --git a/netbox_floorplanner/choices.py b/netbox_floorplanner/choices.py new file mode 100644 index 0000000..5d94fb8 --- /dev/null +++ b/netbox_floorplanner/choices.py @@ -0,0 +1,28 @@ +from django.utils.translation import gettext_lazy as _ +from utilities.choices import ChoiceSet + + +class ItemTypeChoices(ChoiceSet): + TYPE_RACK = 'rack' + TYPE_DEVICE = 'device' + TYPE_WALL = 'wall' + TYPE_DOOR = 'door' + TYPE_WINDOW = 'window' + TYPE_AREA = 'area' + TYPE_COLUMN = 'column' + TYPE_COOLING = 'cooling' + TYPE_POWER = 'power' + TYPE_LABEL = 'label' + + CHOICES = [ + (TYPE_RACK, _('Rack'), 'blue'), + (TYPE_DEVICE, _('Device'), 'purple'), + (TYPE_WALL, _('Wall'), 'gray'), + (TYPE_DOOR, _('Door'), 'orange'), + (TYPE_WINDOW, _('Window'), 'cyan'), + (TYPE_AREA, _('Area'), 'green'), + (TYPE_COLUMN, _('Column'), 'gray'), + (TYPE_COOLING, _('Cooling unit'), 'teal'), + (TYPE_POWER, _('Power / UPS'), 'yellow'), + (TYPE_LABEL, _('Label'), 'dark'), + ] diff --git a/netbox_floorplanner/filtersets.py b/netbox_floorplanner/filtersets.py new file mode 100644 index 0000000..fd40de0 --- /dev/null +++ b/netbox_floorplanner/filtersets.py @@ -0,0 +1,45 @@ +import django_filters +from dcim.models import Location, Site +from django.db.models import Q +from django.utils.translation import gettext_lazy as _ +from netbox.filtersets import NetBoxModelFilterSet + +from .models import FloorPlan + +__all__ = ('FloorPlanFilterSet',) + + +class FloorPlanFilterSet(NetBoxModelFilterSet): + site_id = django_filters.ModelMultipleChoiceFilter( + queryset=Site.objects.all(), + label=_('Site (ID)'), + ) + site = django_filters.ModelMultipleChoiceFilter( + field_name='site__slug', + queryset=Site.objects.all(), + to_field_name='slug', + label=_('Site (slug)'), + ) + location_id = django_filters.ModelMultipleChoiceFilter( + queryset=Location.objects.all(), + label=_('Location (ID)'), + ) + rack_id = django_filters.NumberFilter( + field_name='items__rack_id', + distinct=True, + label=_('Contains rack (ID)'), + ) + + class Meta: + model = FloorPlan + fields = ('id', 'name', 'description', 'width', 'depth', 'grid_size') + + def search(self, queryset, name, value): + if not value.strip(): + return queryset + return queryset.filter( + Q(name__icontains=value) + | Q(description__icontains=value) + | Q(site__name__icontains=value) + | Q(location__name__icontains=value) + ) diff --git a/netbox_floorplanner/forms.py b/netbox_floorplanner/forms.py new file mode 100644 index 0000000..ceae7a3 --- /dev/null +++ b/netbox_floorplanner/forms.py @@ -0,0 +1,74 @@ +from dcim.models import Location, Site +from django import forms +from django.utils.translation import gettext_lazy as _ +from netbox.forms import NetBoxModelFilterSetForm, NetBoxModelForm, NetBoxModelImportForm +from netbox.plugins import get_plugin_config +from utilities.forms.fields import ( + CSVModelChoiceField, CommentField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, TagFilterField, +) +from utilities.forms.rendering import FieldSet + +from .models import FloorPlan + +__all__ = ('FloorPlanForm', 'FloorPlanFilterForm', 'FloorPlanImportForm') + + +class FloorPlanForm(NetBoxModelForm): + site = DynamicModelChoiceField(label=_('Site'), queryset=Site.objects.all()) + location = DynamicModelChoiceField( + label=_('Location'), + queryset=Location.objects.all(), + required=False, + query_params={'site_id': '$site'}, + ) + comments = CommentField() + + fieldsets = ( + FieldSet('name', 'site', 'location', 'description', 'tags', name=_('Floor plan')), + FieldSet('width', 'depth', 'grid_size', name=_('Dimensions (cm)')), + FieldSet('background_image', 'background_opacity', name=_('Background')), + ) + + class Meta: + model = FloorPlan + fields = ( + 'name', 'site', 'location', 'description', 'width', 'depth', 'grid_size', + 'background_image', 'background_opacity', 'comments', 'tags', + ) + widgets = { + 'background_image': forms.ClearableFileInput(attrs={'accept': 'image/*'}), + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self.instance.pk: + for field, setting in (('width', 'default_width'), ('depth', 'default_depth'), + ('grid_size', 'default_grid_size')): + self.fields[field].initial = get_plugin_config('netbox_floorplanner', setting) + + +class FloorPlanFilterForm(NetBoxModelFilterSetForm): + model = FloorPlan + fieldsets = ( + FieldSet('q', 'filter_id', 'tag'), + FieldSet('site_id', 'location_id', name=_('Location')), + ) + site_id = DynamicModelMultipleChoiceField(queryset=Site.objects.all(), required=False, label=_('Site')) + location_id = DynamicModelMultipleChoiceField( + queryset=Location.objects.all(), + required=False, + query_params={'site_id': '$site_id'}, + label=_('Location'), + ) + tag = TagFilterField(model) + + +class FloorPlanImportForm(NetBoxModelImportForm): + site = CSVModelChoiceField(label=_('Site'), queryset=Site.objects.all(), to_field_name='name') + location = CSVModelChoiceField( + label=_('Location'), queryset=Location.objects.all(), to_field_name='name', required=False, + ) + + class Meta: + model = FloorPlan + fields = ('name', 'site', 'location', 'description', 'width', 'depth', 'grid_size', 'comments', 'tags') diff --git a/netbox_floorplanner/locale/de/LC_MESSAGES/django.mo b/netbox_floorplanner/locale/de/LC_MESSAGES/django.mo new file mode 100644 index 0000000..dca770e Binary files /dev/null and b/netbox_floorplanner/locale/de/LC_MESSAGES/django.mo differ diff --git a/netbox_floorplanner/locale/de/LC_MESSAGES/django.po b/netbox_floorplanner/locale/de/LC_MESSAGES/django.po new file mode 100644 index 0000000..c310aa2 --- /dev/null +++ b/netbox_floorplanner/locale/de/LC_MESSAGES/django.po @@ -0,0 +1,391 @@ +# German translation for netbox-floorplanner. +msgid "" +msgstr "" +"Project-Id-Version: netbox-floorplanner 0.1.0\n" +"Language: de\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +# Plugin / navigation +msgid "Floor Planner" +msgstr "Grundrissplaner" + +msgid "Drag & drop floor plan designer for sites and locations" +msgstr "Drag-&-Drop-Grundrissdesigner für Standorte und Räume" + +msgid "Floor Plans" +msgstr "Grundrisse" + +msgid "Add" +msgstr "Hinzufügen" + +msgid "Import" +msgstr "Importieren" + +# Item types +msgid "Rack" +msgstr "Rack" + +msgid "Device" +msgstr "Gerät" + +msgid "Wall" +msgstr "Wand" + +msgid "Door" +msgstr "Tür" + +msgid "Window" +msgstr "Fenster" + +msgid "Area" +msgstr "Bereich" + +msgid "Column" +msgstr "Säule" + +msgid "Cooling unit" +msgstr "Klimagerät" + +msgid "Power / UPS" +msgstr "Strom / USV" + +msgid "Label" +msgstr "Beschriftung" + +# Model fields +msgid "name" +msgstr "Name" + +msgid "site" +msgstr "Standort" + +msgid "location" +msgstr "Raum" + +msgid "width" +msgstr "Breite" + +msgid "depth" +msgstr "Tiefe" + +msgid "grid size" +msgstr "Rastergröße" + +msgid "background image" +msgstr "Hintergrundbild" + +msgid "background opacity" +msgstr "Deckkraft des Hintergrunds" + +msgid "description" +msgstr "Beschreibung" + +msgid "comments" +msgstr "Kommentare" + +msgid "floor plan" +msgstr "Grundriss" + +msgid "floor plans" +msgstr "Grundrisse" + +msgid "floor plan item" +msgstr "Grundriss-Element" + +msgid "floor plan items" +msgstr "Grundriss-Elemente" + +msgid "type" +msgstr "Typ" + +msgid "label" +msgstr "Beschriftung" + +msgid "X" +msgstr "X" + +msgid "Y" +msgstr "Y" + +msgid "height" +msgstr "Höhe" + +msgid "rotation" +msgstr "Drehung" + +msgid "color" +msgstr "Farbe" + +msgid "z-index" +msgstr "Ebene" + +msgid "rack" +msgstr "Rack" + +msgid "device" +msgstr "Gerät" + +msgid "properties" +msgstr "Eigenschaften" + +msgid "Room width in centimeters" +msgstr "Raumbreite in Zentimetern" + +msgid "Room depth in centimeters" +msgstr "Raumtiefe in Zentimetern" + +msgid "Grid spacing in centimeters (used for snapping)" +msgstr "Rasterabstand in Zentimetern (für das Einrasten)" + +msgid "Optional architectural drawing shown behind the plan, stretched to the room size" +msgstr "Optionale Bauzeichnung hinter dem Plan, auf die Raumgröße gestreckt" + +msgid "Opacity of the background image in percent" +msgstr "Deckkraft des Hintergrundbilds in Prozent" + +msgid "The location must belong to the selected site." +msgstr "Der Raum muss zum ausgewählten Standort gehören." + +# Filters, forms, tables +msgid "Site (ID)" +msgstr "Standort (ID)" + +msgid "Site (slug)" +msgstr "Standort (Slug)" + +msgid "Location (ID)" +msgstr "Raum (ID)" + +msgid "Contains rack (ID)" +msgstr "Enthält Rack (ID)" + +msgid "Site" +msgstr "Standort" + +msgid "Location" +msgstr "Raum" + +msgid "Floor plan" +msgstr "Grundriss" + +msgid "Dimensions (cm)" +msgstr "Abmessungen (cm)" + +msgid "Background" +msgstr "Hintergrund" + +msgid "Name" +msgstr "Name" + +msgid "Width (cm)" +msgstr "Breite (cm)" + +msgid "Depth (cm)" +msgstr "Tiefe (cm)" + +msgid "Items" +msgstr "Elemente" + +msgid "Racks" +msgstr "Racks" + +# API validation +msgid "Color must be a hex value like #3b82f6." +msgstr "Die Farbe muss ein Hex-Wert wie #3b82f6 sein." + +msgid "{obj} does not belong to site {site}." +msgstr "{obj} gehört nicht zum Standort {site}." + +msgid "An item can be linked to a rack or a device, not both." +msgstr "Ein Element kann mit einem Rack oder einem Gerät verknüpft sein, nicht mit beiden." + +msgid "{obj} is placed more than once." +msgstr "{obj} ist mehrfach platziert." + +# Views / templates +msgid "Designer" +msgstr "Designer" + +msgid "Open designer" +msgstr "Designer öffnen" + +msgid "Dimensions" +msgstr "Abmessungen" + +msgid "Grid size" +msgstr "Rastergröße" + +msgid "Description" +msgstr "Beschreibung" + +msgid "Add floor plan" +msgstr "Grundriss hinzufügen" + +msgid "Show on floor plan" +msgstr "Im Grundriss anzeigen" + +# Designer (JavaScript) +msgid "Save" +msgstr "Speichern" + +msgid "Saving…" +msgstr "Speichere…" + +msgid "Saved" +msgstr "Gespeichert" + +msgid "Unsaved changes" +msgstr "Ungespeicherte Änderungen" + +msgid "Save failed" +msgstr "Speichern fehlgeschlagen" + +msgid "You have unsaved changes. Leave anyway?" +msgstr "Es gibt ungespeicherte Änderungen. Trotzdem verlassen?" + +msgid "Undo" +msgstr "Rückgängig" + +msgid "Redo" +msgstr "Wiederholen" + +msgid "Delete" +msgstr "Löschen" + +msgid "Duplicate" +msgstr "Duplizieren" + +msgid "Rotate 90°" +msgstr "90° drehen" + +msgid "Bring to front" +msgstr "In den Vordergrund" + +msgid "Send to back" +msgstr "In den Hintergrund" + +msgid "Zoom in" +msgstr "Vergrößern" + +msgid "Zoom out" +msgstr "Verkleinern" + +msgid "Fit to screen" +msgstr "An Bildschirm anpassen" + +msgid "Snap to grid" +msgstr "Am Raster ausrichten" + +msgid "Show grid" +msgstr "Raster anzeigen" + +msgid "Fullscreen" +msgstr "Vollbild" + +msgid "Export SVG" +msgstr "Als SVG exportieren" + +msgid "Export PNG" +msgstr "Als PNG exportieren" + +msgid "Shapes" +msgstr "Formen" + +msgid "Devices" +msgstr "Geräte" + +msgid "Search…" +msgstr "Suchen…" + +msgid "Loading…" +msgstr "Lade…" + +msgid "No racks found" +msgstr "Keine Racks gefunden" + +msgid "No devices found" +msgstr "Keine Geräte gefunden" + +msgid "Already placed" +msgstr "Bereits platziert" + +msgid "Drag onto the plan or click to add" +msgstr "Auf den Plan ziehen oder zum Hinzufügen klicken" + +msgid "Properties" +msgstr "Eigenschaften" + +msgid "Nothing selected – plan settings" +msgstr "Nichts ausgewählt – Planeinstellungen" + +msgid "{n} items selected" +msgstr "{n} Elemente ausgewählt" + +msgid "Type" +msgstr "Typ" + +msgid "X (cm)" +msgstr "X (cm)" + +msgid "Y (cm)" +msgstr "Y (cm)" + +msgid "Height (cm)" +msgstr "Höhe (cm)" + +msgid "Rotation (°)" +msgstr "Drehung (°)" + +msgid "Color" +msgstr "Farbe" + +msgid "Reset color" +msgstr "Farbe zurücksetzen" + +msgid "Linked object" +msgstr "Verknüpftes Objekt" + +msgid "Open object" +msgstr "Objekt öffnen" + +msgid "Grid size (cm)" +msgstr "Rastergröße (cm)" + +msgid "Status" +msgstr "Status" + +msgid "Role" +msgstr "Rolle" + +msgid "Tenant" +msgstr "Mandant" + +msgid "Height (U)" +msgstr "Höhe (HE)" + +msgid "Devices in rack" +msgstr "Geräte im Rack" + +msgid "Color by" +msgstr "Einfärben nach" + +msgid "Item type" +msgstr "Elementtyp" + +msgid "Highlight…" +msgstr "Hervorheben…" + +msgid "Keyboard shortcuts" +msgstr "Tastenkürzel" + +msgid "Drag: move · Alt: no snapping · Shift+click: multi-select · Space+drag / middle mouse: pan · Wheel: zoom · R: rotate · Del: delete · Ctrl+Z/Y: undo/redo · Ctrl+C/V/D: copy/paste/duplicate · Ctrl+S: save" +msgstr "Ziehen: verschieben · Alt: ohne Einrasten · Umschalt+Klick: Mehrfachauswahl · Leertaste+Ziehen / mittlere Maustaste: Ansicht verschieben · Mausrad: Zoom · R: drehen · Entf: löschen · Strg+Z/Y: rückgängig/wiederholen · Strg+C/V/D: kopieren/einfügen/duplizieren · Strg+S: speichern" + +msgid "Wheel: zoom · Drag: pan · Click a rack or device to open it" +msgstr "Mausrad: Zoom · Ziehen: Ansicht verschieben · Rack oder Gerät anklicken, um es zu öffnen" + +msgid "This floor plan is empty." +msgstr "Dieser Grundriss ist leer." diff --git a/netbox_floorplanner/migrations/0001_initial.py b/netbox_floorplanner/migrations/0001_initial.py new file mode 100644 index 0000000..ae91c40 --- /dev/null +++ b/netbox_floorplanner/migrations/0001_initial.py @@ -0,0 +1,74 @@ +import django.core.validators +import django.db.models.deletion +import taggit.managers +import utilities.json +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('dcim', '__first__'), + ('extras', '__first__'), + ] + + operations = [ + migrations.CreateModel( + name='FloorPlan', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)), + ('created', models.DateTimeField(auto_now_add=True, null=True)), + ('last_updated', models.DateTimeField(auto_now=True, null=True)), + ('custom_field_data', models.JSONField(blank=True, default=dict, encoder=utilities.json.CustomFieldJSONEncoder)), + ('name', models.CharField(max_length=100)), + ('width', models.PositiveIntegerField(default=2000, validators=[django.core.validators.MinValueValidator(100), django.core.validators.MaxValueValidator(100000)])), + ('depth', models.PositiveIntegerField(default=1500, validators=[django.core.validators.MinValueValidator(100), django.core.validators.MaxValueValidator(100000)])), + ('grid_size', models.PositiveIntegerField(default=50, validators=[django.core.validators.MinValueValidator(5), django.core.validators.MaxValueValidator(1000)])), + ('background_image', models.ImageField(blank=True, upload_to='floorplanner/')), + ('background_opacity', models.PositiveSmallIntegerField(default=40, validators=[django.core.validators.MaxValueValidator(100)])), + ('description', models.CharField(blank=True, max_length=200)), + ('comments', models.TextField(blank=True)), + ('site', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='floorplans', to='dcim.site')), + ('location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='floorplans', to='dcim.location')), + ('tags', taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag')), + ], + options={ + 'verbose_name': 'floor plan', + 'verbose_name_plural': 'floor plans', + 'ordering': ('site', 'location', 'name'), + }, + ), + migrations.AddConstraint( + model_name='floorplan', + constraint=models.UniqueConstraint( + fields=('site', 'location', 'name'), + name='netbox_floorplanner_floorplan_unique_site_location_name', + ), + ), + migrations.CreateModel( + name='FloorPlanItem', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)), + ('item_type', models.CharField(max_length=30)), + ('label', models.CharField(blank=True, max_length=100)), + ('x', models.IntegerField(default=0)), + ('y', models.IntegerField(default=0)), + ('width', models.PositiveIntegerField(default=60)), + ('height', models.PositiveIntegerField(default=60)), + ('rotation', models.SmallIntegerField(default=0, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(359)])), + ('color', models.CharField(blank=True, max_length=7)), + ('z_index', models.SmallIntegerField(default=0)), + ('properties', models.JSONField(blank=True, default=dict)), + ('floorplan', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='netbox_floorplanner.floorplan')), + ('rack', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='floorplan_items', to='dcim.rack')), + ('device', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='floorplan_items', to='dcim.device')), + ], + options={ + 'verbose_name': 'floor plan item', + 'verbose_name_plural': 'floor plan items', + 'ordering': ('floorplan', 'z_index', 'pk'), + }, + ), + ] diff --git a/netbox_floorplanner/migrations/__init__.py b/netbox_floorplanner/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/netbox_floorplanner/models.py b/netbox_floorplanner/models.py new file mode 100644 index 0000000..4dff9d5 --- /dev/null +++ b/netbox_floorplanner/models.py @@ -0,0 +1,133 @@ +from django.core.exceptions import ValidationError +from django.core.validators import MaxValueValidator, MinValueValidator +from django.db import models +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ +from netbox.models import NetBoxModel + +from .choices import ItemTypeChoices + +__all__ = ('FloorPlan', 'FloorPlanItem') + + +class FloorPlan(NetBoxModel): + name = models.CharField(verbose_name=_('name'), max_length=100) + site = models.ForeignKey( + to='dcim.Site', + on_delete=models.CASCADE, + related_name='floorplans', + verbose_name=_('site'), + ) + location = models.ForeignKey( + to='dcim.Location', + on_delete=models.CASCADE, + related_name='floorplans', + blank=True, + null=True, + verbose_name=_('location'), + ) + width = models.PositiveIntegerField( + verbose_name=_('width'), + default=2000, + validators=[MinValueValidator(100), MaxValueValidator(100000)], + help_text=_('Room width in centimeters'), + ) + depth = models.PositiveIntegerField( + verbose_name=_('depth'), + default=1500, + validators=[MinValueValidator(100), MaxValueValidator(100000)], + help_text=_('Room depth in centimeters'), + ) + grid_size = models.PositiveIntegerField( + verbose_name=_('grid size'), + default=50, + validators=[MinValueValidator(5), MaxValueValidator(1000)], + help_text=_('Grid spacing in centimeters (used for snapping)'), + ) + background_image = models.ImageField( + verbose_name=_('background image'), + upload_to='floorplanner/', + blank=True, + help_text=_('Optional architectural drawing shown behind the plan, stretched to the room size'), + ) + background_opacity = models.PositiveSmallIntegerField( + verbose_name=_('background opacity'), + default=40, + validators=[MaxValueValidator(100)], + help_text=_('Opacity of the background image in percent'), + ) + description = models.CharField(verbose_name=_('description'), max_length=200, blank=True) + comments = models.TextField(verbose_name=_('comments'), blank=True) + + class Meta: + ordering = ('site', 'location', 'name') + verbose_name = _('floor plan') + verbose_name_plural = _('floor plans') + constraints = ( + models.UniqueConstraint( + fields=('site', 'location', 'name'), + name='netbox_floorplanner_floorplan_unique_site_location_name', + ), + ) + + def __str__(self): + return self.name + + def get_absolute_url(self): + return reverse('plugins:netbox_floorplanner:floorplan', args=[self.pk]) + + def clean(self): + super().clean() + if self.location_id and self.site_id and self.location.site_id != self.site_id: + raise ValidationError({'location': _('The location must belong to the selected site.')}) + + +class FloorPlanItem(models.Model): + """ + A single shape on a floor plan. Items are always written as a whole layout + through the layout API endpoint; changes are change-logged on the parent plan. + """ + floorplan = models.ForeignKey( + to=FloorPlan, + on_delete=models.CASCADE, + related_name='items', + verbose_name=_('floor plan'), + ) + item_type = models.CharField(verbose_name=_('type'), max_length=30, choices=ItemTypeChoices) + label = models.CharField(verbose_name=_('label'), max_length=100, blank=True) + x = models.IntegerField(verbose_name=_('X'), default=0) + y = models.IntegerField(verbose_name=_('Y'), default=0) + width = models.PositiveIntegerField(verbose_name=_('width'), default=60) + height = models.PositiveIntegerField(verbose_name=_('height'), default=60) + rotation = models.SmallIntegerField( + verbose_name=_('rotation'), + default=0, + validators=[MinValueValidator(0), MaxValueValidator(359)], + ) + color = models.CharField(verbose_name=_('color'), max_length=7, blank=True) + z_index = models.SmallIntegerField(verbose_name=_('z-index'), default=0) + rack = models.ForeignKey( + to='dcim.Rack', + on_delete=models.CASCADE, + related_name='floorplan_items', + blank=True, + null=True, + verbose_name=_('rack'), + ) + device = models.ForeignKey( + to='dcim.Device', + on_delete=models.CASCADE, + related_name='floorplan_items', + blank=True, + null=True, + verbose_name=_('device'), + ) + properties = models.JSONField(verbose_name=_('properties'), default=dict, blank=True) + + class Meta: + ordering = ('floorplan', 'z_index', 'pk') + verbose_name = _('floor plan item') + verbose_name_plural = _('floor plan items') + + def __str__(self): + return self.label or f'{self.get_item_type_display()} #{self.pk}' diff --git a/netbox_floorplanner/navigation.py b/netbox_floorplanner/navigation.py new file mode 100644 index 0000000..a5cccef --- /dev/null +++ b/netbox_floorplanner/navigation.py @@ -0,0 +1,30 @@ +from django.utils.translation import gettext_lazy as _ +from netbox.plugins import PluginMenu, PluginMenuButton, PluginMenuItem + +menu = PluginMenu( + label=_('Floor Planner'), + icon_class='mdi mdi-floor-plan', + groups=( + (_('Floor Plans'), ( + PluginMenuItem( + link='plugins:netbox_floorplanner:floorplan_list', + link_text=_('Floor Plans'), + permissions=['netbox_floorplanner.view_floorplan'], + buttons=( + PluginMenuButton( + link='plugins:netbox_floorplanner:floorplan_add', + title=_('Add'), + icon_class='mdi mdi-plus-thick', + permissions=['netbox_floorplanner.add_floorplan'], + ), + PluginMenuButton( + link='plugins:netbox_floorplanner:floorplan_bulk_import', + title=_('Import'), + icon_class='mdi mdi-upload', + permissions=['netbox_floorplanner.add_floorplan'], + ), + ), + ), + )), + ), +) diff --git a/netbox_floorplanner/search.py b/netbox_floorplanner/search.py new file mode 100644 index 0000000..2e353a5 --- /dev/null +++ b/netbox_floorplanner/search.py @@ -0,0 +1,16 @@ +from netbox.search import SearchIndex + +from .models import FloorPlan + + +class FloorPlanIndex(SearchIndex): + model = FloorPlan + fields = ( + ('name', 100), + ('description', 500), + ('comments', 5000), + ) + display_attrs = ('site', 'location', 'description') + + +indexes = (FloorPlanIndex,) diff --git a/netbox_floorplanner/static/netbox_floorplanner/floorplanner.css b/netbox_floorplanner/static/netbox_floorplanner/floorplanner.css new file mode 100644 index 0000000..85a6963 --- /dev/null +++ b/netbox_floorplanner/static/netbox_floorplanner/floorplanner.css @@ -0,0 +1,160 @@ +.fp-root { + --fp-bg: #f1f5f9; + --fp-floor: #ffffff; + --fp-grid: #e2e8f0; + --fp-wall: #334155; + --fp-text: #0f172a; + --fp-panel: #ffffff; + --fp-border: #dee2e6; + --fp-accent: #206bc4; + --fp-muted: #6c757d; + display: flex; + flex-direction: column; + border: 1px solid var(--fp-border); + border-radius: 6px; + background: var(--fp-panel); + overflow: hidden; + outline: none; +} + +[data-bs-theme="dark"] .fp-root { + --fp-bg: #111827; + --fp-floor: #1f2937; + --fp-grid: #2d3a4d; + --fp-wall: #94a3b8; + --fp-text: #e5e7eb; + --fp-panel: #182433; + --fp-border: #2c3e50; + --fp-muted: #9aa5b1; +} + +.fp-root:fullscreen { border-radius: 0; } +.fp-root:fullscreen .fp-body { height: auto; flex: 1; } + +.fp-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + padding: 6px 8px; + border-bottom: 1px solid var(--fp-border); +} +.fp-group { align-items: center; } +.fp-btn { border: 1px solid var(--fp-border); background: transparent; color: inherit; } +.fp-btn:hover { background: rgba(32, 107, 196, .1); } +.fp-btn.active { background: rgba(32, 107, 196, .18); color: var(--fp-accent); border-color: var(--fp-accent); } +.fp-btn:disabled { opacity: .4; } +.fp-btn .mdi { font-size: 1.1rem; line-height: 1; } +.fp-zoom-label { min-width: 52px; text-align: center; font-size: .8rem; font-variant-numeric: tabular-nums; } +.fp-select { width: auto; } +.fp-search { width: 200px; } +.fp-spacer { flex: 1; } +.fp-save-state { font-size: .8rem; color: var(--fp-muted); } +.fp-save-state.dirty { color: #f59f00; } +.fp-save-state.ok { color: #2fb344; } +.fp-save-state.error { color: #d63939; } + +.fp-body { display: flex; height: 72vh; min-height: 420px; } +.fp-view .fp-body { height: 62vh; } + +.fp-canvas { position: relative; flex: 1; min-width: 0; background: var(--fp-bg); } +.fp-svg { display: block; width: 100%; height: 100%; user-select: none; touch-action: none; cursor: default; } +.fp-view .fp-svg { cursor: grab; } +.fp-svg.fp-panning, .fp-svg.fp-panning * { cursor: grab !important; } + +.fp-edit .fp-item { cursor: move; } +.fp-view .fp-item.fp-linked { cursor: pointer; } +.fp-item.fp-linked:hover > rect:first-child { filter: brightness(1.12); } +.fp-item.fp-dimmed { opacity: .2; } + +.fp-selection { fill: none; stroke: var(--fp-accent); pointer-events: none; } +.fp-handle { fill: #ffffff; stroke: var(--fp-accent); } +.fp-rot { cursor: grab; } +.fp-rot-line { stroke: var(--fp-accent); pointer-events: none; } +.fp-band { fill: rgba(32, 107, 196, .08); stroke: var(--fp-accent); pointer-events: none; } +.fp-guide { stroke: #e8590c; pointer-events: none; } +.fp-highlight { fill: none; stroke: #f59f00; pointer-events: none; animation: fp-pulse 1.2s ease-in-out infinite; } +@keyframes fp-pulse { 50% { stroke-opacity: .2; } } + +.fp-palette, .fp-panel { + width: 240px; + flex-shrink: 0; + overflow-y: auto; + padding: 8px; + font-size: .85rem; +} +.fp-palette { border-right: 1px solid var(--fp-border); } +.fp-panel { border-left: 1px solid var(--fp-border); } +.fp-palette-title { + font-size: .7rem; + font-weight: 700; + text-transform: uppercase; + letter-spacing: .04em; + color: var(--fp-muted); + margin: 10px 0 6px; +} +.fp-palette-title:first-child { margin-top: 0; } +.fp-shapes { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; } +.fp-shapes .fp-entry { flex-direction: column; justify-content: center; text-align: center; padding: 6px 4px; } +.fp-shapes .fp-entry .mdi { font-size: 1.3rem; } +.fp-entry { + display: flex; + align-items: center; + gap: 6px; + padding: 4px 6px; + border: 1px solid var(--fp-border); + border-radius: 4px; + margin-bottom: 3px; + cursor: grab; + background: var(--fp-panel); +} +.fp-entry:hover { border-color: var(--fp-accent); background: rgba(32, 107, 196, .06); } +.fp-entry.disabled { opacity: .5; cursor: default; } +.fp-entry.disabled:hover { border-color: var(--fp-border); background: var(--fp-panel); } +.fp-entry-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fp-shapes .fp-entry-label { flex: none; font-size: .75rem; } +.fp-entry-sub { font-size: .7rem; color: var(--fp-muted); } +.fp-entry-check { color: #2fb344; } +.fp-objlist { max-height: 30vh; overflow-y: auto; } +.fp-palette-search { margin-top: 10px; } +.fp-muted { color: var(--fp-muted); font-size: .8rem; } +.fp-hint { margin-top: 10px; font-size: .75rem; color: var(--fp-muted); } + +.fp-field { display: block; margin-bottom: 8px; width: 100%; } +.fp-field > span { display: block; font-size: .75rem; color: var(--fp-muted); margin-bottom: 2px; } +.fp-row { display: flex; gap: 6px; } +.fp-color { display: flex; gap: 6px; } +.fp-type-badge { font-weight: 600; margin-bottom: 8px; } +.fp-info { display: grid; grid-template-columns: auto 1fr; gap: 2px 8px; margin-bottom: 10px; font-size: .8rem; } +.fp-info dt { font-weight: 400; color: var(--fp-muted); } +.fp-info dd { margin: 0; overflow: hidden; text-overflow: ellipsis; } + +.fp-tooltip { + position: absolute; + z-index: 10; + pointer-events: none; + min-width: 160px; + max-width: 280px; + padding: 8px 10px; + border-radius: 6px; + background: var(--fp-panel); + border: 1px solid var(--fp-border); + box-shadow: 0 4px 16px rgba(0, 0, 0, .15); + font-size: .8rem; +} + +.fp-statusbar { + padding: 4px 8px; + border-top: 1px solid var(--fp-border); + font-size: .72rem; + color: var(--fp-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +@media (max-width: 992px) { + .fp-body { flex-direction: column; height: auto; } + .fp-canvas { height: 60vh; } + .fp-palette, .fp-panel { width: auto; max-height: 30vh; border: none; border-top: 1px solid var(--fp-border); } +} diff --git a/netbox_floorplanner/static/netbox_floorplanner/floorplanner.js b/netbox_floorplanner/static/netbox_floorplanner/floorplanner.js new file mode 100644 index 0000000..43ba4d0 --- /dev/null +++ b/netbox_floorplanner/static/netbox_floorplanner/floorplanner.js @@ -0,0 +1,1297 @@ +/* + * NetBox Floor Planner – interactive SVG floor plan designer. + * Units: 1 SVG user unit = 1 cm. Item x/y is the top-left corner of the + * unrotated shape; rotation is applied around the shape's center. + */ +(function () { + 'use strict'; + + const NS = 'http://www.w3.org/2000/svg'; + + const TYPES = { + area: { w: 400, h: 300, color: '#22c55e', z: -10, icon: 'mdi-texture-box' }, + wall: { w: 300, h: 15, color: '#475569', z: 0, icon: 'mdi-wall' }, + door: { w: 90, h: 10, color: '#b45309', z: 1, icon: 'mdi-door' }, + window: { w: 120, h: 10, color: '#0ea5e9', z: 1, icon: 'mdi-window-closed-variant' }, + column: { w: 40, h: 40, color: '#64748b', z: 2, icon: 'mdi-square' }, + rack: { w: 60, h: 120, color: '#3b82f6', z: 5, icon: 'mdi-server' }, + device: { w: 50, h: 50, color: '#8b5cf6', z: 5, icon: 'mdi-access-point' }, + cooling: { w: 100, h: 90, color: '#06b6d4', z: 5, icon: 'mdi-snowflake' }, + power: { w: 80, h: 60, color: '#f59e0b', z: 5, icon: 'mdi-flash' }, + label: { w: 200, h: 40, color: '#334155', z: 10, icon: 'mdi-format-text' }, + }; + const SHAPE_ORDER = ['wall', 'door', 'window', 'area', 'column', 'cooling', 'power', 'label']; + + const COLOR_NAMES = { + green: '#2fb344', red: '#d63939', blue: '#206bc4', cyan: '#17a2b8', yellow: '#f59f00', + orange: '#f76707', purple: '#ae3ec9', gray: '#868e96', teal: '#0ca678', indigo: '#4263eb', + pink: '#d6336c', dark: '#343a40', black: '#000000', white: '#ffffff', + }; + // Fallback status colors for objects coming from the REST API (NetBox defaults) + const STATUS_COLORS = { + active: 'green', planned: 'cyan', reserved: 'yellow', available: 'gray', deprecated: 'red', + offline: 'gray', staged: 'blue', failed: 'red', inventory: 'purple', decommissioning: 'yellow', + }; + + const MIN_SIZE = 5; + const HISTORY_LIMIT = 100; + + /* ---------- helpers ---------- */ + + function svg(tag, attrs, parent) { + const node = document.createElementNS(NS, tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (v !== undefined && v !== null) node.setAttribute(k, v); + } + if (parent) parent.appendChild(node); + return node; + } + + function html(tag, attrs, children) { + const node = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (v === undefined || v === null || v === false) continue; + if (k === 'class') node.className = v; + else if (k === 'text') node.textContent = v; + else if (k.startsWith('on')) node.addEventListener(k.slice(2), v); + else node.setAttribute(k, v === true ? '' : v); + } + for (const child of [].concat(children || [])) { + if (child) node.appendChild(typeof child === 'string' ? document.createTextNode(child) : child); + } + return node; + } + + function getCookie(name) { + const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)')); + return match ? decodeURIComponent(match[1]) : ''; + } + + const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v)); + const snap = (v, step) => Math.round(v / step) * step; + + function toCm(value, unit) { + if (!value) return null; + const u = unit && (unit.value || unit); + return Math.round(u === 'in' ? value * 2.54 : value / 10); + } + + function download(filename, blob) { + const a = html('a', { href: URL.createObjectURL(blob), download: filename }); + document.body.appendChild(a); + a.click(); + setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 1000); + } + + function blobToDataUrl(blob) { + return new Promise((resolve) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.readAsDataURL(blob); + }); + } + + /* ---------- designer ---------- */ + + class Designer { + constructor(root, cfg) { + this.root = root; + this.cfg = cfg; + this.edit = cfg.mode === 'edit'; + this.strings = cfg.strings || {}; + this.settings = Object.assign({}, cfg.settings); + this.items = []; + this.selection = new Set(); + this.view = { x: 0, y: 0, scale: 1 }; + this.undoStack = []; + this.redoStack = []; + this.clipboard = []; + this.dirty = false; + this.snapEnabled = true; + this.gridVisible = true; + this.colorMode = 'type'; + this.filter = ''; + this.drag = null; + this.spaceDown = false; + this.uidCounter = 1; + this.palette = { racks: null, devices: null, search: '' }; + this.guides = []; + + this.buildDom(); + this.bindEvents(); + this.load(); + } + + t(s, params) { + let out = this.strings[s] || s; + for (const [k, v] of Object.entries(params || {})) out = out.replace('{' + k + '}', v); + return out; + } + + /* ----- DOM ----- */ + + buildDom() { + this.root.classList.add(this.edit ? 'fp-edit' : 'fp-view'); + this.root.tabIndex = 0; + this.root.innerHTML = ''; + + this.toolbar = html('div', { class: 'fp-toolbar' }); + this.body = html('div', { class: 'fp-body' }); + this.canvasWrap = html('div', { class: 'fp-canvas' }); + this.tooltip = html('div', { class: 'fp-tooltip', hidden: true }); + this.statusBar = html('div', { class: 'fp-statusbar' }); + + if (this.edit) { + this.paletteEl = html('div', { class: 'fp-palette' }); + this.panelEl = html('div', { class: 'fp-panel' }); + this.body.append(this.paletteEl, this.canvasWrap, this.panelEl); + } else { + this.body.append(this.canvasWrap); + } + this.root.append(this.toolbar, this.body, this.statusBar); + + this.svg = svg('svg', { class: 'fp-svg', xmlns: NS }, this.canvasWrap); + this.canvasWrap.appendChild(this.tooltip); + const defs = svg('defs', {}, this.svg); + this.gridId = 'fp-grid-' + Math.random().toString(36).slice(2, 8); + this.gridPattern = svg('pattern', { id: this.gridId, patternUnits: 'userSpaceOnUse' }, defs); + this.gridPath = svg('path', { fill: 'none', 'stroke-width': 1, 'vector-effect': 'non-scaling-stroke' }, this.gridPattern); + + this.viewport = svg('g', { class: 'fp-viewport' }, this.svg); + this.floor = svg('rect', { class: 'fp-floor', x: 0, y: 0 }, this.viewport); + this.bgImage = svg('image', { preserveAspectRatio: 'none', x: 0, y: 0 }, this.viewport); + this.gridRect = svg('rect', { x: 0, y: 0, fill: `url(#${this.gridId})`, 'pointer-events': 'none' }, this.viewport); + this.floorBorder = svg('rect', { class: 'fp-floor-border', x: 0, y: 0, fill: 'none', 'pointer-events': 'none' }, this.viewport); + this.itemsLayer = svg('g', { class: 'fp-items' }, this.viewport); + this.overlay = svg('g', { class: 'fp-overlay' }, this.viewport); + + this.buildToolbar(); + if (this.edit) this.buildPalette(); + this.updateStatusBar(); + } + + button(icon, title, onclick, extraClass) { + return html('button', { + type: 'button', class: 'btn btn-sm fp-btn ' + (extraClass || ''), title: title, 'aria-label': title, + onclick: (e) => { e.preventDefault(); onclick(e); this.root.focus({ preventScroll: true }); }, + }, [html('i', { class: 'mdi ' + icon })]); + } + + buildToolbar() { + const tb = this.toolbar; + const group = (...nodes) => html('div', { class: 'btn-group fp-group' }, nodes); + + if (this.edit) { + this.saveBtn = html('button', { + type: 'button', class: 'btn btn-sm btn-primary fp-save', onclick: () => this.save(), + }, [html('i', { class: 'mdi mdi-content-save' }), ' ', html('span', { text: this.t('Save') })]); + this.undoBtn = this.button('mdi-undo', this.t('Undo') + ' (Ctrl+Z)', () => this.undo()); + this.redoBtn = this.button('mdi-redo', this.t('Redo') + ' (Ctrl+Y)', () => this.redo()); + this.snapBtn = this.button('mdi-magnet', this.t('Snap to grid'), () => { + this.snapEnabled = !this.snapEnabled; + this.snapBtn.classList.toggle('active', this.snapEnabled); + }, 'active'); + tb.append( + group(this.saveBtn), + group(this.undoBtn, this.redoBtn), + group( + this.button('mdi-content-copy', this.t('Duplicate') + ' (Ctrl+D)', () => this.duplicate()), + this.button('mdi-rotate-right', this.t('Rotate 90°') + ' (R)', () => this.rotateSelection(90)), + this.button('mdi-arrange-bring-to-front', this.t('Bring to front'), () => this.reorder(1)), + this.button('mdi-arrange-send-to-back', this.t('Send to back'), () => this.reorder(-1)), + this.button('mdi-trash-can-outline', this.t('Delete') + ' (Del)', () => this.deleteSelection()), + ), + ); + } else { + this.colorSelect = html('select', { + class: 'form-select form-select-sm fp-select', title: this.t('Color by'), + onchange: (e) => { this.colorMode = e.target.value; this.render(); }, + }, [ + html('option', { value: 'type', text: this.t('Color by') + ': ' + this.t('Item type') }), + html('option', { value: 'status', text: this.t('Color by') + ': ' + this.t('Status') }), + html('option', { value: 'role', text: this.t('Color by') + ': ' + this.t('Role') }), + ]); + this.filterInput = html('input', { + type: 'search', class: 'form-control form-control-sm fp-search', placeholder: this.t('Highlight…'), + oninput: (e) => { this.filter = e.target.value.trim().toLowerCase(); this.render(); }, + }); + tb.append(group(this.colorSelect), group(this.filterInput)); + } + + this.zoomLabel = html('span', { class: 'fp-zoom-label', text: '100%' }); + this.gridBtn = this.button('mdi-grid', this.t('Show grid'), () => { + this.gridVisible = !this.gridVisible; + this.gridBtn.classList.toggle('active', this.gridVisible); + this.renderFloor(); + }, 'active'); + tb.append( + group( + this.button('mdi-magnify-minus-outline', this.t('Zoom out') + ' (-)', () => this.zoomBy(1 / 1.25)), + this.zoomLabel, + this.button('mdi-magnify-plus-outline', this.t('Zoom in') + ' (+)', () => this.zoomBy(1.25)), + this.button('mdi-fit-to-screen-outline', this.t('Fit to screen') + ' (0)', () => this.fit()), + ), + group(...[this.snapBtn, this.gridBtn].filter(Boolean)), + group( + this.button('mdi-svg', this.t('Export SVG'), () => this.exportSvg()), + this.button('mdi-file-image-outline', this.t('Export PNG'), () => this.exportPng()), + this.button('mdi-fullscreen', this.t('Fullscreen'), () => this.toggleFullscreen()), + ), + ); + this.saveState = html('span', { class: 'fp-save-state' }); + tb.append(html('div', { class: 'fp-spacer' }), this.saveState); + } + + buildPalette() { + const p = this.paletteEl; + p.innerHTML = ''; + p.append(html('div', { class: 'fp-palette-title', text: this.t('Shapes') })); + const shapes = html('div', { class: 'fp-shapes' }); + for (const type of SHAPE_ORDER) { + shapes.append(this.paletteEntry({ kind: 'shape', type: type }, TYPES[type].icon, this.cfg.types[type] || type)); + } + p.append(shapes); + + this.paletteSearch = html('input', { + type: 'search', class: 'form-control form-control-sm fp-palette-search', placeholder: this.t('Search…'), + oninput: (e) => { this.palette.search = e.target.value.toLowerCase(); this.renderObjectLists(); }, + }); + this.rackList = html('div', { class: 'fp-objlist' }, [html('div', { class: 'fp-muted', text: this.t('Loading…') })]); + this.deviceList = html('div', { class: 'fp-objlist' }, [html('div', { class: 'fp-muted', text: this.t('Loading…') })]); + p.append( + this.paletteSearch, + html('div', { class: 'fp-palette-title', text: this.t('Racks') }), this.rackList, + html('div', { class: 'fp-palette-title', text: this.t('Devices') }), this.deviceList, + html('div', { class: 'fp-hint', text: this.t('Drag onto the plan or click to add') }), + ); + } + + paletteEntry(payload, icon, label, sub, disabled) { + const entry = html('div', { + class: 'fp-entry' + (disabled ? ' disabled' : ''), draggable: disabled ? 'false' : 'true', + title: disabled ? this.t('Already placed') : this.t('Drag onto the plan or click to add'), + }, [ + html('i', { class: 'mdi ' + icon }), + html('span', { class: 'fp-entry-label', text: label }), + sub ? html('span', { class: 'fp-entry-sub', text: sub }) : null, + disabled ? html('i', { class: 'mdi mdi-check fp-entry-check' }) : null, + ]); + if (!disabled) { + entry.addEventListener('dragstart', (e) => { + e.dataTransfer.setData('application/x-floorplanner', JSON.stringify(payload)); + e.dataTransfer.effectAllowed = 'copy'; + }); + entry.addEventListener('click', () => { + const r = this.svg.getBoundingClientRect(); + this.addFromPayload(payload, this.toWorld(r.left + r.width / 2, r.top + r.height / 2)); + }); + } + return entry; + } + + async loadObjects() { + const fetchAll = async (url) => { + const out = []; + let next = url; + while (next) { + const resp = await fetch(next, { credentials: 'same-origin', headers: { Accept: 'application/json' } }); + if (!resp.ok) throw new Error(resp.statusText); + const data = await resp.json(); + out.push(...data.results); + next = data.next; + } + return out; + }; + try { + this.palette.racks = await fetchAll(this.cfg.api.racks); + } catch (e) { + this.palette.racks = []; + } + try { + this.palette.devices = await fetchAll(this.cfg.api.devices); + } catch (e) { + this.palette.devices = []; + } + this.renderObjectLists(); + } + + renderObjectLists() { + if (!this.edit || this.palette.racks === null) return; + const placed = new Set(this.items.map((i) => i.rack ? 'rack-' + i.rack : i.device ? 'device-' + i.device : null)); + const q = this.palette.search; + const fill = (container, list, kind, emptyText) => { + container.innerHTML = ''; + const matches = list.filter((o) => !q || (o.display || o.name || '').toLowerCase().includes(q)); + if (!matches.length) { + container.append(html('div', { class: 'fp-muted', text: emptyText })); + return; + } + for (const o of matches) { + const sub = kind === 'rack' + ? (o.u_height ? o.u_height + 'U' : '') + : (o.role && (o.role.display || o.role.name)) || ''; + container.append(this.paletteEntry( + { kind: kind, id: o.id }, TYPES[kind].icon, o.display || o.name, sub, placed.has(kind + '-' + o.id), + )); + } + }; + fill(this.rackList, this.palette.racks, 'rack', this.t('No racks found')); + fill(this.deviceList, this.palette.devices, 'device', this.t('No devices found')); + } + + objectInfoFromApi(o) { + const status = o.status && (o.status.value || o.status); + return { + id: o.id, + name: o.name || o.display, + url: o.display_url || o.url, + status: status, + status_label: o.status && o.status.label, + status_color: STATUS_COLORS[status] || 'gray', + role: o.role && (o.role.display || o.role.name), + role_color: o.role && o.role.color ? '#' + o.role.color : null, + tenant: o.tenant && (o.tenant.display || o.tenant.name), + u_height: o.u_height, + }; + } + + /* ----- data ----- */ + + async load() { + try { + const resp = await fetch(this.cfg.api.layout, { credentials: 'same-origin', headers: { Accept: 'application/json' } }); + if (!resp.ok) throw new Error(resp.statusText); + this.applyLayout(await resp.json()); + } catch (e) { + this.setSaveState(this.t('Save failed') + ': ' + e.message, 'error'); + } + this.renderFloor(); + this.fit(); + this.render(); + this.renderPanel(); + if (this.edit) this.loadObjects(); + if (this.cfg.highlight) this.focusHighlight(this.cfg.highlight); + } + + applyLayout(data) { + Object.assign(this.settings, data.settings || {}); + this.items = (data.items || []).map((i) => Object.assign({ uid: this.uidCounter++ }, i)); + } + + serialize() { + return { + settings: this.settings, + items: this.items.map((i) => ({ + item_type: i.item_type, label: i.label || '', x: Math.round(i.x), y: Math.round(i.y), + width: Math.max(1, Math.round(i.width)), height: Math.max(1, Math.round(i.height)), + rotation: ((Math.round(i.rotation) % 360) + 360) % 360, color: i.color || '', + z_index: i.z_index || 0, rack: i.rack || null, device: i.device || null, properties: i.properties || {}, + })), + }; + } + + async save() { + if (!this.edit) return; + this.setSaveState(this.t('Saving…'), 'busy'); + try { + const resp = await fetch(this.cfg.api.layout, { + method: 'PUT', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRFToken': getCookie('csrftoken') }, + body: JSON.stringify(this.serialize()), + }); + const data = await resp.json().catch(() => ({})); + if (!resp.ok) { + const detail = data.detail || JSON.stringify(data.items || data.settings || data); + throw new Error(detail); + } + const selectedKeys = new Set([...this.selection].map((uid) => this.itemIndex(uid))); + this.applyLayout(data); + this.selection = new Set(this.items.filter((_, idx) => selectedKeys.has(idx)).map((i) => i.uid)); + this.dirty = false; + this.setSaveState(this.t('Saved'), 'ok'); + this.render(); + this.renderPanel(); + this.renderObjectLists(); + } catch (e) { + this.setSaveState(this.t('Save failed') + ': ' + e.message, 'error'); + } + } + + setSaveState(text, kind) { + this.saveState.textContent = text; + this.saveState.className = 'fp-save-state ' + (kind || ''); + } + + markDirty() { + this.dirty = true; + this.setSaveState(this.t('Unsaved changes'), 'dirty'); + this.updateHistoryButtons(); + } + + /* ----- history ----- */ + + snapshotState() { + return JSON.stringify({ settings: this.settings, items: this.items }); + } + + checkpoint() { + this.undoStack.push(this.snapshotState()); + if (this.undoStack.length > HISTORY_LIMIT) this.undoStack.shift(); + this.redoStack = []; + this.markDirty(); + } + + restore(state) { + const data = JSON.parse(state); + this.settings = data.settings; + this.items = data.items; + const uids = new Set(this.items.map((i) => i.uid)); + this.selection = new Set([...this.selection].filter((u) => uids.has(u))); + this.renderFloor(); + this.render(); + this.renderPanel(); + this.renderObjectLists(); + this.markDirty(); + } + + undo() { + if (!this.undoStack.length) return; + this.redoStack.push(this.snapshotState()); + this.restore(this.undoStack.pop()); + } + + redo() { + if (!this.redoStack.length) return; + this.undoStack.push(this.snapshotState()); + this.restore(this.redoStack.pop()); + } + + updateHistoryButtons() { + if (!this.edit) return; + this.undoBtn.disabled = !this.undoStack.length; + this.redoBtn.disabled = !this.redoStack.length; + } + + /* ----- item operations ----- */ + + itemByUid(uid) { return this.items.find((i) => i.uid === uid); } + itemIndex(uid) { return this.items.findIndex((i) => i.uid === uid); } + selectedItems() { return this.items.filter((i) => this.selection.has(i.uid)); } + + gridStep(e) { + return this.snapEnabled && !(e && e.altKey) ? this.settings.grid_size : 1; + } + + sizeStep(e) { + return this.snapEnabled && !(e && e.altKey) ? 5 : 1; + } + + addFromPayload(payload, at) { + let item; + if (payload.kind === 'shape') { + const d = TYPES[payload.type]; + item = { item_type: payload.type, width: d.w, height: d.h, label: payload.type === 'label' ? this.cfg.types.label : '' }; + } else { + const list = payload.kind === 'rack' ? this.palette.racks : this.palette.devices; + const obj = (list || []).find((o) => o.id === payload.id); + if (!obj) return; + if (this.items.some((i) => i[payload.kind] === obj.id)) return; + const w = payload.kind === 'rack' ? (toCm(obj.outer_width, obj.outer_unit) || this.cfg.defaults.rack_width) : TYPES.device.w; + const h = payload.kind === 'rack' ? (toCm(obj.outer_depth, obj.outer_unit) || this.cfg.defaults.rack_depth) : TYPES.device.h; + item = { item_type: payload.kind, width: w, height: h, label: '', object: this.objectInfoFromApi(obj) }; + item[payload.kind] = obj.id; + } + const step = this.gridStep(); + Object.assign(item, { + uid: this.uidCounter++, + x: snap(at.x - item.width / 2, step), + y: snap(at.y - item.height / 2, step), + rotation: 0, color: '', z_index: TYPES[item.item_type].z, properties: {}, + rack: item.rack || null, device: item.device || null, + }); + this.checkpoint(); + this.items.push(item); + this.selection = new Set([item.uid]); + this.render(); + this.renderPanel(); + this.renderObjectLists(); + } + + deleteSelection() { + if (!this.selection.size) return; + this.checkpoint(); + this.items = this.items.filter((i) => !this.selection.has(i.uid)); + this.selection.clear(); + this.render(); + this.renderPanel(); + this.renderObjectLists(); + } + + copySelection() { + this.clipboard = JSON.parse(JSON.stringify(this.selectedItems())); + } + + paste(offset) { + // Linked racks/devices may exist only once on a plan, so pasted copies are unlinked + if (!this.clipboard.length) return; + this.checkpoint(); + const step = offset === undefined ? this.settings.grid_size : offset; + const added = this.clipboard.map((src) => { + const copy = JSON.parse(JSON.stringify(src)); + Object.assign(copy, { uid: this.uidCounter++, x: src.x + step, y: src.y + step, id: undefined }); + if (copy.rack || copy.device) { + copy.label = copy.label || (copy.object && copy.object.name) || ''; + copy.item_type = copy.rack ? 'rack' : 'device'; + copy.rack = null; copy.device = null; copy.object = null; + } + return copy; + }); + this.items.push(...added); + this.clipboard = JSON.parse(JSON.stringify(added)); + this.selection = new Set(added.map((i) => i.uid)); + this.render(); + this.renderPanel(); + } + + duplicate() { + this.copySelection(); + this.paste(); + } + + rotateSelection(deg) { + const items = this.selectedItems(); + if (!items.length) return; + this.checkpoint(); + for (const i of items) i.rotation = (((i.rotation || 0) + deg) % 360 + 360) % 360; + this.render(); + this.renderPanel(); + } + + reorder(direction) { + const items = this.selectedItems(); + if (!items.length) return; + this.checkpoint(); + const zs = this.items.map((i) => i.z_index || 0); + const target = direction > 0 ? Math.max(...zs) + 1 : Math.min(...zs) - 1; + for (const i of items) i.z_index = clamp(target, -32000, 32000); + this.render(); + this.renderPanel(); + } + + nudge(dx, dy) { + const items = this.selectedItems(); + if (!items.length) return; + this.checkpoint(); + for (const i of items) { i.x += dx; i.y += dy; } + this.render(); + this.renderPanel(); + } + + /* ----- geometry ----- */ + + toWorld(clientX, clientY) { + const r = this.svg.getBoundingClientRect(); + return { + x: (clientX - r.left - this.view.x) / this.view.scale, + y: (clientY - r.top - this.view.y) / this.view.scale, + }; + } + + bbox(i) { + const a = (i.rotation || 0) * Math.PI / 180; + const c = Math.abs(Math.cos(a)), s = Math.abs(Math.sin(a)); + const w = i.width * c + i.height * s, h = i.width * s + i.height * c; + const cx = i.x + i.width / 2, cy = i.y + i.height / 2; + return { x1: cx - w / 2, y1: cy - h / 2, x2: cx + w / 2, y2: cy + h / 2 }; + } + + applyView() { + this.viewport.setAttribute('transform', `translate(${this.view.x} ${this.view.y}) scale(${this.view.scale})`); + this.zoomLabel.textContent = Math.round(this.view.scale * 100 / this.baseScale()) + '%'; + this.renderOverlay(); + } + + baseScale() { + const r = this.svg.getBoundingClientRect(); + const m = 40; + return Math.max(0.01, Math.min((r.width - m) / this.settings.width, (r.height - m) / this.settings.depth)); + } + + fit() { + const r = this.svg.getBoundingClientRect(); + const s = this.baseScale(); + this.view = { scale: s, x: (r.width - this.settings.width * s) / 2, y: (r.height - this.settings.depth * s) / 2 }; + this.applyView(); + } + + zoomBy(factor, clientX, clientY) { + const r = this.svg.getBoundingClientRect(); + const cx = clientX === undefined ? r.left + r.width / 2 : clientX; + const cy = clientY === undefined ? r.top + r.height / 2 : clientY; + const before = this.toWorld(cx, cy); + const base = this.baseScale(); + this.view.scale = clamp(this.view.scale * factor, base * 0.1, base * 40); + this.view.x = cx - r.left - before.x * this.view.scale; + this.view.y = cy - r.top - before.y * this.view.scale; + this.applyView(); + } + + /* ----- rendering ----- */ + + cssVar(name, fallback) { + return getComputedStyle(this.root).getPropertyValue(name).trim() || fallback; + } + + renderFloor() { + const { width, depth, grid_size: g } = this.settings; + for (const r of [this.floor, this.gridRect, this.floorBorder]) { + r.setAttribute('width', width); + r.setAttribute('height', depth); + } + this.floor.setAttribute('fill', this.cssVar('--fp-floor', '#ffffff')); + this.floorBorder.setAttribute('stroke', this.cssVar('--fp-wall', '#334155')); + this.floorBorder.setAttribute('stroke-width', 4); + this.gridPattern.setAttribute('width', g); + this.gridPattern.setAttribute('height', g); + this.gridPath.setAttribute('d', `M ${g} 0 L 0 0 0 ${g}`); + this.gridPath.setAttribute('stroke', this.cssVar('--fp-grid', '#e2e8f0')); + this.gridRect.style.display = this.gridVisible ? '' : 'none'; + + const bg = this.cfg.background || {}; + if (bg.url) { + this.bgImage.setAttribute('href', bg.url); + this.bgImage.setAttribute('width', width); + this.bgImage.setAttribute('height', depth); + this.bgImage.setAttribute('opacity', bg.opacity); + } else { + this.bgImage.style.display = 'none'; + } + } + + itemColor(i) { + if (!this.edit && this.colorMode !== 'type' && i.object) { + if (this.colorMode === 'status') return COLOR_NAMES[i.object.status_color] || i.object.status_color || '#868e96'; + if (this.colorMode === 'role' && i.object.role_color) return i.object.role_color; + return '#868e96'; + } + return i.color || TYPES[i.item_type].color; + } + + itemText(i) { + return i.label || (i.object && i.object.name) || ''; + } + + matchesFilter(i) { + if (!this.filter) return true; + const o = i.object || {}; + return [this.itemText(i), o.role, o.tenant, o.status_label].some((v) => v && v.toLowerCase().includes(this.filter)); + } + + render() { + const layer = this.itemsLayer; + layer.innerHTML = ''; + const textColor = this.cssVar('--fp-text', '#0f172a'); + const sorted = this.items.map((i, idx) => [i, idx]).sort((a, b) => (a[0].z_index || 0) - (b[0].z_index || 0) || a[1] - b[1]); + for (const [i] of sorted) layer.appendChild(this.renderItem(i, textColor)); + this.renderOverlay(); + this.updateStatusBar(); + this.updateHistoryButtons(); + } + + renderItem(i, textColor) { + const { x, y, width: w, height: h } = i; + const cx = x + w / 2, cy = y + h / 2; + const color = this.itemColor(i); + const linked = !!(i.rack || i.device); + const g = svg('g', { + class: 'fp-item fp-type-' + i.item_type + (linked ? ' fp-linked' : '') + (this.matchesFilter(i) ? '' : ' fp-dimmed'), + 'data-uid': i.uid, + transform: i.rotation ? `rotate(${i.rotation} ${cx} ${cy})` : null, + }); + const base = { x: x, y: y, width: w, height: h, 'vector-effect': 'non-scaling-stroke' }; + + switch (i.item_type) { + case 'area': + svg('rect', Object.assign(base, { fill: color, 'fill-opacity': 0.12, stroke: color, 'stroke-width': 2, 'stroke-dasharray': '8 4', rx: 4 }), g); + break; + case 'wall': + svg('rect', Object.assign(base, { fill: color, stroke: color, 'stroke-width': 1 }), g); + break; + case 'door': { + svg('rect', Object.assign(base, { fill: color, stroke: color, 'stroke-width': 1 }), g); + const r = w; + svg('path', { + d: `M ${x + w} ${y} A ${r} ${r} 0 0 0 ${x} ${y - r} L ${x} ${y}`, + fill: color, 'fill-opacity': 0.08, stroke: color, 'stroke-width': 1, 'stroke-dasharray': '4 3', + 'vector-effect': 'non-scaling-stroke', + }, g); + break; + } + case 'window': + svg('rect', Object.assign(base, { fill: this.cssVar('--fp-floor', '#fff'), stroke: color, 'stroke-width': 2 }), g); + svg('line', { x1: x, y1: cy, x2: x + w, y2: cy, stroke: color, 'stroke-width': 1, 'vector-effect': 'non-scaling-stroke' }, g); + break; + case 'column': + svg('rect', Object.assign(base, { fill: color, 'fill-opacity': 0.35, stroke: color, 'stroke-width': 2 }), g); + svg('path', { d: `M ${x} ${y} L ${x + w} ${y + h} M ${x + w} ${y} L ${x} ${y + h}`, stroke: color, 'stroke-width': 1, 'vector-effect': 'non-scaling-stroke' }, g); + break; + case 'label': + svg('rect', Object.assign(base, { fill: 'transparent', stroke: this.edit ? color : 'none', 'stroke-width': 1, 'stroke-dasharray': '3 3', 'stroke-opacity': 0.4 }), g); + break; + default: { + // rack, device, cooling, power + svg('rect', Object.assign(base, { fill: color, 'fill-opacity': 0.85, stroke: this.shade(color), 'stroke-width': 2, rx: 2 }), g); + if (i.item_type === 'rack') { + // Front indicator: thick bar on the front (bottom) side + const fh = Math.min(h * 0.12, 10); + svg('rect', { x: x, y: y + h - fh, width: w, height: fh, fill: this.shade(color), 'pointer-events': 'none' }, g); + } + if (i.item_type === 'cooling' || i.item_type === 'power') { + const sym = i.item_type === 'cooling' ? '❄' : '⚡'; + const fs = Math.min(w, h) * 0.45; + svg('text', { x: cx, y: y + fs * 0.9, 'font-size': fs, 'text-anchor': 'middle', fill: '#ffffff', 'pointer-events': 'none' }, g).textContent = sym; + } + } + } + + const text = this.itemText(i); + if (text) { + const onShape = ['rack', 'device', 'cooling', 'power'].includes(i.item_type); + const fs = i.item_type === 'label' + ? Math.max(8, h * 0.6) + : clamp(Math.min(h * 0.3, (w * 1.6) / Math.max(text.length, 3)), 6, 60); + const ty = i.item_type === 'area' ? y + fs * 1.2 : (i.item_type === 'cooling' || i.item_type === 'power') ? y + h - fs * 0.6 : cy; + const tx = i.item_type === 'area' ? x + fs * 0.5 : cx; + const tnode = svg('text', { + x: tx, y: ty, 'font-size': fs, 'font-family': 'Inter, system-ui, sans-serif', 'font-weight': 600, + 'text-anchor': i.item_type === 'area' ? 'start' : 'middle', 'dominant-baseline': 'middle', + fill: onShape ? '#ffffff' : (i.item_type === 'label' ? (i.color || textColor) : this.shade(color)), + 'pointer-events': 'none', + }, g); + tnode.textContent = text; + } + return g; + } + + shade(hex) { + // Darken a hex color by ~30 % for borders + const m = /^#?([0-9a-f]{6})$/i.exec(hex || ''); + if (!m) return hex; + const n = parseInt(m[1], 16); + const f = (v) => Math.round(v * 0.7).toString(16).padStart(2, '0'); + return '#' + f(n >> 16) + f((n >> 8) & 255) + f(n & 255); + } + + renderOverlay() { + const o = this.overlay; + o.innerHTML = ''; + const px = 1 / this.view.scale; + for (const gl of this.guides) { + svg('line', Object.assign({ class: 'fp-guide', 'stroke-width': px }, gl), o); + } + const items = this.selectedItems(); + for (const i of items) { + const cx = i.x + i.width / 2, cy = i.y + i.height / 2; + const g = svg('g', { transform: i.rotation ? `rotate(${i.rotation} ${cx} ${cy})` : null }, o); + svg('rect', { + class: 'fp-selection', x: i.x - 2 * px, y: i.y - 2 * px, width: i.width + 4 * px, height: i.height + 4 * px, + 'stroke-width': 1.5 * px, 'stroke-dasharray': `${4 * px} ${3 * px}`, + }, g); + if (this.edit && items.length === 1) { + const hs = 9 * px; + svg('line', { class: 'fp-rot-line', x1: cx, y1: i.y, x2: cx, y2: i.y - 24 * px, 'stroke-width': px }, g); + svg('circle', { class: 'fp-handle fp-rot', 'data-handle': 'rot', cx: cx, cy: i.y - 24 * px, r: hs * 0.6, 'stroke-width': px }, g); + for (const hx of [-1, 0, 1]) { + for (const hy of [-1, 0, 1]) { + if (!hx && !hy) continue; + svg('rect', { + class: 'fp-handle', 'data-handle': `${hx},${hy}`, + x: cx + hx * i.width / 2 - hs / 2, y: cy + hy * i.height / 2 - hs / 2, width: hs, height: hs, + 'stroke-width': px, style: `cursor:${this.resizeCursor(hx, hy, i.rotation)}`, + }, g); + } + } + } + } + if (this.drag && this.drag.kind === 'band') { + const b = this.drag; + svg('rect', { + class: 'fp-band', x: Math.min(b.x0, b.x1), y: Math.min(b.y0, b.y1), + width: Math.abs(b.x1 - b.x0), height: Math.abs(b.y1 - b.y0), 'stroke-width': px, + }, o); + } + if (this.highlightUid) { + const i = this.itemByUid(this.highlightUid); + if (i) { + const b = this.bbox(i); + svg('rect', { + class: 'fp-highlight', x: b.x1 - 10 * px, y: b.y1 - 10 * px, width: b.x2 - b.x1 + 20 * px, height: b.y2 - b.y1 + 20 * px, + rx: 6 * px, 'stroke-width': 3 * px, + }, o); + } + } + } + + resizeCursor(hx, hy, rot) { + const cursors = ['ew-resize', 'nwse-resize', 'ns-resize', 'nesw-resize']; + const angle = Math.atan2(hy, hx) * 180 / Math.PI + (rot || 0); + return cursors[((Math.round(angle / 45) % 4) + 4) % 4]; + } + + updateStatusBar() { + const help = this.edit + ? this.t('Drag: move · Alt: no snapping · Shift+click: multi-select · Space+drag / middle mouse: pan · Wheel: zoom · R: rotate · Del: delete · Ctrl+Z/Y: undo/redo · Ctrl+C/V/D: copy/paste/duplicate · Ctrl+S: save') + : this.t('Wheel: zoom · Drag: pan · Click a rack or device to open it'); + this.statusBar.textContent = (!this.edit && !this.items.length ? this.t('This floor plan is empty.') + ' · ' : '') + help; + } + + /* ----- properties panel ----- */ + + renderPanel() { + if (!this.edit) return; + const p = this.panelEl; + p.innerHTML = ''; + const items = this.selectedItems(); + p.append(html('div', { class: 'fp-palette-title', text: this.t('Properties') })); + + const field = (label, input) => html('label', { class: 'fp-field' }, [html('span', { text: label }), input]); + const num = (value, onchange, opts) => html('input', Object.assign({ + type: 'number', class: 'form-control form-control-sm', value: Math.round(value), + onchange: (e) => { const v = parseInt(e.target.value, 10); if (!isNaN(v)) onchange(v); }, + }, opts || {})); + + if (!items.length) { + p.append(html('div', { class: 'fp-muted', text: this.t('Nothing selected – plan settings') })); + const setSetting = (key, min) => (v) => { + this.checkpoint(); + this.settings[key] = Math.max(min, v); + this.renderFloor(); + this.render(); + }; + p.append( + field(this.t('Width (cm)'), num(this.settings.width, setSetting('width', 100), { min: 100, step: 10 })), + field(this.t('Depth (cm)'), num(this.settings.depth, setSetting('depth', 100), { min: 100, step: 10 })), + field(this.t('Grid size (cm)'), num(this.settings.grid_size, setSetting('grid_size', 5), { min: 5, step: 5 })), + ); + return; + } + + const update = (fn) => { this.checkpoint(); items.forEach(fn); this.render(); this.renderPanel(); }; + + if (items.length > 1) { + p.append(html('div', { class: 'fp-muted', text: this.t('{n} items selected', { n: items.length }) })); + p.append(field(this.t('Color'), html('input', { + type: 'color', class: 'form-control form-control-sm form-control-color', value: items[0].color || TYPES[items[0].item_type].color, + onchange: (e) => update((i) => { i.color = e.target.value; }), + }))); + p.append(field(this.t('Rotation (°)'), num(items[0].rotation || 0, (v) => update((i) => { i.rotation = ((v % 360) + 360) % 360; }), { step: 15 }))); + return; + } + + const i = items[0]; + const typeLabel = this.cfg.types[i.item_type] || i.item_type; + p.append(html('div', { class: 'fp-type-badge' }, [html('i', { class: 'mdi ' + TYPES[i.item_type].icon }), ' ' + typeLabel])); + + if (i.object) { + const o = i.object; + const rows = [ + [this.t('Linked object'), html('a', { href: o.url, target: '_blank', text: o.name })], + o.status_label ? [this.t('Status'), html('span', { class: 'badge text-bg-' + (o.status_color || 'secondary'), text: o.status_label })] : null, + o.role ? [this.t('Role'), o.role] : null, + o.tenant ? [this.t('Tenant'), o.tenant] : null, + o.u_height ? [this.t('Height (U)'), String(o.u_height)] : null, + ].filter(Boolean); + p.append(html('dl', { class: 'fp-info' }, rows.flatMap(([k, v]) => [html('dt', { text: k }), html('dd', {}, [v])]))); + } + + p.append( + field(this.t('Label'), html('input', { + type: 'text', class: 'form-control form-control-sm', value: i.label || '', maxlength: 100, + placeholder: (i.object && i.object.name) || '', + onchange: (e) => update((it) => { it.label = e.target.value; }), + })), + html('div', { class: 'fp-row' }, [ + field(this.t('X (cm)'), num(i.x, (v) => update((it) => { it.x = v; }))), + field(this.t('Y (cm)'), num(i.y, (v) => update((it) => { it.y = v; }))), + ]), + html('div', { class: 'fp-row' }, [ + field(this.t('Width (cm)'), num(i.width, (v) => update((it) => { it.width = Math.max(1, v); }), { min: 1 })), + field(this.t('Depth (cm)'), num(i.height, (v) => update((it) => { it.height = Math.max(1, v); }), { min: 1 })), + ]), + field(this.t('Rotation (°)'), num(i.rotation || 0, (v) => update((it) => { it.rotation = ((v % 360) + 360) % 360; }), { step: 15 })), + field(this.t('Color'), html('div', { class: 'fp-color' }, [ + html('input', { + type: 'color', class: 'form-control form-control-sm form-control-color', value: i.color || TYPES[i.item_type].color, + onchange: (e) => update((it) => { it.color = e.target.value; }), + }), + html('button', { + type: 'button', class: 'btn btn-sm btn-outline-secondary', title: this.t('Reset color'), + onclick: () => update((it) => { it.color = ''; }), + }, [html('i', { class: 'mdi mdi-restore' })]), + ])), + ); + } + + /* ----- events ----- */ + + bindEvents() { + const s = this.svg; + s.addEventListener('pointerdown', (e) => this.onPointerDown(e)); + s.addEventListener('pointermove', (e) => this.onPointerMove(e)); + s.addEventListener('pointerup', (e) => this.onPointerUp(e)); + s.addEventListener('pointercancel', (e) => this.onPointerUp(e)); + s.addEventListener('pointerleave', () => { this.tooltip.hidden = true; }); + s.addEventListener('wheel', (e) => { + e.preventDefault(); + if (e.ctrlKey || !e.shiftKey) { + this.zoomBy(Math.exp(-e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.0015)), e.clientX, e.clientY); + } else { + this.view.x -= e.deltaY; + this.applyView(); + } + }, { passive: false }); + s.addEventListener('dblclick', (e) => { + const g = e.target.closest('.fp-item'); + if (!g || !this.edit) return; + const i = this.itemByUid(+g.dataset.uid); + const input = this.panelEl.querySelector('input[type=text]'); + if (i && input) { input.focus(); input.select(); } + }); + + if (this.edit) { + s.addEventListener('dragover', (e) => { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }); + s.addEventListener('drop', (e) => { + e.preventDefault(); + const raw = e.dataTransfer.getData('application/x-floorplanner'); + if (!raw) return; + this.addFromPayload(JSON.parse(raw), this.toWorld(e.clientX, e.clientY)); + this.root.focus({ preventScroll: true }); + }); + window.addEventListener('beforeunload', (e) => { + if (this.dirty) { e.preventDefault(); e.returnValue = this.t('You have unsaved changes. Leave anyway?'); } + }); + } + + this.root.addEventListener('keydown', (e) => this.onKeyDown(e)); + this.root.addEventListener('keyup', (e) => { if (e.code === 'Space') { this.spaceDown = false; this.svg.classList.remove('fp-panning'); } }); + new ResizeObserver(() => this.applyView()).observe(this.canvasWrap); + // Re-color the floor when NetBox switches between light and dark mode + new MutationObserver(() => { this.renderFloor(); this.render(); }) + .observe(document.documentElement, { attributes: true, attributeFilter: ['data-bs-theme'] }); + } + + onKeyDown(e) { + if (e.target.closest('input, textarea, select')) return; + const ctrl = e.ctrlKey || e.metaKey; + const key = e.key.toLowerCase(); + if (e.code === 'Space') { this.spaceDown = true; this.svg.classList.add('fp-panning'); e.preventDefault(); return; } + if (key === '+' || key === '=') { this.zoomBy(1.25); e.preventDefault(); return; } + if (key === '-') { this.zoomBy(1 / 1.25); e.preventDefault(); return; } + if (key === '0') { this.fit(); e.preventDefault(); return; } + if (key === 'escape') { this.selection.clear(); this.render(); this.renderPanel(); return; } + if (!this.edit) return; + + if (ctrl && key === 's') { e.preventDefault(); this.save(); return; } + if (ctrl && key === 'z' && !e.shiftKey) { e.preventDefault(); this.undo(); return; } + if (ctrl && (key === 'y' || (key === 'z' && e.shiftKey))) { e.preventDefault(); this.redo(); return; } + if (ctrl && key === 'c') { e.preventDefault(); this.copySelection(); return; } + if (ctrl && key === 'v') { e.preventDefault(); this.paste(); return; } + if (ctrl && key === 'd') { e.preventDefault(); this.duplicate(); return; } + if (ctrl && key === 'a') { + e.preventDefault(); + this.selection = new Set(this.items.map((i) => i.uid)); + this.render(); this.renderPanel(); + return; + } + if (key === 'delete' || key === 'backspace') { e.preventDefault(); this.deleteSelection(); return; } + if (key === 'r' && !ctrl) { e.preventDefault(); this.rotateSelection(e.shiftKey ? -90 : 90); return; } + const arrows = { arrowleft: [-1, 0], arrowright: [1, 0], arrowup: [0, -1], arrowdown: [0, 1] }; + if (arrows[key] && this.selection.size) { + e.preventDefault(); + const step = e.shiftKey ? this.settings.grid_size : 1; + this.nudge(arrows[key][0] * step, arrows[key][1] * step); + } + } + + onPointerDown(e) { + this.root.focus({ preventScroll: true }); + const w = this.toWorld(e.clientX, e.clientY); + const handle = e.target.closest('[data-handle]'); + const itemEl = e.target.closest('.fp-item'); + const item = itemEl ? this.itemByUid(+itemEl.dataset.uid) : null; + this.highlightUid = null; + + if (e.button === 1 || this.spaceDown || (!this.edit && e.button === 0)) { + this.drag = { kind: 'pan', sx: e.clientX, sy: e.clientY, vx: this.view.x, vy: this.view.y, moved: false, item: item }; + } else if (e.button !== 0) { + return; + } else if (handle && this.edit) { + const i = this.selectedItems()[0]; + this.drag = { + kind: handle.dataset.handle === 'rot' ? 'rotate' : 'resize', + dirs: handle.dataset.handle.split(',').map(Number), + start: { x: i.x, y: i.y, w: i.width, h: i.height, r: i.rotation || 0 }, + item: i, changed: false, + }; + } else if (item) { + if (e.shiftKey) { + if (this.selection.has(item.uid)) this.selection.delete(item.uid); else this.selection.add(item.uid); + } else if (!this.selection.has(item.uid)) { + this.selection = new Set([item.uid]); + } + const origins = new Map(this.selectedItems().map((i) => [i.uid, { x: i.x, y: i.y }])); + this.drag = { kind: 'move', w0: w, origins: origins, primary: item, changed: false }; + this.render(); + this.renderPanel(); + } else { + if (!e.shiftKey) this.selection.clear(); + this.drag = { kind: 'band', x0: w.x, y0: w.y, x1: w.x, y1: w.y, additive: new Set(this.selection) }; + this.render(); + this.renderPanel(); + } + this.svg.setPointerCapture(e.pointerId); + } + + onPointerMove(e) { + const d = this.drag; + if (!d) { + this.updateTooltip(e); + return; + } + const w = this.toWorld(e.clientX, e.clientY); + + if (d.kind === 'pan') { + const dx = e.clientX - d.sx, dy = e.clientY - d.sy; + if (Math.abs(dx) + Math.abs(dy) > 3) d.moved = true; + this.view.x = d.vx + dx; + this.view.y = d.vy + dy; + this.applyView(); + return; + } + + if (d.kind === 'band') { + d.x1 = w.x; d.y1 = w.y; + const x1 = Math.min(d.x0, d.x1), x2 = Math.max(d.x0, d.x1), y1 = Math.min(d.y0, d.y1), y2 = Math.max(d.y0, d.y1); + this.selection = new Set(d.additive); + for (const i of this.items) { + const b = this.bbox(i); + if (b.x1 < x2 && b.x2 > x1 && b.y1 < y2 && b.y2 > y1) this.selection.add(i.uid); + } + this.renderOverlay(); + return; + } + + if (!d.changed) { this.checkpoint(); d.changed = true; } + + if (d.kind === 'move') { + let dx = w.x - d.w0.x, dy = w.y - d.w0.y; + const p0 = d.origins.get(d.primary.uid); + const step = this.gridStep(e); + dx = snap(p0.x + dx, step) - p0.x; + dy = snap(p0.y + dy, step) - p0.y; + // Magnetic snapping against the edges of other items + this.guides = []; + if (this.snapEnabled && !e.altKey) { + const adj = this.magnet(dx, dy, d.origins); + dx = adj.dx; dy = adj.dy; + } + for (const i of this.selectedItems()) { + const o = d.origins.get(i.uid); + i.x = o.x + dx; i.y = o.y + dy; + } + this.render(); + return; + } + + const i = d.item, s = d.start; + if (d.kind === 'rotate') { + const cx = s.x + s.w / 2, cy = s.y + s.h / 2; + let angle = Math.atan2(w.y - cy, w.x - cx) * 180 / Math.PI + 90; + angle = snap(angle, this.snapEnabled && !e.altKey ? 15 : 1); + i.rotation = ((Math.round(angle) % 360) + 360) % 360; + this.render(); + return; + } + + if (d.kind === 'resize') { + const [hx, hy] = d.dirs; + const a = s.r * Math.PI / 180, cos = Math.cos(a), sin = Math.sin(a); + const cx0 = s.x + s.w / 2, cy0 = s.y + s.h / 2; + const px = w.x - cx0, py = w.y - cy0; + const lx = px * cos + py * sin, ly = -px * sin + py * cos; + const step = this.sizeStep(e); + let left = -s.w / 2, right = s.w / 2, top = -s.h / 2, bottom = s.h / 2; + if (hx === 1) right = left + Math.max(MIN_SIZE, snap(lx - left, step)); + if (hx === -1) left = right - Math.max(MIN_SIZE, snap(right - lx, step)); + if (hy === 1) bottom = top + Math.max(MIN_SIZE, snap(ly - top, step)); + if (hy === -1) top = bottom - Math.max(MIN_SIZE, snap(bottom - ly, step)); + const nw = right - left, nh = bottom - top; + const lcx = (left + right) / 2, lcy = (top + bottom) / 2; + const wcx = cx0 + lcx * cos - lcy * sin, wcy = cy0 + lcx * sin + lcy * cos; + i.width = Math.round(nw); i.height = Math.round(nh); + i.x = Math.round(wcx - nw / 2); i.y = Math.round(wcy - nh / 2); + this.render(); + } + } + + magnet(dx, dy, origins) { + const threshold = 8 / this.view.scale; + const moving = this.selectedItems().map((i) => { + const o = origins.get(i.uid); + return this.bbox(Object.assign({}, i, { x: o.x + dx, y: o.y + dy })); + }); + const mb = { + x1: Math.min(...moving.map((b) => b.x1)), x2: Math.max(...moving.map((b) => b.x2)), + y1: Math.min(...moving.map((b) => b.y1)), y2: Math.max(...moving.map((b) => b.y2)), + }; + const others = this.items.filter((i) => !this.selection.has(i.uid) && i.item_type !== 'area').map((i) => this.bbox(i)); + others.push({ x1: 0, y1: 0, x2: this.settings.width, y2: this.settings.depth }); + let bestX = null, bestY = null; + for (const b of others) { + for (const [m, t] of [[mb.x1, b.x1], [mb.x1, b.x2], [mb.x2, b.x1], [mb.x2, b.x2]]) { + const diff = t - m; + if (Math.abs(diff) < threshold && (bestX === null || Math.abs(diff) < Math.abs(bestX.diff))) bestX = { diff: diff, at: t }; + } + for (const [m, t] of [[mb.y1, b.y1], [mb.y1, b.y2], [mb.y2, b.y1], [mb.y2, b.y2]]) { + const diff = t - m; + if (Math.abs(diff) < threshold && (bestY === null || Math.abs(diff) < Math.abs(bestY.diff))) bestY = { diff: diff, at: t }; + } + } + if (bestX) { + dx += bestX.diff; + this.guides.push({ x1: bestX.at, x2: bestX.at, y1: -100000, y2: 100000 }); + } + if (bestY) { + dy += bestY.diff; + this.guides.push({ y1: bestY.at, y2: bestY.at, x1: -100000, x2: 100000 }); + } + return { dx: Math.round(dx), dy: Math.round(dy) }; + } + + onPointerUp(e) { + const d = this.drag; + this.drag = null; + this.guides = []; + if (this.svg.hasPointerCapture(e.pointerId)) this.svg.releasePointerCapture(e.pointerId); + if (!d) return; + if (d.kind === 'pan' && !d.moved && !this.edit) { + // Click in view mode: open the linked object + if (d.item && d.item.object && d.item.object.url) { + if (e.ctrlKey || e.metaKey || e.button === 1) window.open(d.item.object.url, '_blank'); + else window.location.href = d.item.object.url; + } + return; + } + this.render(); + if (d.kind !== 'pan') this.renderPanel(); + } + + updateTooltip(e) { + const itemEl = e.target.closest && e.target.closest('.fp-item'); + const i = itemEl ? this.itemByUid(+itemEl.dataset.uid) : null; + if (!i || (this.edit && !i.object)) { this.tooltip.hidden = true; return; } + const o = i.object || {}; + const rows = [ + html('strong', { text: this.itemText(i) || this.cfg.types[i.item_type] }), + html('div', { class: 'fp-muted', text: this.cfg.types[i.item_type] + ` · ${i.width} × ${i.height} cm` }), + ]; + if (o.status_label) rows.push(html('div', {}, [this.t('Status') + ': ', html('span', { class: 'badge text-bg-' + (o.status_color || 'secondary'), text: o.status_label })])); + if (o.role) rows.push(html('div', { text: this.t('Role') + ': ' + o.role })); + if (o.tenant) rows.push(html('div', { text: this.t('Tenant') + ': ' + o.tenant })); + if (o.u_height) rows.push(html('div', { text: this.t('Height (U)') + ': ' + o.u_height })); + if (o.device_count !== undefined && o.device_count !== null) rows.push(html('div', { text: this.t('Devices in rack') + ': ' + o.device_count })); + this.tooltip.replaceChildren(...rows); + const r = this.canvasWrap.getBoundingClientRect(); + this.tooltip.hidden = false; + const tx = Math.min(e.clientX - r.left + 14, r.width - this.tooltip.offsetWidth - 8); + const ty = Math.min(e.clientY - r.top + 14, r.height - this.tooltip.offsetHeight - 8); + this.tooltip.style.left = Math.max(4, tx) + 'px'; + this.tooltip.style.top = Math.max(4, ty) + 'px'; + } + + focusHighlight(key) { + const [kind, id] = key.split('-'); + const i = this.items.find((it) => it[kind] === +id); + if (!i) return; + this.highlightUid = i.uid; + const r = this.svg.getBoundingClientRect(); + const b = this.bbox(i); + this.view.scale = this.baseScale() * 2.5; + this.view.x = r.width / 2 - ((b.x1 + b.x2) / 2) * this.view.scale; + this.view.y = r.height / 2 - ((b.y1 + b.y2) / 2) * this.view.scale; + this.applyView(); + } + + /* ----- export / fullscreen ----- */ + + async exportClone() { + const clone = this.svg.cloneNode(true); + const m = 20; + clone.setAttribute('viewBox', `${-m} ${-m} ${this.settings.width + 2 * m} ${this.settings.depth + 2 * m}`); + clone.setAttribute('width', this.settings.width + 2 * m); + clone.setAttribute('height', this.settings.depth + 2 * m); + clone.querySelector('.fp-viewport').removeAttribute('transform'); + clone.querySelector('.fp-overlay').remove(); + if (!this.gridVisible) clone.querySelector(`rect[fill="url(#${this.gridId})"]`).remove(); + clone.querySelectorAll('.fp-dimmed').forEach((n) => n.setAttribute('opacity', 0.2)); + const img = clone.querySelector('image'); + if (img && this.cfg.background && this.cfg.background.url) { + try { + const resp = await fetch(this.cfg.background.url, { credentials: 'same-origin' }); + img.setAttribute('href', await blobToDataUrl(await resp.blob())); + } catch (e) { + img.remove(); + } + } else if (img) { + img.remove(); + } + return clone; + } + + filename(ext) { + return (this.cfg.name || 'floorplan').replace(/[^\w.-]+/g, '_') + '.' + ext; + } + + async exportSvg() { + const clone = await this.exportClone(); + download(this.filename('svg'), new Blob([new XMLSerializer().serializeToString(clone)], { type: 'image/svg+xml' })); + } + + async exportPng() { + const clone = await this.exportClone(); + const w = +clone.getAttribute('width'), h = +clone.getAttribute('height'); + const scale = clamp(4000 / Math.max(w, h), 0.5, 4); + const url = URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(clone)], { type: 'image/svg+xml' })); + const img = new Image(); + img.onload = () => { + const canvas = html('canvas', { width: Math.round(w * scale), height: Math.round(h * scale) }); + const ctx = canvas.getContext('2d'); + ctx.fillStyle = this.cssVar('--fp-bg', '#ffffff'); + ctx.fillRect(0, 0, canvas.width, canvas.height); + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + URL.revokeObjectURL(url); + canvas.toBlob((blob) => download(this.filename('png'), blob), 'image/png'); + }; + img.src = url; + } + + toggleFullscreen() { + if (document.fullscreenElement) document.exitFullscreen(); + else this.root.requestFullscreen && this.root.requestFullscreen(); + } + } + + function init() { + document.querySelectorAll('.fp-root[data-fp-config]').forEach((root) => { + if (root.dataset.fpReady) return; + const cfgEl = document.getElementById(root.dataset.fpConfig); + if (!cfgEl) return; + root.dataset.fpReady = '1'; + root.floorplanner = new Designer(root, JSON.parse(cfgEl.textContent)); + }); + } + + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init); + else init(); +})(); diff --git a/netbox_floorplanner/strings.py b/netbox_floorplanner/strings.py new file mode 100644 index 0000000..6fad4dd --- /dev/null +++ b/netbox_floorplanner/strings.py @@ -0,0 +1,81 @@ +""" +User-facing strings of the JavaScript designer. The English text is the msgid, +so the designer falls back to English if a translation is missing. +""" +from django.utils.translation import gettext, gettext_noop + +JS_STRINGS = ( + gettext_noop('Save'), + gettext_noop('Saving…'), + gettext_noop('Saved'), + gettext_noop('Unsaved changes'), + gettext_noop('Save failed'), + gettext_noop('You have unsaved changes. Leave anyway?'), + gettext_noop('Undo'), + gettext_noop('Redo'), + gettext_noop('Delete'), + gettext_noop('Duplicate'), + gettext_noop('Rotate 90°'), + gettext_noop('Bring to front'), + gettext_noop('Send to back'), + gettext_noop('Zoom in'), + gettext_noop('Zoom out'), + gettext_noop('Fit to screen'), + gettext_noop('Snap to grid'), + gettext_noop('Show grid'), + gettext_noop('Fullscreen'), + gettext_noop('Export SVG'), + gettext_noop('Export PNG'), + gettext_noop('Shapes'), + gettext_noop('Racks'), + gettext_noop('Devices'), + gettext_noop('Search…'), + gettext_noop('Loading…'), + gettext_noop('No racks found'), + gettext_noop('No devices found'), + gettext_noop('Already placed'), + gettext_noop('Drag onto the plan or click to add'), + gettext_noop('Properties'), + gettext_noop('Floor plan'), + gettext_noop('Nothing selected – plan settings'), + gettext_noop('{n} items selected'), + gettext_noop('Type'), + gettext_noop('Label'), + gettext_noop('X (cm)'), + gettext_noop('Y (cm)'), + gettext_noop('Width (cm)'), + gettext_noop('Depth (cm)'), + gettext_noop('Height (cm)'), + gettext_noop('Rotation (°)'), + gettext_noop('Color'), + gettext_noop('Reset color'), + gettext_noop('Linked object'), + gettext_noop('Open object'), + gettext_noop('Grid size (cm)'), + gettext_noop('Status'), + gettext_noop('Role'), + gettext_noop('Tenant'), + gettext_noop('Height (U)'), + gettext_noop('Devices in rack'), + gettext_noop('Color by'), + gettext_noop('Item type'), + gettext_noop('Highlight…'), + gettext_noop('Rack'), + gettext_noop('Device'), + gettext_noop('Wall'), + gettext_noop('Door'), + gettext_noop('Window'), + gettext_noop('Area'), + gettext_noop('Column'), + gettext_noop('Cooling unit'), + gettext_noop('Power / UPS'), + gettext_noop('Label'), + gettext_noop('Keyboard shortcuts'), + gettext_noop('Drag: move · Alt: no snapping · Shift+click: multi-select · Space+drag / middle mouse: pan · Wheel: zoom · R: rotate · Del: delete · Ctrl+Z/Y: undo/redo · Ctrl+C/V/D: copy/paste/duplicate · Ctrl+S: save'), + gettext_noop('Wheel: zoom · Drag: pan · Click a rack or device to open it'), + gettext_noop('This floor plan is empty.'), +) + + +def get_js_strings(): + return {s: gettext(s) for s in JS_STRINGS} diff --git a/netbox_floorplanner/tables.py b/netbox_floorplanner/tables.py new file mode 100644 index 0000000..74cdf85 --- /dev/null +++ b/netbox_floorplanner/tables.py @@ -0,0 +1,26 @@ +import django_tables2 as tables +from django.utils.translation import gettext_lazy as _ +from netbox.tables import NetBoxTable, columns + +from .models import FloorPlan + +__all__ = ('FloorPlanTable',) + + +class FloorPlanTable(NetBoxTable): + name = tables.Column(verbose_name=_('Name'), linkify=True) + site = tables.Column(verbose_name=_('Site'), linkify=True) + location = tables.Column(verbose_name=_('Location'), linkify=True) + width = tables.Column(verbose_name=_('Width (cm)')) + depth = tables.Column(verbose_name=_('Depth (cm)')) + item_count = tables.Column(verbose_name=_('Items')) + rack_count = tables.Column(verbose_name=_('Racks')) + tags = columns.TagColumn(url_name='plugins:netbox_floorplanner:floorplan_list') + + class Meta(NetBoxTable.Meta): + model = FloorPlan + fields = ( + 'pk', 'id', 'name', 'site', 'location', 'width', 'depth', 'grid_size', 'item_count', 'rack_count', + 'description', 'tags', 'created', 'last_updated', + ) + default_columns = ('name', 'site', 'location', 'width', 'depth', 'rack_count', 'description') diff --git a/netbox_floorplanner/template_content.py b/netbox_floorplanner/template_content.py new file mode 100644 index 0000000..05b09fe --- /dev/null +++ b/netbox_floorplanner/template_content.py @@ -0,0 +1,22 @@ +from netbox.plugins import PluginTemplateExtension + +from .models import FloorPlanItem + + +class RackFloorPlanButton(PluginTemplateExtension): + """Adds a "Show on floor plan" button to racks and devices that are placed on a plan.""" + models = ['dcim.rack', 'dcim.device'] + + def buttons(self): + obj = self.context['object'] + field = 'rack' if obj._meta.model_name == 'rack' else 'device' + item = FloorPlanItem.objects.filter(**{field: obj}).select_related('floorplan').first() + if item is None: + return '' + return self.render('netbox_floorplanner/inc/floorplan_button.html', extra_context={ + 'floorplan': item.floorplan, + 'highlight': f'{field}-{obj.pk}', + }) + + +template_extensions = [RackFloorPlanButton] diff --git a/netbox_floorplanner/templates/netbox_floorplanner/floorplan.html b/netbox_floorplanner/templates/netbox_floorplanner/floorplan.html new file mode 100644 index 0000000..d67c76d --- /dev/null +++ b/netbox_floorplanner/templates/netbox_floorplanner/floorplan.html @@ -0,0 +1,65 @@ +{% extends 'generic/object.html' %} +{% load helpers %} +{% load i18n %} + +{% block extra_controls %} + {% if perms.netbox_floorplanner.change_floorplan %} + + {% trans "Open designer" %} + + {% endif %} +{% endblock %} + +{% block content %} +
+
+ {% include 'netbox_floorplanner/inc/designer.html' %} +
+
+
+
+
+

{% trans "Floor plan" %}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{% trans "Name" %}{{ object.name }}
{% trans "Site" %}{{ object.site|linkify }}
{% trans "Location" %}{{ object.location|linkify|placeholder }}
{% trans "Dimensions" %}{{ object.width }} × {{ object.depth }} cm
{% trans "Grid size" %}{{ object.grid_size }} cm
{% trans "Items" %}{{ object.item_count }}
{% trans "Racks" %}{{ object.rack_count }}
{% trans "Description" %}{{ object.description|placeholder }}
+
+ {% include 'inc/panels/tags.html' %} +
+
+ {% include 'inc/panels/custom_fields.html' %} + {% include 'inc/panels/comments.html' %} +
+
+{% endblock %} diff --git a/netbox_floorplanner/templates/netbox_floorplanner/floorplan_designer.html b/netbox_floorplanner/templates/netbox_floorplanner/floorplan_designer.html new file mode 100644 index 0000000..04cda18 --- /dev/null +++ b/netbox_floorplanner/templates/netbox_floorplanner/floorplan_designer.html @@ -0,0 +1,5 @@ +{% extends 'generic/object.html' %} + +{% block content %} + {% include 'netbox_floorplanner/inc/designer.html' %} +{% endblock %} diff --git a/netbox_floorplanner/templates/netbox_floorplanner/inc/designer.html b/netbox_floorplanner/templates/netbox_floorplanner/inc/designer.html new file mode 100644 index 0000000..cbdbdb6 --- /dev/null +++ b/netbox_floorplanner/templates/netbox_floorplanner/inc/designer.html @@ -0,0 +1,5 @@ +{% load static %} + +
+{{ designer_config|json_script:"fp-config" }} + diff --git a/netbox_floorplanner/templates/netbox_floorplanner/inc/floorplan_button.html b/netbox_floorplanner/templates/netbox_floorplanner/inc/floorplan_button.html new file mode 100644 index 0000000..c066b8f --- /dev/null +++ b/netbox_floorplanner/templates/netbox_floorplanner/inc/floorplan_button.html @@ -0,0 +1,4 @@ +{% load i18n %} + + {% trans "Show on floor plan" %} + diff --git a/netbox_floorplanner/templates/netbox_floorplanner/object_floorplans.html b/netbox_floorplanner/templates/netbox_floorplanner/object_floorplans.html new file mode 100644 index 0000000..a1cbc2f --- /dev/null +++ b/netbox_floorplanner/templates/netbox_floorplanner/object_floorplans.html @@ -0,0 +1,10 @@ +{% extends 'generic/object_children.html' %} +{% load i18n %} + +{% block extra_controls %} + {% if perms.netbox_floorplanner.add_floorplan %} + + {% trans "Add floor plan" %} + + {% endif %} +{% endblock %} diff --git a/netbox_floorplanner/urls.py b/netbox_floorplanner/urls.py new file mode 100644 index 0000000..9f01c61 --- /dev/null +++ b/netbox_floorplanner/urls.py @@ -0,0 +1,9 @@ +from django.urls import include, path +from utilities.urls import get_model_urls + +from . import views # noqa: F401 – registers the model views + +urlpatterns = ( + path('floorplans/', include(get_model_urls('netbox_floorplanner', 'floorplan', detail=False))), + path('floorplans//', include(get_model_urls('netbox_floorplanner', 'floorplan'))), +) diff --git a/netbox_floorplanner/views.py b/netbox_floorplanner/views.py new file mode 100644 index 0000000..cf8540f --- /dev/null +++ b/netbox_floorplanner/views.py @@ -0,0 +1,164 @@ +from dcim.models import Location, Site +from django.db.models import Count, Q +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ +from netbox.plugins import get_plugin_config +from netbox.views import generic +from utilities.permissions import get_permission_for_model +from utilities.views import ViewTab, register_model_view + +from . import filtersets, forms, tables +from .choices import ItemTypeChoices +from .models import FloorPlan +from .strings import get_js_strings + + +def floorplans_queryset(): + return FloorPlan.objects.select_related('site', 'location').annotate( + item_count=Count('items', distinct=True), + rack_count=Count('items', filter=Q(items__rack__isnull=False), distinct=True), + ) + + +def designer_config(request, floorplan, mode): + """Configuration handed to the JavaScript designer via json_script.""" + rack_filter = f'site_id={floorplan.site_id}' + if floorplan.location_id: + rack_filter += f'&location_id={floorplan.location_id}' + return { + 'mode': mode, + 'id': floorplan.pk, + 'name': floorplan.name, + 'settings': { + 'width': floorplan.width, + 'depth': floorplan.depth, + 'grid_size': floorplan.grid_size, + }, + 'background': { + 'url': floorplan.background_image.url if floorplan.background_image else None, + 'opacity': floorplan.background_opacity / 100, + }, + 'api': { + 'layout': reverse('plugins-api:netbox_floorplanner-api:floorplan-layout', args=[floorplan.pk]), + 'racks': reverse('dcim-api:rack-list') + f'?{rack_filter}&limit=1000&ordering=name', + 'devices': reverse('dcim-api:device-list') + f'?{rack_filter}&rack_id=null&limit=1000&ordering=name', + }, + 'highlight': request.GET.get('highlight', ''), + 'defaults': { + 'rack_width': get_plugin_config('netbox_floorplanner', 'default_rack_width'), + 'rack_depth': get_plugin_config('netbox_floorplanner', 'default_rack_depth'), + }, + 'types': {choice[0]: str(choice[1]) for choice in ItemTypeChoices.CHOICES}, + 'strings': get_js_strings(), + } + + +@register_model_view(FloorPlan, 'list', path='', detail=False) +class FloorPlanListView(generic.ObjectListView): + queryset = floorplans_queryset() + table = tables.FloorPlanTable + filterset = filtersets.FloorPlanFilterSet + filterset_form = forms.FloorPlanFilterForm + + +@register_model_view(FloorPlan) +class FloorPlanView(generic.ObjectView): + queryset = floorplans_queryset() + + def get_extra_context(self, request, instance): + return {'designer_config': designer_config(request, instance, 'view')} + + +@register_model_view(FloorPlan, 'designer', path='designer') +class FloorPlanDesignerView(generic.ObjectView): + queryset = FloorPlan.objects.select_related('site', 'location') + template_name = 'netbox_floorplanner/floorplan_designer.html' + tab = ViewTab( + label=_('Designer'), + permission='netbox_floorplanner.change_floorplan', + weight=100, + ) + + def get_required_permission(self): + return get_permission_for_model(FloorPlan, 'change') + + def get_extra_context(self, request, instance): + return {'designer_config': designer_config(request, instance, 'edit')} + + +@register_model_view(FloorPlan, 'add', detail=False) +@register_model_view(FloorPlan, 'edit') +class FloorPlanEditView(generic.ObjectEditView): + queryset = FloorPlan.objects.all() + form = forms.FloorPlanForm + + def alter_object(self, obj, request, url_args, url_kwargs): + # Allow pre-filling site/location from the Site or Location tab + if not obj.pk: + if site_id := request.GET.get('site'): + obj.site_id = site_id + if location_id := request.GET.get('location'): + obj.location_id = location_id + return obj + + +@register_model_view(FloorPlan, 'delete') +class FloorPlanDeleteView(generic.ObjectDeleteView): + queryset = FloorPlan.objects.all() + + +@register_model_view(FloorPlan, 'bulk_import', path='import', detail=False) +class FloorPlanBulkImportView(generic.BulkImportView): + queryset = FloorPlan.objects.all() + model_form = forms.FloorPlanImportForm + + +@register_model_view(FloorPlan, 'bulk_delete', path='delete', detail=False) +class FloorPlanBulkDeleteView(generic.BulkDeleteView): + queryset = floorplans_queryset() + filterset = filtersets.FloorPlanFilterSet + table = tables.FloorPlanTable + + +# +# "Floor plans" tabs on Site and Location +# + +class BaseFloorPlanChildrenView(generic.ObjectChildrenView): + child_model = FloorPlan + table = tables.FloorPlanTable + filterset = filtersets.FloorPlanFilterSet + template_name = 'netbox_floorplanner/object_floorplans.html' + filter_field = None + + def get_children(self, request, parent): + return floorplans_queryset().restrict(request.user, 'view').filter(**{self.filter_field: parent}) + + def get_extra_context(self, request, instance): + return {'add_params': f'{self.filter_field}={instance.pk}' + ( + f'&site={instance.site_id}' if self.filter_field == 'location' else '' + )} + + +@register_model_view(Site, 'floorplans', path='floorplans') +class SiteFloorPlansView(BaseFloorPlanChildrenView): + queryset = Site.objects.all() + filter_field = 'site' + tab = ViewTab( + label=_('Floor Plans'), + badge=lambda obj: obj.floorplans.count(), + permission='netbox_floorplanner.view_floorplan', + weight=1500, + ) + + +@register_model_view(Location, 'floorplans', path='floorplans') +class LocationFloorPlansView(BaseFloorPlanChildrenView): + queryset = Location.objects.all() + filter_field = 'location' + tab = ViewTab( + label=_('Floor Plans'), + badge=lambda obj: obj.floorplans.count(), + permission='netbox_floorplanner.view_floorplan', + weight=1500, + ) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..c546e0b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,26 @@ +[build-system] +requires = ["setuptools>=69", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "netbox-floorplanner" +version = "0.1.0" +description = "Modern drag & drop floor plan designer for NetBox 4.7+" +readme = "README.md" +license = "Apache-2.0" +requires-python = ">=3.12" +authors = [{ name = "Louis" }] +classifiers = [ + "Framework :: Django", + "Programming Language :: Python :: 3", +] + +[tool.setuptools.packages.find] +include = ["netbox_floorplanner*"] + +[tool.setuptools.package-data] +netbox_floorplanner = [ + "templates/**/*", + "static/**/*", + "locale/**/*", +]