""" Server-side SVG preview of a floor plan (read-only, no JavaScript). Mirrors the shape styling of the designer in floorplanner.js in a simplified form. """ from django.utils.html import escape from django.utils.safestring import mark_safe from .utils import format_meters __all__ = ('render_preview_svg',) TYPE_COLORS = { 'area': '#22c55e', 'wall': '#475569', 'door': '#b45309', 'window': '#0ea5e9', 'column': '#64748b', 'rack': '#3b82f6', 'device': '#8b5cf6', 'cooling': '#06b6d4', 'power': '#f59e0b', 'label': '#334155', } FILLED_TYPES = ('rack', 'device', 'cooling', 'power') def _shade(hex_color): try: n = int(hex_color.lstrip('#'), 16) except ValueError: return hex_color return '#{:02x}{:02x}{:02x}'.format(*(round(((n >> s) & 255) * 0.7) for s in (16, 8, 0))) def _item_svg(item): x, y, w, h = item.x, item.y, item.width, item.height cx, cy = x + w / 2, y + h / 2 color = item.color or TYPE_COLORS.get(item.item_type, '#868e96') parts = [] t = item.item_type if t == 'area': parts.append(f'') elif t in ('wall', 'door'): parts.append(f'') if t == 'door': parts.append(f'') elif t == 'window': parts.append(f'') elif t == 'column': parts.append(f'' f'') elif t in FILLED_TYPES: parts.append(f'') if t == 'rack': fh = min(h * 0.12, 10) parts.append(f'') text = item.label or (item.rack.name if item.rack_id else item.device.name if item.device_id else '') if text: if t == 'label': fs = max(8, h * 0.6) else: fs = max(6, min(h * 0.3, (w * 1.6) / max(len(text), 3), 60)) fill = '#ffffff' if t in FILLED_TYPES else (item.color or 'currentColor') if t == 'label' else _shade(color) anchor, tx, ty = ('start', x + fs * 0.5, y + fs * 1.2) if t == 'area' else ('middle', cx, cy) # Keep text readable on items rotated upside down flip = f' transform="rotate(180 {tx} {ty})"' if 90 < item.rotation % 360 <= 270 else '' parts.append(f'{escape(text)}') transform = f' transform="rotate({item.rotation} {cx} {cy})"' if item.rotation else '' return f'{"".join(parts)}' def render_preview_svg(floorplan): width, depth = floorplan.width, floorplan.depth fs = max(10, min(max(width, depth) * 0.025, 200)) m = fs * 2 items = floorplan.items.select_related('rack', 'device').order_by('z_index', 'pk') background = '' if floorplan.background_image: background = (f'') return mark_safe( f'' f'' f'{background}' f'{"".join(_item_svg(i) for i in items)}' f'' f'{format_meters(width)} m' f'{format_meters(depth)} m' f'' )