diff --git a/README.md b/README.md index 7a09544..bf7ae71 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ Before updating, back up the database and try the update on a staging instance f ## 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. +- **To-scale plans:** enter the room size in meters, e.g. `4 x 3` or `12,5 x 8`, or exactly in centimeters. Both are available in the form and in the designer, and the plan shows its dimensions in meters along the walls. 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. @@ -129,7 +129,7 @@ Example layout payload: ## 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. +- **Coordinates are stored in centimetres.** The room size in meters is only an input and display format, converted to whole 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. diff --git a/netbox_floorplanner/forms.py b/netbox_floorplanner/forms.py index ceae7a3..9dce80e 100644 --- a/netbox_floorplanner/forms.py +++ b/netbox_floorplanner/forms.py @@ -9,6 +9,7 @@ from utilities.forms.fields import ( from utilities.forms.rendering import FieldSet from .models import FloorPlan +from .utils import format_room_size, parse_room_size __all__ = ('FloorPlanForm', 'FloorPlanFilterForm', 'FloorPlanImportForm') @@ -21,11 +22,16 @@ class FloorPlanForm(NetBoxModelForm): required=False, query_params={'site_id': '$site'}, ) + room_size = forms.CharField( + label=_('Room size (m)'), + required=False, + help_text=_('Width x depth in meters, e.g. "4 x 3" or "12,5 x 8". Takes precedence over the centimeter values.'), + ) comments = CommentField() fieldsets = ( FieldSet('name', 'site', 'location', 'description', 'tags', name=_('Floor plan')), - FieldSet('width', 'depth', 'grid_size', name=_('Dimensions (cm)')), + FieldSet('room_size', 'width', 'depth', 'grid_size', name=_('Dimensions')), FieldSet('background_image', 'background_opacity', name=_('Background')), ) @@ -45,6 +51,20 @@ class FloorPlanForm(NetBoxModelForm): 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) + width = self.instance.width if self.instance.pk else self.fields['width'].initial + depth = self.instance.depth if self.instance.pk else self.fields['depth'].initial + self.fields['room_size'].initial = format_room_size(width, depth) + + def clean(self): + super().clean() + # Only apply the meter value if the user actually edited it, so the + # centimeter fields can still be used on their own. + if 'room_size' in self.changed_data and self.cleaned_data.get('room_size'): + size = parse_room_size(self.cleaned_data['room_size']) + if size is None: + raise forms.ValidationError({'room_size': _('Enter the size as "width x depth" in meters, e.g. "4 x 3".')}) + self.cleaned_data['width'], self.cleaned_data['depth'] = size + return self.cleaned_data class FloorPlanFilterForm(NetBoxModelFilterSetForm): diff --git a/netbox_floorplanner/locale/de/LC_MESSAGES/django.mo b/netbox_floorplanner/locale/de/LC_MESSAGES/django.mo index dca770e..1babd87 100644 Binary files a/netbox_floorplanner/locale/de/LC_MESSAGES/django.mo 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 index c310aa2..0bd6119 100644 --- a/netbox_floorplanner/locale/de/LC_MESSAGES/django.po +++ b/netbox_floorplanner/locale/de/LC_MESSAGES/django.po @@ -171,8 +171,23 @@ msgstr "Raum" msgid "Floor plan" msgstr "Grundriss" -msgid "Dimensions (cm)" -msgstr "Abmessungen (cm)" +msgid "Room size (m)" +msgstr "Raumgröße (m)" + +msgid "Width x depth in meters, e.g. \"4 x 3\" or \"12,5 x 8\". Takes precedence over the centimeter values." +msgstr "Breite x Tiefe in Metern, z. B. „4 x 3“ oder „12,5 x 8“. Hat Vorrang vor den Zentimeterwerten." + +msgid "Enter the size as \"width x depth\" in meters, e.g. \"4 x 3\"." +msgstr "Bitte die Größe als „Breite x Tiefe“ in Metern angeben, z. B. „4 x 3“." + +msgid "e.g. 4 x 3" +msgstr "z. B. 4 x 3" + +msgid "Width x depth in meters, e.g. 4 x 3" +msgstr "Breite x Tiefe in Metern, z. B. 4 x 3" + +msgid "Floor area" +msgstr "Grundfläche" msgid "Background" msgstr "Hintergrund" diff --git a/netbox_floorplanner/static/netbox_floorplanner/floorplanner.js b/netbox_floorplanner/static/netbox_floorplanner/floorplanner.js index 43ba4d0..8ed7181 100644 --- a/netbox_floorplanner/static/netbox_floorplanner/floorplanner.js +++ b/netbox_floorplanner/static/netbox_floorplanner/floorplanner.js @@ -76,6 +76,17 @@ return Math.round(u === 'in' ? value * 2.54 : value / 10); } + const meterFormat = new Intl.NumberFormat(document.documentElement.lang || undefined, { maximumFractionDigits: 2 }); + const meters = (cm) => meterFormat.format(cm / 100); + const roomSize = (w, d) => `${meters(w)} x ${meters(d)}`; + + // "4x3", "4 x 3 m", "12,5 × 8" -> [width_cm, depth_cm]; mirrors utils.parse_room_size() + function parseRoomSize(value) { + const m = /^\s*(\d+(?:[.,]\d+)?)\s*m?\s*[x×*]\s*(\d+(?:[.,]\d+)?)\s*m?\s*$/i.exec(value || ''); + if (!m) return null; + return [m[1], m[2]].map((v) => Math.round(parseFloat(v.replace(',', '.')) * 100)); + } + function download(filename, blob) { const a = html('a', { href: URL.createObjectURL(blob), download: filename }); document.body.appendChild(a); @@ -162,6 +173,8 @@ 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.dimTop = svg('text', { 'text-anchor': 'middle', 'pointer-events': 'none', 'font-family': 'Inter, system-ui, sans-serif' }, this.viewport); + this.dimLeft = svg('text', { 'text-anchor': 'middle', 'pointer-events': 'none', 'font-family': 'Inter, system-ui, sans-serif' }, this.viewport); this.itemsLayer = svg('g', { class: 'fp-items' }, this.viewport); this.overlay = svg('g', { class: 'fp-overlay' }, this.viewport); @@ -614,14 +627,23 @@ baseScale() { const r = this.svg.getBoundingClientRect(); + // Leave room for the dimension labels on the top and left edge + const pad = this.dimFontSize() * 2; const m = 40; - return Math.max(0.01, Math.min((r.width - m) / this.settings.width, (r.height - m) / this.settings.depth)); + return Math.max(0.01, Math.min( + (r.width - m) / (this.settings.width + pad), (r.height - m) / (this.settings.depth + pad), + )); } 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 }; + const pad = this.dimFontSize(); + this.view = { + scale: s, + x: (r.width - (this.settings.width - pad) * s) / 2, + y: (r.height - (this.settings.depth - pad) * s) / 2, + }; this.applyView(); } @@ -658,6 +680,21 @@ this.gridPath.setAttribute('stroke', this.cssVar('--fp-grid', '#e2e8f0')); this.gridRect.style.display = this.gridVisible ? '' : 'none'; + // Room dimensions in meters along the top and left edge + const fs = this.dimFontSize(); + const muted = this.cssVar('--fp-muted', '#6c757d'); + this.dimTop.setAttribute('x', width / 2); + this.dimTop.setAttribute('y', -fs * 0.6); + this.dimTop.setAttribute('font-size', fs); + this.dimTop.setAttribute('fill', muted); + this.dimTop.textContent = meters(width) + ' m'; + this.dimLeft.setAttribute('x', 0); + this.dimLeft.setAttribute('y', 0); + this.dimLeft.setAttribute('font-size', fs); + this.dimLeft.setAttribute('fill', muted); + this.dimLeft.setAttribute('transform', `translate(${-fs * 0.6} ${depth / 2}) rotate(-90)`); + this.dimLeft.textContent = meters(depth) + ' m'; + const bg = this.cfg.background || {}; if (bg.url) { this.bgImage.setAttribute('href', bg.url); @@ -669,6 +706,10 @@ } } + dimFontSize() { + return clamp(Math.max(this.settings.width, this.settings.depth) * 0.025, 10, 200); + } + 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'; @@ -868,8 +909,25 @@ this.settings[key] = Math.max(min, v); this.renderFloor(); this.render(); + this.renderPanel(); }; + const sizeInput = html('input', { + type: 'text', class: 'form-control form-control-sm', value: roomSize(this.settings.width, this.settings.depth), + placeholder: this.t('e.g. 4 x 3'), title: this.t('Width x depth in meters, e.g. 4 x 3'), + onchange: (e) => { + const size = parseRoomSize(e.target.value); + if (!size || size[0] < 100 || size[1] < 100) { e.target.classList.add('is-invalid'); return; } + this.checkpoint(); + [this.settings.width, this.settings.depth] = size; + this.renderFloor(); + this.render(); + this.renderPanel(); + this.fit(); + }, + }); p.append( + field(this.t('Room size (m)'), sizeInput), + html('div', { class: 'fp-muted fp-field', text: this.t('Floor area') + ': ' + meters(this.settings.width * this.settings.depth / 100) + ' m²' }), 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 })), @@ -919,6 +977,7 @@ 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 })), ]), + html('div', { class: 'fp-muted fp-field', text: '= ' + roomSize(i.width, i.height) + ' m' }), 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', { @@ -1194,7 +1253,7 @@ 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` }), + html('div', { class: 'fp-muted', text: this.cfg.types[i.item_type] + ` · ${roomSize(i.width, i.height)} m` }), ]; 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 })); @@ -1227,7 +1286,7 @@ async exportClone() { const clone = this.svg.cloneNode(true); - const m = 20; + const m = Math.max(20, this.dimFontSize() * 2); 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); diff --git a/netbox_floorplanner/strings.py b/netbox_floorplanner/strings.py index 6fad4dd..c950121 100644 --- a/netbox_floorplanner/strings.py +++ b/netbox_floorplanner/strings.py @@ -52,6 +52,10 @@ JS_STRINGS = ( gettext_noop('Linked object'), gettext_noop('Open object'), gettext_noop('Grid size (cm)'), + gettext_noop('Room size (m)'), + gettext_noop('e.g. 4 x 3'), + gettext_noop('Width x depth in meters, e.g. 4 x 3'), + gettext_noop('Floor area'), gettext_noop('Status'), gettext_noop('Role'), gettext_noop('Tenant'), diff --git a/netbox_floorplanner/tables.py b/netbox_floorplanner/tables.py index 74cdf85..5f4426e 100644 --- a/netbox_floorplanner/tables.py +++ b/netbox_floorplanner/tables.py @@ -3,6 +3,7 @@ from django.utils.translation import gettext_lazy as _ from netbox.tables import NetBoxTable, columns from .models import FloorPlan +from .utils import format_room_size __all__ = ('FloorPlanTable',) @@ -11,6 +12,7 @@ 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) + room_size = tables.Column(verbose_name=_('Room size (m)'), empty_values=(), orderable=False) width = tables.Column(verbose_name=_('Width (cm)')) depth = tables.Column(verbose_name=_('Depth (cm)')) item_count = tables.Column(verbose_name=_('Items')) @@ -20,7 +22,10 @@ class FloorPlanTable(NetBoxTable): 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', + 'pk', 'id', 'name', 'site', 'location', 'room_size', 'width', 'depth', 'grid_size', 'item_count', + 'rack_count', 'description', 'tags', 'created', 'last_updated', ) - default_columns = ('name', 'site', 'location', 'width', 'depth', 'rack_count', 'description') + default_columns = ('name', 'site', 'location', 'room_size', 'rack_count', 'description') + + def render_room_size(self, record): + return f'{format_room_size(record.width, record.depth)} m' diff --git a/netbox_floorplanner/templates/netbox_floorplanner/floorplan.html b/netbox_floorplanner/templates/netbox_floorplanner/floorplan.html index d67c76d..66f72a7 100644 --- a/netbox_floorplanner/templates/netbox_floorplanner/floorplan.html +++ b/netbox_floorplanner/templates/netbox_floorplanner/floorplan.html @@ -35,7 +35,7 @@ {% trans "Dimensions" %} - {{ object.width }} × {{ object.depth }} cm + {{ room_size }} m ({{ object.width }} × {{ object.depth }} cm · {{ floor_area }} m²) {% trans "Grid size" %} diff --git a/netbox_floorplanner/utils.py b/netbox_floorplanner/utils.py new file mode 100644 index 0000000..e39ce62 --- /dev/null +++ b/netbox_floorplanner/utils.py @@ -0,0 +1,30 @@ +import re + +from django.utils import formats + +__all__ = ('format_meters', 'format_room_size', 'parse_room_size') + +# Accepts e.g. "4x3", "4 x 3 m", "4m x 3m", "12,5 × 8", "4.2*3" +ROOM_SIZE_RE = re.compile( + r'^\s*(\d+(?:[.,]\d+)?)\s*m?\s*[x×*]\s*(\d+(?:[.,]\d+)?)\s*m?\s*$', + re.IGNORECASE, +) + + +def parse_room_size(value): + """Parse " x " in meters; returns (width_cm, depth_cm) or None.""" + match = ROOM_SIZE_RE.match(value or '') + if not match: + return None + width, depth = (round(float(v.replace(',', '.')) * 100) for v in match.groups()) + return width, depth + + +def format_meters(cm): + """Format a centimeter value as meters using the active locale, e.g. 450 -> "4,5".""" + text = f'{cm / 100:.2f}'.rstrip('0').rstrip('.') + return text.replace('.', formats.get_format('DECIMAL_SEPARATOR')) + + +def format_room_size(width_cm, depth_cm): + return f'{format_meters(width_cm)} x {format_meters(depth_cm)}' diff --git a/netbox_floorplanner/views.py b/netbox_floorplanner/views.py index cf8540f..da0cacf 100644 --- a/netbox_floorplanner/views.py +++ b/netbox_floorplanner/views.py @@ -11,6 +11,7 @@ from . import filtersets, forms, tables from .choices import ItemTypeChoices from .models import FloorPlan from .strings import get_js_strings +from .utils import format_meters, format_room_size def floorplans_queryset(): @@ -66,7 +67,11 @@ class FloorPlanView(generic.ObjectView): queryset = floorplans_queryset() def get_extra_context(self, request, instance): - return {'designer_config': designer_config(request, instance, 'view')} + return { + 'designer_config': designer_config(request, instance, 'view'), + 'room_size': format_room_size(instance.width, instance.depth), + 'floor_area': format_meters(instance.width * instance.depth / 100), + } @register_model_view(FloorPlan, 'designer', path='designer')