Skip to content

Home Information - Your home, your data, organized.

Python
9.1 KB
Raw Blame
from dataclasses import dataclass

from django.http import HttpRequest

from hi.apps.collection.models import Collection
from hi.apps.common.svg_models import SvgViewBox
from hi.apps.location.models import Location, LocationView

from .enums import ViewMode, ViewType


@dataclass
class ViewParameters:

    # Default SVG-editor snap grid in screen pixels (0 disables snapping).
    # Single source of truth for the value, seeded to the client via
    # ClientConfig and shared by both SVG editors.
    DEFAULT_SVG_SNAP_GRID_PIXELS = 5

    # For anything in this view state that needs to be kept in sync with
    # Javascript, add global variables in the base.html template at start
    # of body and reference in Javascript as needed. e.g., The editing mode
    # requires additional event registrations to handle mouse and gesture
    # events..

    view_type                   : ViewType  = None
    view_mode                   : ViewMode  = None
    location_view_id            : int       = None  # Last LocationView viewed
    collection_id               : int       = None  # Last Collection viewed
    ref_picker_integration_id   : str       = None  # Last referencer the operator successfully linked from

    # User preference: snap-grid size (screen pixels) for the SVG editors,
    # persisted across reloads. 0 = snapping disabled. Delivered to JS via
    # ClientConfig; both snap inputs render and write it back.
    svg_snap_grid_pixels        : int       = DEFAULT_SVG_SNAP_GRID_PIXELS

    # Transient pan/zoom state for the current LocationView. Pan/zoom is
    # normally ephemeral (a full reload restores the LocationView's stored
    # viewbox), but specific operations (e.g. adding an entity) want to
    # preserve where the user is looking. This holds the last-explored SVG
    # geometry so those operations can opt in to it; it is NOT a render
    # default - consumers apply it explicitly (see EntityAddView). It is
    # cleared whenever the view context shifts (different LocationView, or
    # any Collection view), since the geometry is meaningless elsewhere.
    # Serialized to/from the session as its SVG attribute string.
    last_svg_view_box           : SvgViewBox = None
    last_svg_rotate             : str        = None
    
    def __post_init__(self):
        if self.view_type is None:
            self.view_type = ViewType.default()
        if self.view_mode is None:
            self.view_mode = ViewMode.default()
        self._location = None  # Lazy loaded
        self._location_view = None  # Lazy loaded
        self._collection = None  # Lazy loaded
        return

    @property
    def is_editing(self):
        return self.view_mode.is_editing
    
    @property
    def location_id(self) -> int:
        location = self.location
        if location:
            return self._location.id
        return None
    
    @property
    def location(self) -> Location:
        if self._location:
            return self._location
        _ = self.location_view  # This will also load the location (if possible)
        return self._location
    
    @property
    def location_view(self) -> LocationView:
        if self._location_view:
            return self._location_view
        try:            
            if self.location_view_id is None:
                location = Location.objects.all().order_by( 'order_id' ).first()
                if not location:
                    raise Location.DoesNotExist()
                self._location_view = location.views.all().order_by( 'order_id' ).first()
                if not self._location_view:
                    raise LocationView.DoesNotExist()
            else:
                queryset = LocationView.objects.select_related('location')
                self._location_view = queryset.get( id = self.location_view_id )
                
            self.location_view_id = self._location_view.id
            self._location = self._location_view.location
            return self._location_view
        except ( Location.DoesNotExist, LocationView.DoesNotExist ):
            self.location_view_id = None
            return None

    def set_last_svg_geometry( self, svg_view_box : SvgViewBox, svg_rotate : str ):
        self.last_svg_view_box = svg_view_box
        self.last_svg_rotate = svg_rotate
        return

    def clear_last_svg_geometry( self ):
        self.last_svg_view_box = None
        self.last_svg_rotate = None
        return

    def update_location_view( self, location_view : LocationView ):
        if not location_view:
            if self.location_view_id is not None:
                self.clear_last_svg_geometry()
            self.location_view_id = None
            self._location_view = None
            self._location = None
        else:
            # Switching to a different LocationView invalidates any preserved
            # pan/zoom (sibling views share a Location's coordinate space but
            # frame it differently). Same-id re-renders must NOT clear it, or
            # the post-add redirect would lose the geometry it is preserving.
            if self.location_view_id != location_view.id:
                self.clear_last_svg_geometry()
            self.location_view_id = location_view.id
            self._location_view = location_view
            self._location = location_view.location
        return
            
    @property
    def active_location_view(self) -> Collection:
        if self.view_type != ViewType.LOCATION_VIEW:
            return None
        return self.location_view
    
    @property
    def collection(self) -> Collection:
        if self._collection:
            return self._collection
        if self.collection_id is None:
            return None
        try:
            self._collection = Collection.objects.get( id = self.collection_id )
            return self._collection
        except Collection.DoesNotExist:
            self.collection_id = None
            return None
        
    def update_collection( self, collection : Collection ):
        # Moving to a Collection view is a context shift away from any
        # LocationView; preserved location pan/zoom no longer applies.
        self.clear_last_svg_geometry()
        if not collection:
            self.collection_id = None
            self._collection = None
        else:
            self.collection_id = collection.id
            self._collection = collection
        return
        
    @property
    def active_collection(self) -> Collection:
        if self.view_type != ViewType.COLLECTION:
            return None
        return self.collection
        
    def to_session( self, request : HttpRequest ):
        if not hasattr( request, 'session' ):
            return
        request.session['view_type'] = str(self.view_type)
        request.session['view_mode'] = str(self.view_mode)
        request.session['location_view_id'] = self.location_view_id
        request.session['collection_id'] = self.collection_id
        request.session['ref_picker_integration_id'] = self.ref_picker_integration_id
        request.session['last_svg_view_box_str'] = (
            str(self.last_svg_view_box) if self.last_svg_view_box is not None else None
        )
        request.session['last_svg_rotate'] = self.last_svg_rotate
        request.session['svg_snap_grid_pixels'] = self.svg_snap_grid_pixels
        return

    @staticmethod
    def from_session( request : HttpRequest ):
        if not request:
            return ViewParameters()
        if not hasattr( request, 'session' ):
            return ViewParameters()

        view_type = ViewType.from_name_safe( name = request.session.get( 'view_type' ))
        view_mode = ViewMode.from_name_safe( name = request.session.get( 'view_mode' ))

        try:
            location_view_id = int( request.session.get( 'location_view_id' ))
        except ( TypeError, ValueError ):
            location_view_id = None
        try:
            collection_id = int( request.session.get( 'collection_id' ))
        except ( TypeError, ValueError ):
            collection_id = None

        ref_picker_integration_id = request.session.get(
            'ref_picker_integration_id',
        )

        last_svg_view_box = None
        last_svg_view_box_str = request.session.get( 'last_svg_view_box_str' )
        if last_svg_view_box_str:
            try:
                last_svg_view_box = SvgViewBox.from_attribute_value( last_svg_view_box_str )
            except ( ValueError, TypeError ):
                last_svg_view_box = None

        # Preserve an explicit 0 (snapping disabled); fall back to the
        # default only when the key is missing or malformed.
        try:
            svg_snap_grid_pixels = int( request.session.get( 'svg_snap_grid_pixels' ) )
        except ( TypeError, ValueError ):
            svg_snap_grid_pixels = ViewParameters.DEFAULT_SVG_SNAP_GRID_PIXELS

        return ViewParameters(
            view_type = view_type,
            view_mode = view_mode,
            location_view_id = location_view_id,
            collection_id = collection_id,
            ref_picker_integration_id = ref_picker_integration_id,
            last_svg_view_box = last_svg_view_box,
            last_svg_rotate = request.session.get( 'last_svg_rotate' ),
            svg_snap_grid_pixels = svg_snap_grid_pixels,
        )