Home Information - Your home, your data, organized.
Python
Progress on SVG icon position editing. WIP
Anthony Cassandrac059222f7d95
diff --git a/src/hi/apps/api/api_models.py b/src/hi/apps/api/api_models.pydeleted file mode 100644index 9a722526..00000000--- a/src/hi/apps/api/api_models.py+++ /dev/null@@ -1,82 +0,0 @@-"""-The models that define the interface and model translations between the-client and server. This is meant to decouple the client and server data-model spaces. We want the client to be a simple as possible and know as-little as possible about the server's internal models.-"""--from dataclasses import dataclass, field-import json-from typing import List--from hi.apps.common.svg_models import SvgPathStyle---@dataclass-class SvgIconItem:- """- A item that is positoned over a base SVG relative to the base SVG- viewBox. Styling is defined by CSS classes in the- icon_filename. Each itemm will have a "state" HTML attribute that can- be used to change the appearance of the icon based on state changes and- sensoir values. However, those are changes dynamically by the client- polling for status, so the svg file itself will contain the default- state value (how it appears when the state is unknown). This structure- is only used for the initial population of the SVG display when the- server is first providing the view..- """- html_id : str- icon_filename : str- svg_x : float- svg_y : float- scale : float- rotation : float-- def to_dict(self):- return {- 'html_id': self.html_id,- 'icon_filename': self.icon_filename,- 'svg_x': self.svg_x,- 'svg_y': self.svg_y,- 'scale': self.scale,- 'rotation': self.rotation,- }---@dataclass-class SvgPathItem:- html_id : str- svg_path : str # The value/content of the 'd' attribute- svg_path_style : SvgPathStyle-- def to_dict(self):- return {- 'html_id': self.html_id,- 'svg_path': self.svg_path,- 'svg_path_style': self.svg_path_style.to_dict(),- }---@dataclass-class SvgOverlayData:- """- All the data the client (Javascript) needs to display items over a a- base SVG. The positioning is relative to the current view box and- display area which only the Javascript can know since the dislpay area- is defined dynamically to be responsive.- """-- base_html_id : str- icon_items : List[ SvgIconItem ] = field( default_factory = list )- path_items : List[ SvgPathItem ] = field( default_factory = list )-- def to_dict(self):- return {- 'base_html_id': self.base_html_id,- 'icon_items': [ x.to_dict() for x in self.icon_items ],- 'path_items': [ x.to_dict() for x in self.path_items ],- }-- def to_json(self):- return json.dumps( self.to_dict() )-diff --git a/src/hi/apps/api/api_translator.py b/src/hi/apps/api/api_translator.pydeleted file mode 100644index 51e3b3c1..00000000--- a/src/hi/apps/api/api_translator.py+++ /dev/null@@ -1,51 +0,0 @@-from hi.apps.location.location_view_data import LocationViewData--from . import api_models---class ApiTranslator:-- @classmethod- def toSvgOverlayData( cls, location_view_data : LocationViewData ) -> api_models.SvgOverlayData:-- icon_items = list()- path_items = list()-- for entity_position in location_view_data.entity_positions:- icon_item = api_models.SvgIconItem(- html_id = entity_position.entity.html_id,- icon_filename = entity_position.entity.entity_type.svg_icon_template_name,- svg_x = float( entity_position.svg_x ),- svg_y = float( entity_position.svg_y ),- scale = float( entity_position.svg_scale ),- rotation = float( entity_position.svg_rotation ),- )- icon_items.append( icon_item )- continue-- for entity_path in location_view_data.entity_paths:- path_item = api_models.SvgPathItem(- html_id = entity_path.entity.html_id,- svg_path = entity_path.svg_path,- svg_path_style = entity_path.entity.entity_type.svg_path_style,- )- icon_items.append( path_item )- continue-- for collection_position in location_view_data.collection_positions:- icon_item = api_models.SvgIconItem(- html_id = collection_position.collection.html_id,- icon_filename = collection_position.collection.collection_type.svg_icon_template_name,- svg_x = float( collection_position.svg_x ),- svg_y = float( collection_position.svg_y ),- scale = float( collection_position.svg_scale ),- rotation = float( collection_position.svg_rotation ),- )- continue-- return api_models.SvgOverlayData(- base_html_id = location_view_data.location_view.html_id,- icon_items = icon_items,- path_items = path_items,- )-diff --git a/src/hi/apps/collection/migrations/0004_alter_collectionentity_options_and_more.py b/src/hi/apps/collection/migrations/0004_alter_collectionentity_options_and_more.pynew file mode 100644index 00000000..bc7f4214--- /dev/null+++ b/src/hi/apps/collection/migrations/0004_alter_collectionentity_options_and_more.py@@ -0,0 +1,62 @@+# Generated by Django 4.2.15 on 2024-09-01 04:00++from django.db import migrations, models+import django.db.models.deletion+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0005_rename_svg_rotation_locationview_svg_rotate"),+ ("collection", "0003_collectionview_order_id_and_more"),+ ]++ operations = [+ migrations.AlterModelOptions(+ name="collectionentity",+ options={+ "ordering": ["order_id"],+ "verbose_name": "Collection Entity",+ "verbose_name_plural": "Collection Entities",+ },+ ),+ migrations.AlterModelOptions(+ name="collectionposition",+ options={+ "verbose_name": "Collection Position",+ "verbose_name_plural": "Collection Positions",+ },+ ),+ migrations.RenameField(+ model_name="collectionposition",+ old_name="svg_rotation",+ new_name="svg_rotate",+ ),+ migrations.AlterField(+ model_name="collectionview",+ name="collection",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="collection_views",+ to="collection.collection",+ verbose_name="Collection",+ ),+ ),+ migrations.AlterField(+ model_name="collectionview",+ name="location_view",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="collection_views",+ to="location.locationview",+ verbose_name="Location",+ ),+ ),+ migrations.AddConstraint(+ model_name="collectionposition",+ constraint=models.UniqueConstraint(+ fields=("location", "collection"),+ name="collection_position_location_entity",+ ),+ ),+ ]diff --git a/src/hi/apps/collection/migrations/0005_alter_collectionposition_svg_rotate.py b/src/hi/apps/collection/migrations/0005_alter_collectionposition_svg_rotate.pynew file mode 100644index 00000000..c8fef5b6--- /dev/null+++ b/src/hi/apps/collection/migrations/0005_alter_collectionposition_svg_rotate.py@@ -0,0 +1,20 @@+# Generated by Django 4.2.15 on 2024-09-01 04:01++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("collection", "0004_alter_collectionentity_options_and_more"),+ ]++ operations = [+ migrations.AlterField(+ model_name="collectionposition",+ name="svg_rotate",+ field=models.DecimalField(+ decimal_places=6, default=0.0, max_digits=12, verbose_name="Rotate"+ ),+ ),+ ]diff --git a/src/hi/apps/collection/models.py b/src/hi/apps/collection/models.pyindex 757fd0fe..591abfb3 100644--- a/src/hi/apps/collection/models.py+++ b/src/hi/apps/collection/models.py@@ -104,6 +104,12 @@ class CollectionPosition( SvgPositionModel ):class Meta:verbose_name = 'Collection Position'verbose_name_plural = 'Collection Positions'+ constraints = [+ models.UniqueConstraint(+ fields = [ 'location', 'collection' ],+ name = 'collection_position_location_entity',+ ),+ ]@propertydef svg_item(self):@@ -113,7 +119,7 @@ class CollectionPosition( SvgPositionModel ):position_x = float( self.svg_x ),position_y = float( self.svg_y ),bounding_box = self.collection.collection_type.svg_icon_bounding_box,- rotate = float( self.svg_rotation ),+ rotate = float( self.svg_rotate ),scale = float( self.svg_scale ),)diff --git a/src/hi/apps/common/antinode.py b/src/hi/apps/common/antinode.pyindex 5d169a5a..b07b4a5b 100644--- a/src/hi/apps/common/antinode.py+++ b/src/hi/apps/common/antinode.py@@ -58,6 +58,7 @@ def response_as_dict( main_content = None,replace_map = None,insert_map = None,append_map = None,+ set_attributes_map = None,modal_content = None,push_url = None,reset_scrollbar = False ):@@ -91,6 +92,8 @@ def response_as_dict( main_content = None,response_dict['insert'] = insert_mapif append_map is not None:response_dict['append'] = append_map+ if set_attributes_map is not None:+ response_dict['setAttributes'] = set_attributes_mapif modal_content is not None:response_dict['modal'] = modal_contentif push_url is not None:@@ -104,19 +107,22 @@ def response( main_content = None,replace_map = None,insert_map = None,append_map = None,+ set_attributes_map = None,modal_content = None,push_url = None,reset_scrollbar = False,status = 200 ):- response_dict = response_as_dict( main_content = main_content,- replace_map = replace_map,- insert_map = insert_map,- append_map = append_map,- modal_content = modal_content,- push_url = push_url,- reset_scrollbar = reset_scrollbar,- )+ response_dict = response_as_dict(+ main_content = main_content,+ replace_map = replace_map,+ insert_map = insert_map,+ append_map = append_map,+ set_attributes_map = set_attributes_map,+ modal_content = modal_content,+ push_url = push_url,+ reset_scrollbar = reset_scrollbar,+ )return http_response( response_dict, status=status )diff --git a/src/hi/apps/common/svg_models.py b/src/hi/apps/common/svg_models.pyindex e5ad3493..fd32e29c 100644--- a/src/hi/apps/common/svg_models.py+++ b/src/hi/apps/common/svg_models.py@@ -83,11 +83,11 @@ class SvgItem:# - Translation does not dirrectly move the item, but insteadmodifies# the coordinate systems zero point.# - Scaling has to be accounted for in the translation cooridinates.- # - Scaling does *not* affect the rotate center point.- # - Translation does not affect the roatate center point.+ # - Translation does not affect the rotate center point.+ # - Scaling does not affect the rotate center point# - Thus, though the transformation order matters, things that# come before can impact things that come after.- # - Also, scaling does not always need to be compensated for.+ # - Scaling does not always have to be taken into account.# Template namehtml_id : str@@ -98,6 +98,10 @@ class SvgItem:rotate : float = 0.0scale : float = 1.0+ @property+ def transform_str(self):+ return f'scale( {self.scale} ) translate( {self.translate_x} {self.translate_y} ) rotate( {self.rotate} {self.bounds_center_x} {self.bounds_center_y} )'+@propertydef bounds_center_x(self):return self.bounding_box.x + ( self.bounding_box.width / 2.0 )@@ -119,16 +123,3 @@ class SvgItem:if self.scale < 0.000001:return 0return ( self.position_y / self.scale ) - self.bounds_center_y-- @property- def rotation_x(self):- if self.scale < 0.000001:- return 0- return ( self.position_x / self.scale )-- @property- def rotation_y(self):- if self.scale < 0.000001:- return 0- return ( self.position_y / self.scale )-diff --git a/src/hi/apps/edit/templates/edit/panes/bottom.html b/src/hi/apps/edit/templates/edit/panes/bottom.htmldeleted file mode 100644index be029aef..00000000--- a/src/hi/apps/edit/templates/edit/panes/bottom.html+++ /dev/null@@ -1,9 +0,0 @@-<div class="row bg-white p-1">-- <div class="col-1">- <a href="{% url 'edit_end' %}"- class="btn btn-tertiary btn-control" role="button" >- EXIT- </a>- </div>-</div>diff --git a/src/hi/apps/edit/templates/edit/panes/collection.html b/src/hi/apps/edit/templates/edit/panes/collection.htmlnew file mode 100644index 00000000..f8ce2c06--- /dev/null+++ b/src/hi/apps/edit/templates/edit/panes/collection.html@@ -0,0 +1,11 @@+<h4>{{ collection.name }}</h4>++<h5>Position</h5>+<div id="hi-edit-svg-position">+ {% include "edit/panes/svg_position.html" with html_id=collection.html_id svg_position_form=svg_position_form %}+</div>++<h5>Views</h5>+<div id="hi-edit-collection-views">+ {% include "edit/panes/collection_views.html" %}+</div>diff --git a/src/hi/apps/edit/templates/edit/panes/collection_views.html b/src/hi/apps/edit/templates/edit/panes/collection_views.htmlnew file mode 100644index 00000000..bbc7148f--- /dev/null+++ b/src/hi/apps/edit/templates/edit/panes/collection_views.html@@ -0,0 +1 @@+TBD - VIEWSdiff --git a/src/hi/apps/edit/templates/edit/panes/entity.html b/src/hi/apps/edit/templates/edit/panes/entity.htmlnew file mode 100644index 00000000..fd2502b1--- /dev/null+++ b/src/hi/apps/edit/templates/edit/panes/entity.html@@ -0,0 +1,26 @@+<h4>{{ entity.name }}</h4>++<h5>Position</h5>+<div id="hi-edit-svg-position">+ {% include "edit/panes/svg_position.html" with html_id=entity.html_id svg_position_form=svg_position_form %}+</div>++<h5>Attributes</h5>+<div id="hi-edit-entity-attributes">+ {% include "edit/panes/entity_attributes.html" %}+</div>++<h5>Views</h5>+<div id="hi-edit-entity-views">+ {% include "edit/panes/entity_views.html" %}+</div>++<h5>Sensors</h5>+<div id="hi-edit-entity-sensors">+ {% include "edit/panes/entity_sensors.html" %}+</div>++<h5>Controllers</h5>+<div id="hi-edit-entity-controllers">+ {% include "edit/panes/entity_controllers.html" %}+</div>diff --git a/src/hi/apps/edit/templates/edit/panes/entity_attributes.html b/src/hi/apps/edit/templates/edit/panes/entity_attributes.htmlnew file mode 100644index 00000000..b539898c--- /dev/null+++ b/src/hi/apps/edit/templates/edit/panes/entity_attributes.html@@ -0,0 +1 @@+TBD - ATTRIBUTESdiff --git a/src/hi/apps/edit/templates/edit/panes/entity_controllers.html b/src/hi/apps/edit/templates/edit/panes/entity_controllers.htmlnew file mode 100644index 00000000..02b8f9cc--- /dev/null+++ b/src/hi/apps/edit/templates/edit/panes/entity_controllers.html@@ -0,0 +1 @@+TBD - CONTROLLERSdiff --git a/src/hi/apps/edit/templates/edit/panes/entity_sensors.html b/src/hi/apps/edit/templates/edit/panes/entity_sensors.htmlnew file mode 100644index 00000000..fb6dc86e--- /dev/null+++ b/src/hi/apps/edit/templates/edit/panes/entity_sensors.html@@ -0,0 +1 @@+TBD - SENSORSdiff --git a/src/hi/apps/edit/templates/edit/panes/entity_views.html b/src/hi/apps/edit/templates/edit/panes/entity_views.htmlnew file mode 100644index 00000000..bbc7148f--- /dev/null+++ b/src/hi/apps/edit/templates/edit/panes/entity_views.html@@ -0,0 +1 @@+TBD - VIEWSdiff --git a/src/hi/apps/edit/templates/edit/panes/main.html b/src/hi/apps/edit/templates/edit/panes/main.htmldeleted file mode 100644index 410c7989..00000000--- a/src/hi/apps/edit/templates/edit/panes/main.html+++ /dev/null@@ -1 +0,0 @@-<h5>Edit Main</h5>diff --git a/src/hi/apps/edit/templates/edit/panes/side.html b/src/hi/apps/edit/templates/edit/panes/side.htmlindex b405d5e2..0a0ec272 100644--- a/src/hi/apps/edit/templates/edit/panes/side.html+++ b/src/hi/apps/edit/templates/edit/panes/side.html@@ -1 +1,17 @@-<h5>Edit Side</h5>+<div id="hi-edit-side-content" class="d-flex justify-content-between">+ <div class="h5">Editing</div>+ <div class="">+ <a href="{% url 'edit_end' %}"+ class="btn btn-tertiary" role="button" >+ EXIT+ </a>+ </div>+</div>+<div id="hi-edit-entity">+ {% if entity %}+ {% include "edit/panes/entity.html" %}+ {% else %}+ <div><em>Click to see details.</em></div>+ {% endif %}+</div>+diff --git a/src/hi/apps/edit/templates/edit/panes/svg_position.html b/src/hi/apps/edit/templates/edit/panes/svg_position.htmlnew file mode 100644index 00000000..75eafdc4--- /dev/null+++ b/src/hi/apps/edit/templates/edit/panes/svg_position.html@@ -0,0 +1,46 @@+{% if not svg_position_form.instance %}+<div><em>Not positioned.</em></div>+{% endif %}++<form action="{% url 'edit_svg_position' html_id=html_id %}" method="post"+ class="form" data-async="#hi-edit-svg-position">+ {% csrf_token %}++ {% for hidden in svg_position_form.hidden_fields %}+ {{ hidden }}+ {% endfor %}++ {% if svg_position_form.non_field_errors %}+ <div class="non-field-errors alert alert-danger">+ {% for err in svg_position_form.non_field_errors %}+ <p class="form-error">{{ err }}</p>+ {% endfor %}+ </div>+ {% endif %}++ <div class="pt-4">+ {{ svg_position_form.svg_x.label }}+ {{ svg_position_form.svg_x }}+ {{ svg_position_form.svg_x.errors }}+ </div>++ <div class="pt-4">+ {{ svg_position_form.svg_y.label }}+ {{ svg_position_form.svg_y }}+ {{ svg_position_form.svg_y.errors }}+ </div>++ <div class="pt-4">+ {{ svg_position_form.svg_scale.label }}+ {{ svg_position_form.svg_scale }}+ {{ svg_position_form.svg_scale.errors }}+ </div>++ <div class="pt-4">+ {{ svg_position_form.svg_rotate.label }}+ {{ svg_position_form.svg_rotate }}+ {{ svg_position_form.svg_rotate.errors }}+ </div>++ <button type="submit" role="button" >SUBMIT</button>+</form>diff --git a/src/hi/apps/edit/urls.py b/src/hi/apps/edit/urls.pyindex e2815040..d2a001dd 100644--- a/src/hi/apps/edit/urls.py+++ b/src/hi/apps/edit/urls.py@@ -12,4 +12,12 @@ urlpatterns = [re_path( r'^end$',views.EditEndView.as_view(),name='edit_end' ),++ re_path( r'^details/(?P<html_id>[\w\-]+)$',+ views.EditDetailsView.as_view(),+ name='edit_details' ),++ re_path( r'^svg/position/(?P<html_id>[\w\-]+)$',+ views.EditSvgPositionView.as_view(),+ name='edit_svg_position' ),]diff --git a/src/hi/apps/edit/views.py b/src/hi/apps/edit/views.pyindex c4a56e00..970d3bd7 100644--- a/src/hi/apps/edit/views.py+++ b/src/hi/apps/edit/views.py@@ -1,37 +1,207 @@-from django.http import HttpResponseRedirect+import re++from django.shortcuts import redirect+from django.template.loader import get_templatefrom django.urls import reverse+from django.views.generic import View++import hi.apps.common.antinode as antinode+from hi.apps.collection.models import Collection, CollectionPosition+from hi.apps.entity.models import Entity, EntityPosition+from hi.apps.location.forms import SvgPositionForm+from hi.apps.location.models import Location-from hi.hi_grid_view import HiGridView+from hi.constants import DIVIDfrom hi.enums import EditMode-class EditStartView( HiGridView ):+class EditViewMixin:- def get(self, request, *args, **kwargs):+ def parse_html_id( self, html_id : str ):+ m = re.match( r'^hi-(\w+)-(\d+)$', html_id )+ if not m:+ raise NotImplementedError( 'Not yet handling bad edit details html id' )+ return ( m.group(1), int(m.group(2)) )++class EditStartView( View ):++ def get(self, request, *args, **kwargs):request.view_parameters.edit_mode = EditMode.ONrequest.view_parameters.to_session( request )++ redirect_url = request.META.get('HTTP_REFERER')+ if not redirect_url:+ redirect_url = reverse('home')+ return redirect( redirect_url )+++class EditEndView( View ):++ def get(self, request, *args, **kwargs):+ request.view_parameters.edit_mode = EditMode.OFF+ request.view_parameters.to_session( request )++ redirect_url = request.META.get('HTTP_REFERER')+ if not redirect_url:+ redirect_url = reverse('home')+ return redirect( redirect_url )+++class EditDetailsView( View, EditViewMixin ):++ def get(self, request, *args, **kwargs):+ if request.view_parameters.edit_mode == EditMode.OFF:+ raise NotImplementedError( 'Not yet handling bad edit context' )++ ( item_type, item_id ) = self.parse_html_id( kwargs.get('html_id'))++ if item_type == 'entity':+ return self.get_entity_details( request, entity_id = item_id )+ if item_type == 'collection':+ return self.get_collection_details( request, collection_id = item_id )+ raise NotImplementedError( 'Not yet handling unknown edit detail type.' )++ def get_entity_details( self, request, entity_id : int ):+ try:+ entity = Entity.objects.get( id = entity_id )+ except Entity.DoesNotExist:+ raise NotImplementedError( 'Handling bad entity Id not yet implemented' )++ location_view = request.view_parameters.location_view+ entity_position = EntityPosition.objects.filter(+ entity = entity,+ location = location_view.location,+ ).first()++ svg_position_form = SvgPositionForm.from_svg_position_model( entity_position )++ context = {+ 'entity': entity,+ 'svg_position_form': svg_position_form,+ }+ template = get_template('edit/panes/entity.html')+ content = template.render( context, request = request )+ insert_map = {+ DIVID['EDIT_ENTITY']: content,+ }+ return antinode.response(+ insert_map = insert_map,+ )++ def get_collection_details( self, request, collection_id : int ):+ try:+ collection = Collection.objects.get( id = collection_id )+ except Collection.DoesNotExist:+ raise NotImplementedError( 'Handling bad collection Id not yet implemented' )++ location_view = request.view_parameters.location_view+ collection_position = CollectionPosition.objects.filter(+ collection = collection,+ location = location_view.location,+ ).first()++ svg_position_form = SvgPositionForm.from_svg_position_model( collection_position )+context = {+ 'collection': collection,+ 'svg_position_form': svg_position_form,+ }+ template = get_template('edit/panes/collection.html')+ content = template.render( context, request = request )++ insert_map = {+ DIVID['EDIT_COLLECTION']: content,}- return self.hi_grid_response(- request = request,- context = context,- bottom_template_name = 'edit/panes/bottom.html',- main_template_name = 'edit/panes/main.html',- side_template_name = 'edit/panes/side.html',- push_url_name = 'edit_start',- push_url_kwargs = kwargs,+ return antinode.response(+ insert_map = insert_map,)+++class EditSvgPositionView( View, EditViewMixin ):--class EditEndView( HiGridView ):+ def post(self, request, *args, **kwargs):+ if request.view_parameters.edit_mode == EditMode.OFF:+ raise NotImplementedError( 'Not yet handling bad edit context' )- def get(self, request, *args, **kwargs):+ ( item_type, item_id ) = self.parse_html_id( kwargs.get('html_id'))- request.view_parameters.edit_mode = EditMode.OFF- request.view_parameters.to_session( request )+ location_view = request.view_parameters.location_view+ if item_type == 'entity':+ svg_position_model = self.get_entity_position(+ entity_id = item_id,+ location = location_view.location,+ )+ elif item_type == 'collection':+ svg_position_model = self.get_collection_position(+ collection_id = item_id,+ location = location_view.location,+ )+ else:+ raise NotImplementedError( 'Not yet handling unknown edit detail type.' )- redirect_url = reverse( 'home' )- return HttpResponseRedirect( redirect_url )+ svg_position_form = SvgPositionForm( request.POST )+ if svg_position_form.is_valid():+ svg_position_form.to_svg_position_model( svg_position_model )+ svg_position_model.save()++ svg_position_item = svg_position_model.svg_item+ context = {+ 'html_id': svg_position_item.html_id,+ 'svg_position_form': svg_position_form,+ }+ template = get_template('edit/panes/svg_position.html')+ content = template.render( context, request = request )++ insert_map = {+ DIVID['EDIT_SVG_POSITION']: content,+ }+ set_attributes_map = {+ svg_position_item.html_id: {+ 'transform': svg_position_item.transform_str,+ }+ }+ return antinode.response(+ insert_map = insert_map,+ set_attributes_map = set_attributes_map,+ )++ def get_entity_position( self,+ entity_id : int,+ location : Location ):+ try:+ entity = Entity.objects.get( id = entity_id )+ except Entity.DoesNotExist:+ raise NotImplementedError( 'Handling bad entity Id not yet implemented' )++ entity_position = EntityPosition.objects.filter(+ entity = entity,+ location = location,+ ).first()+ if entity_position:+ return entity_position+ return EntityPosition(+ entity = entity,+ location = location,+ )+ def get_collection_position( self,+ collection_id : int,+ location : Location ):+ try:+ collection = Collection.objects.get( id = collection_id )+ except Collection.DoesNotExist:+ raise NotImplementedError( 'Handling bad collection Id not yet implemented' )++ collection_position = CollectionPosition.objects.filter(+ collection = collection,+ location = location,+ ).first()+ if collection_position:+ return collection_position++ return CollectionPosition(+ collection = collection,+ location = location,+ )diff --git a/src/hi/apps/entity/migrations/0006_remove_entitypath_entity_enti_locatio_15cbf9_idx_and_more.py b/src/hi/apps/entity/migrations/0006_remove_entitypath_entity_enti_locatio_15cbf9_idx_and_more.pynew file mode 100644index 00000000..b152ee67--- /dev/null+++ b/src/hi/apps/entity/migrations/0006_remove_entitypath_entity_enti_locatio_15cbf9_idx_and_more.py@@ -0,0 +1,65 @@+# Generated by Django 4.2.15 on 2024-09-01 04:00++from django.db import migrations, models+import django.db.models.deletion+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0005_rename_svg_rotation_locationview_svg_rotate"),+ ("entity", "0005_entitypath_updated_datetime_and_more"),+ ]++ operations = [+ migrations.RemoveIndex(+ model_name="entitypath",+ name="entity_enti_locatio_15cbf9_idx",+ ),+ migrations.RemoveIndex(+ model_name="entityposition",+ name="entity_enti_locatio_0402a2_idx",+ ),+ migrations.RenameField(+ model_name="entityposition",+ old_name="svg_rotation",+ new_name="svg_rotate",+ ),+ migrations.AlterField(+ model_name="entitystate",+ name="value_range",+ field=models.TextField(blank=True, null=True, verbose_name="Value Range"),+ ),+ migrations.AlterField(+ model_name="entityview",+ name="entity",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="entity_views",+ to="entity.entity",+ verbose_name="Entity",+ ),+ ),+ migrations.AlterField(+ model_name="entityview",+ name="location_view",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="entity_views",+ to="location.locationview",+ verbose_name="Location",+ ),+ ),+ migrations.AddConstraint(+ model_name="entitypath",+ constraint=models.UniqueConstraint(+ fields=("location", "entity"), name="entity_path_location_entity"+ ),+ ),+ migrations.AddConstraint(+ model_name="entityposition",+ constraint=models.UniqueConstraint(+ fields=("location", "entity"), name="entity_position_location_entity"+ ),+ ),+ ]diff --git a/src/hi/apps/entity/migrations/0007_alter_entityposition_svg_rotate.py b/src/hi/apps/entity/migrations/0007_alter_entityposition_svg_rotate.pynew file mode 100644index 00000000..62397565--- /dev/null+++ b/src/hi/apps/entity/migrations/0007_alter_entityposition_svg_rotate.py@@ -0,0 +1,20 @@+# Generated by Django 4.2.15 on 2024-09-01 04:01++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("entity", "0006_remove_entitypath_entity_enti_locatio_15cbf9_idx_and_more"),+ ]++ operations = [+ migrations.AlterField(+ model_name="entityposition",+ name="svg_rotate",+ field=models.DecimalField(+ decimal_places=6, default=0.0, max_digits=12, verbose_name="Rotate"+ ),+ ),+ ]diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.pyindex 8d51d8f8..19388772 100644--- a/src/hi/apps/entity/models.py+++ b/src/hi/apps/entity/models.py@@ -303,8 +303,11 @@ class EntityPosition( SvgPositionModel ):class Meta:verbose_name = 'Entity Position'verbose_name_plural = 'Entity Positions'- indexes = [- models.Index( fields=[ 'location', 'entity' ] ),+ constraints = [+ models.UniqueConstraint(+ fields = [ 'location', 'entity' ],+ name = 'entity_position_location_entity',+ ),]@property@@ -315,7 +318,7 @@ class EntityPosition( SvgPositionModel ):position_x = float( self.svg_x ),position_y = float( self.svg_y ),bounding_box = self.entity.entity_type.svg_icon_bounding_box,- # rotate = float( self.svg_rotation ),+ # rotate = float( self.svg_rotate ),# scale = float( self.svg_scale ),rotate = 0,scale = 4.0,@@ -354,8 +357,10 @@ class EntityPath( SvgPathModel ):class Meta:verbose_name = 'Entity Path'verbose_name_plural = 'Entity Paths'- indexes = [- models.Index( fields=[ 'location', 'entity' ] ),+ constraints = [+ models.UniqueConstraint(+ fields = [ 'location', 'entity' ],+ name = 'entity_path_location_entity', ),]diff --git a/src/hi/apps/location/admin.py b/src/hi/apps/location/admin.pyindex 03cada63..4a237730 100644--- a/src/hi/apps/location/admin.py+++ b/src/hi/apps/location/admin.py@@ -39,7 +39,7 @@ class LocationViewAdmin(admin.ModelAdmin):'name','location','svg_view_box_str',- 'svg_rotation',+ 'svg_rotate','order_id','created_datetime','updated_datetime',diff --git a/src/hi/apps/location/forms.py b/src/hi/apps/location/forms.pynew file mode 100644index 00000000..d40d6c9f--- /dev/null+++ b/src/hi/apps/location/forms.py@@ -0,0 +1,55 @@+from decimal import Decimal++from django import forms++from .models import SvgPositionModel+++class SvgPositionForm(forms.Form):++ svg_x = forms.DecimalField(+ label = 'X',+ decimal_places = 3,+ required = True,+ )+ svg_y = forms.DecimalField(+ label = 'Y',+ decimal_places = 3,+ required = True,+ )+ svg_scale = forms.DecimalField(+ label = 'Scale',+ decimal_places = 3,+ required = True,+ )+ svg_rotate = forms.DecimalField(+ label = 'Angle',+ decimal_places = 3,+ required = True,+ )++ @classmethod+ def from_svg_position_model( cls, svg_position_model : SvgPositionModel ):+ if svg_position_model:+ return cls(+ initial = {+ 'svg_x': svg_position_model.svg_x,+ 'svg_y': svg_position_model.svg_y,+ 'svg_scale': svg_position_model.svg_scale,+ 'svg_rotate': svg_position_model.svg_rotate,+ },+ )+ return cls(+ initial = {+ 'svg_scale': Decimal( 1.0 ),+ 'svg_rotate': Decimal( 0.0 ),+ },+ )++ def to_svg_position_model( self, svg_position_model : SvgPositionModel ):+ svg_position_model.svg_x = self.svg_x+ svg_position_model.svg_y = self.svg_y+ svg_position_model.svg_scale = self.svg_scale+ svg_position_model.svg_rotate = self.svg_rotate+ return+diff --git a/src/hi/apps/location/migrations/0005_rename_svg_rotation_locationview_svg_rotate.py b/src/hi/apps/location/migrations/0005_rename_svg_rotation_locationview_svg_rotate.pynew file mode 100644index 00000000..0c1c5b43--- /dev/null+++ b/src/hi/apps/location/migrations/0005_rename_svg_rotation_locationview_svg_rotate.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-09-01 04:00++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0004_rename_svg_viewbox_location_svg_view_box_str_and_more"),+ ]++ operations = [+ migrations.RenameField(+ model_name="locationview",+ old_name="svg_rotation",+ new_name="svg_rotate",+ ),+ ]diff --git a/src/hi/apps/location/migrations/0006_alter_locationview_svg_rotate.py b/src/hi/apps/location/migrations/0006_alter_locationview_svg_rotate.pynew file mode 100644index 00000000..3a707c1a--- /dev/null+++ b/src/hi/apps/location/migrations/0006_alter_locationview_svg_rotate.py@@ -0,0 +1,20 @@+# Generated by Django 4.2.15 on 2024-09-01 04:01++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0005_rename_svg_rotation_locationview_svg_rotate"),+ ]++ operations = [+ migrations.AlterField(+ model_name="locationview",+ name="svg_rotate",+ field=models.DecimalField(+ decimal_places=6, max_digits=9, verbose_name="Rotate"+ ),+ ),+ ]diff --git a/src/hi/apps/location/models.py b/src/hi/apps/location/models.pyindex 34169130..2988e240 100644--- a/src/hi/apps/location/models.py+++ b/src/hi/apps/location/models.py@@ -1,6 +1,6 @@from django.db import models-from hi.apps.common.svg_models import SvgViewBox+from hi.apps.common.svg_models import SvgItem, SvgViewBoxfrom .enums import ViewType@@ -95,8 +95,8 @@ class LocationView(models.Model):max_length = 64,null = False, blank = False,)- svg_rotation = models.DecimalField(- 'Rotation',+ svg_rotate = models.DecimalField(+ 'Rotate',max_digits = 9,decimal_places = 6,)@@ -172,14 +172,18 @@ class SvgPositionModel(models.Model):decimal_places = 6,default = 1.0,)- svg_rotation = models.DecimalField(- 'Rotation',+ svg_rotate = models.DecimalField(+ 'Rotate',max_digits = 12,decimal_places = 6,default = 0.0,)-+ @property+ def svg_item(self) -> SvgItem:+ raise NotImplementedError('Subclasses must implement this method.')++class SvgPathModel(models.Model):"""For models that have a visual representaion that can be overlayed ondiff --git a/src/hi/apps/location/templates/location/location_view.html b/src/hi/apps/location/templates/location/location_view.htmlindex c3c4a414..aea43100 100644--- a/src/hi/apps/location/templates/location/location_view.html+++ b/src/hi/apps/location/templates/location/location_view.html@@ -1,21 +1,17 @@{% load common_template_helpers %}<div id="hi-location-view-main" class="hi-location-view">- <svg id="{{ location_view_data.location_view.html_id }}" xmlns="http://www.w3.org/2000/svg"+ <svg id="{{ location_view_data.location_view.html_id }}"+ xmlns="http://www.w3.org/2000/svg"viewBox="{{ location_view_data.location_view.svg_view_box }}"- transform="rotate({{ location_view_data.location_view.svg_rotation }} 0 0)">+ width="100%" height="100%" preserveAspectRatio="xMidYMid meet"+ transform="rotate({{ location_view_data.location_view.svg_rotate }} 0 0)">{% include_media_template location_view_data.location_view.location.svg_filename %}{% for entity_path in location_view_data.entity_paths %}{% endfor %}{% for entity_position in location_view_data.entity_positions %}- {% with entity_position.svg_item as svg_item %}- <g id="{{ svg_item.html_id }}"- class="draggable"- transform="scale( {{ svg_item.scale }} ) translate( {{ svg_item.translate_x }} {{ svg_item.translate_y }} ) rotate( {{ svg_item.rotate }} {{ svg_item.bounds_center_x }} {{ svg_item.bounds_center_y }} )">- {% include entity_position.svg_item.template_name %}- </g>- {% endwith %}+ {% include "location/svg_position_item.html" with svg_position_item=entity_position.svg_item %}{% endfor %}{% for collection_position in location_view_data.collection_positions %}diff --git a/src/hi/apps/location/templates/location/svg_position_item.html b/src/hi/apps/location/templates/location/svg_position_item.htmlnew file mode 100644index 00000000..2adeb42d--- /dev/null+++ b/src/hi/apps/location/templates/location/svg_position_item.html@@ -0,0 +1,5 @@+<g id="{{ svg_position_item.html_id }}"+ class="draggable"+ transform="{{ svg_position_item.transform_str }}">+ {% include svg_position_item.template_name %}+</g>diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.pyindex b8919430..8f0107ad 100644--- a/src/hi/apps/location/views.py+++ b/src/hi/apps/location/views.py@@ -4,7 +4,6 @@ from django.http import HttpResponseRedirectfrom django.urls import reversefrom django.views.generic import View-from hi.apps.api.api_translator import ApiTranslatorfrom hi.apps.common.utils import is_ajaxfrom hi.hi_grid_view import HiGridView@@ -61,13 +60,9 @@ class LocationViewView( HiGridView ):location_view_data = LocationViewManager().get_location_view_data(location_view = location_view,)- svgOverlayData = ApiTranslator.toSvgOverlayData(- location_view_data = location_view_data,- )context = {'is_async_request': is_ajax( request ),'location_view_data': location_view_data,- 'svgOverlayData': svgOverlayData,}return self.hi_grid_response(request = request,diff --git a/src/hi/constants.py b/src/hi/constants.pyindex 99ff2ca5..1fb4f1cf 100644--- a/src/hi/constants.py+++ b/src/hi/constants.py@@ -1,9 +1,25 @@# HTML div ids that are commonly referencedDIVID = {++ # Main HI Grid Structure'TOP': 'hi-top-content','BOTTOM': 'hi-bottom-content','MAIN': 'hi-main-content','SIDE': 'hi-side-content',++ # Config'INTEGRATION_TAB': 'hi-config-integration-tab',++ # Editing+ 'EDIT_SIDE': 'hi-edit-side-content',+ 'EDIT_ENTITY': 'hi-edit-entity',+ 'EDIT_COLLECTION': 'hi-edit-collection',+ 'EDIT_SVG_POSITION': 'hi-edit-svg-position',+ 'EDIT_ENTITY_VIEWS': 'hi-edit-entity-views',+ 'EDIT_ENTITY_ATTRIBUTES': 'hi-edit-entity-attributes',+ 'EDIT_ENTITY_SENSORS': 'hi-edit-entity-sensors',+ 'EDIT_ENTITY_CONTROLLERS': 'hi-edit-entity-controllers',++}diff --git a/src/hi/enums.py b/src/hi/enums.pyindex 49748c17..31d1b7ac 100644--- a/src/hi/enums.py+++ b/src/hi/enums.py@@ -5,4 +5,7 @@ class EditMode(LabeledEnum):OFF = ('Off', '' )ON = ('On', '' )-++ @property+ def is_editing(self):+ return bool( self != EditMode.OFF )diff --git a/src/hi/middleware.py b/src/hi/middleware.pyindex d07995d0..a343c9d4 100644--- a/src/hi/middleware.py+++ b/src/hi/middleware.py@@ -18,5 +18,6 @@ class ViewMiddleware:def _set_view_parameters( self, request ):request.view_parameters = ViewParameters.from_session( request )+ request.is_editing = request.view_parameters.edit_mode.is_editingreturndiff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.jsindex 5d749ba9..2a649490 100644--- a/src/hi/static/js/antinode.js+++ b/src/hi/static/js/antinode.js@@ -61,7 +61,7 @@//// onchange-async="true"//-// If you define the javascript function "AN_handlePostAsyncUpdate()", this+// If you define the javascript function "handlePostAsyncUpdate()", this// will be called after each async content update after all updated are// handled.//@@ -96,6 +96,53 @@// synchronous refresh to ensure the latest version of the CSS and JS// assets are loaded.+(function() {++ const AN = {+ get: function( url ) {+ $.ajax({+ type: 'GET',+ url: url,++ success: function(data, status, xhr) {+ asyncUpdateData( null, null, data, xhr );+ return false;+ },+ error: function (xhr, ajaxOptions, thrownError) {+ let http_code = xhr.status;+ let error_msg = thrownError;+ asyncUpdateData( null, null, xhr.responseText, xhr );+ return false;+ }+ });+ },++ post: function( url ) {+ $.ajax({+ type: 'POST',+ url: url,+ data: data,+ async: true,+ cache: false,+ contentType: false,+ processData: false,++ success: function(data, status, xhr) {+ asyncUpdateData( null, null, data, xhr );+ return false;+ },+ error: function (xhr, ajaxOptions, thrownError) {+ let http_code = xhr.status;+ let error_msg = thrownError;+ asyncUpdateData( null, null, xhr.responseText, xhr );+ return false;+ }+ });+ }+ }++ window.AN = AN;+//====================// The handle for forms that want to trigger an ansynchonous (aka, ajax)// request.@@ -104,7 +151,7 @@ function asyncSubmitHandler(event) {event.preventDefault();event.stopPropagation();- var $form = $(this);+ let $form = $(this);return asyncSubmitHandlerHelper( $form );};@@ -114,11 +161,11 @@ function asyncSubmitHandlerHelper( $form ) {$form.find('button').prop('disabled', true);}- AN_handleHideShowIfNeeded( $form );+ handleHideShowIfNeeded( $form );- var $target = getAsyncTarget( $form );+ let $target = getAsyncTarget( $form );- var $mode = $form.attr('data-mode');+ let $mode = $form.attr('data-mode');if ( ! $mode ) {$mode = 'insert';}@@ -129,8 +176,8 @@ function asyncSubmitHandlerHelper( $form ) {// In case the last submit button data was saved.// (See: lastButtonClickHandler)//- var lastButtonName = $form.data('lastSubmitButtonName');- var lastButtonValue = null;+ let lastButtonName = $form.data('lastSubmitButtonName');+ let lastButtonValue = null;if ( lastButtonName ) {lastButtonValue = $form.data('lastSubmitButtonValue');@@ -142,16 +189,15 @@ function asyncSubmitHandlerHelper( $form ) {$form.removeData('lastSubmitButtonValue');}- var formData = null;- var processData = true;- var contentType = null;- var async = true;- var cache = true;-+ let formData = null;+ let processData = true;+ let contentType = null;+ let async = true;+ let cache = true;if (( $($form).attr('method') )&& ( $($form).attr('method').toUpperCase() == 'GET' )) {- var formData = $form.serializeArray();+ let formData = $form.serializeArray();if ( lastButtonName ) {formData.push( { name: lastButtonName, value: lastButtonValue } );}@@ -169,7 +215,7 @@ function asyncSubmitHandlerHelper( $form ) {}if ( $($form).attr('enctype') == 'multipart/form-data' ) {- var dummy = 0;+ let dummy = 0;}$.ajax({@@ -197,8 +243,8 @@ function asyncSubmitHandlerHelper( $form ) {// to use that to repopulate the content in the page.error: function (xhr, ajaxOptions, thrownError) {- var http_code = xhr.status;- var error_msg = thrownError;+ let http_code = xhr.status;+ let error_msg = thrownError;asyncUpdateData( $target, $mode, xhr.responseText, xhr );return false;}@@ -215,9 +261,9 @@ function asyncClickHandler(event) {event.preventDefault();event.stopPropagation();- var $anchor = $(this);+ let $anchor = $(this);- AN_handleHideShowIfNeeded( $anchor );+ handleHideShowIfNeeded( $anchor );// Special case for bootstrap dropdown menus that have data-async links// in them. Since we are suppressing the event propagation here, we@@ -228,13 +274,13 @@ function asyncClickHandler(event) {$('.an-async-hide').hide();$('.an-async-show').show();- var $target = getAsyncTarget( $anchor );- var $mode = $anchor.attr('data-mode');+ let $target = getAsyncTarget( $anchor );+ let $mode = $anchor.attr('data-mode');if ( ! $mode ) {$mode = 'insert';}- var url = $anchor.attr('href');+ let url = $anchor.attr('href');if ( $anchor.attr('data-params') ) {url += '?' + $anchor.attr('data-params');}@@ -257,8 +303,8 @@ function asyncClickHandler(event) {return false;},error: function (xhr, ajaxOptions, thrownError) {- var http_code = xhr.status;- var error_msg = thrownError;+ let http_code = xhr.status;+ let error_msg = thrownError;asyncUpdateData( $target, $mode, xhr.responseText, xhr );return false;}@@ -271,27 +317,27 @@ function asyncClickHandler(event) {//====================// For modal dialogs-var AN_lastModalId = 0;+let lastModalId = 0;-function AN_getNewModal() {- AN_lastModalId += 1;- var htmlId = "antinode-modal-"+AN_lastModalId;- var htmlString = '<div id="'+htmlId+'" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true"></div>';- var modalObj = $.parseHTML(htmlString);+function getNewModal() {+ lastModalId += 1;+ let htmlId = "antinode-modal-"+lastModalId;+ let htmlString = '<div id="'+htmlId+'" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true"></div>';+ let modalObj = $.parseHTML(htmlString);$('body').append( modalObj );return $(modalObj);};//====================-function AN_handleHideShowIfNeeded( $anchor ) {+function handleHideShowIfNeeded( $anchor ) {- var hide_selector = $anchor.attr('data-hide');+ let hide_selector = $anchor.attr('data-hide');if ( hide_selector ) {$(hide_selector).hide();}- var show_selector = $anchor.attr('data-show');+ let show_selector = $anchor.attr('data-show');if ( show_selector ) {$(show_selector).show();}@@ -303,11 +349,11 @@ function AN_handleHideShowIfNeeded( $anchor ) {// Common for POST and GET to find the target node for returned contentfunction getAsyncTarget( anchorNode ) {- var targetSelector = $(anchorNode).attr('data-async');+ let targetSelector = $(anchorNode).attr('data-async');// Special case to allow us to create a modal for the contentif ( targetSelector == "modal" ) {- return AN_getNewModal();+ return getNewModal();}return $(targetSelector);};@@ -316,10 +362,10 @@ function getAsyncTarget( anchorNode ) {//====================// The Async "loading" spinner-function AN_insertLoadingImage() {+function insertLoadingImage() {// N.B. The negative margins in the css should be half the width of the loading image.- var htmlString = '<div id="antinode-loader" style="display:none; position: absolute; top: 50%; left: 50%; margin-left: -64px; margin-top: -64px; z-index: 1020;"><img src="/static/img/antinode-loading.gif" alt="Page Loading Interstitial"/></div>';- var loadingObj = $.parseHTML(htmlString);+ let htmlString = '<div id="antinode-loader" style="display:none; position: absolute; top: 50%; left: 50%; margin-left: -64px; margin-top: -64px; z-index: 1020;"><img src="/static/img/antinode-loading.gif" alt="Page Loading Interstitial"/></div>';+ let loadingObj = $.parseHTML(htmlString);$('body').append( loadingObj );return;};@@ -341,7 +387,7 @@ function asyncUpdateData( $target, $mode, data, xhr ) {// patterns, and each of these are encoded as a JSON document with// corresponding content type.- var ct = xhr.getResponseHeader("content-type") || "";+ let ct = xhr.getResponseHeader("content-type") || "";if (ct.indexOf('html') > -1) {if ( $target ) {@@ -355,7 +401,7 @@ function asyncUpdateData( $target, $mode, data, xhr ) {}}if (ct.indexOf('json') > -1) {- var json = data;+ let json = data;// The response data might be text that has to be parsed into JSON// This raises an exception if data is already a JSON object.@@ -382,7 +428,7 @@ function asyncUpdateDataFromWebsocket( json ) {//====================function asyncUpdateDataFromJson( $target, $mode, json ) {-+// To allow the server to decide to redirect the page rather than// render async content.//@@ -391,7 +437,7 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {// If they were different, we would have to check for both here.//if ( 'location' in json ) {- var url = json['location'];+ let url = json['location'];this.document.location.href = url;return;}@@ -427,8 +473,8 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {// be replaced. This includes replacing the target element itself.//if ( 'replace' in json ) {- for ( var htmlId in json['replace'] ) {- var targetObj = $("#"+htmlId);+ for ( let htmlId in json['replace'] ) {+ let targetObj = $("#"+htmlId);targetObj.replaceWith( json['replace'][htmlId] ).show();handleNewContentAdded( targetObj );}@@ -438,8 +484,8 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {// be changed. This does not include the target element itself.//if ( 'insert' in json ) {- for ( var htmlId in json['insert'] ) {- var targetObj = $("#"+htmlId);+ for ( let htmlId in json['insert'] ) {+ let targetObj = $("#"+htmlId);targetObj.empty();targetObj.html( json['insert'][htmlId] ).show();handleNewContentAdded( targetObj );@@ -450,19 +496,34 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {// be appended. This add it as the last child of the target tag id.//if ( 'append' in json ) {- for ( var htmlId in json['append'] ) {- var targetObj = $("#"+htmlId);+ for ( let htmlId in json['append'] ) {+ let targetObj = $("#"+htmlId);targetObj.append( json['append'][htmlId] ).show();handleNewContentAdded( targetObj );}}+ // This entry should be a map from html ids to content that should+ // be appended. This add it as the last child of the target tag id.+ //+ if ( 'setAttributes' in json ) {+ for ( let htmlId in json['setAttributes'] ) {+ let targetObj = $("#"+htmlId);+ let attrMap = json['setAttributes'][htmlId];+ for ( let attrName in attrMap ) {+ let attrValue = attrMap[attrName];+ targetObj.attr( attrName, attrValue );+ handleNewContentAdded( targetObj );+ }+ }+ }+// In case any content with preserved scroll bars was refreshed.//afterAsyncRender();if ( 'modal' in json ) {- var targetObj = AN_getNewModal();+ let targetObj = getNewModal();targetObj.append( json['modal'] )showModal( targetObj );}@@ -476,11 +537,11 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {window.scrollTo(0, 0);}- if ( typeof AN_handlePostAsyncUpdate === "function") {- AN_handlePostAsyncUpdate();+ if ( typeof handlePostAsyncUpdate === "function") {+ handlePostAsyncUpdate();}};-+//====================function handleNewContentAdded( contentObj ) {doAutofocusIfNeeded( contentObj );@@ -503,11 +564,11 @@ function beforeAsyncCall( $node ) {//====================// Things that need to run after asynchronous content is rendered-var afterAsyncRenderFunctionList = [];+let afterAsyncRenderFunctionList = [];function afterAsyncRender() {- for ( var i = 0; i < afterAsyncRenderFunctionList.length; i++ ) {+ for ( let i = 0; i < afterAsyncRenderFunctionList.length; i++ ) {afterAsyncRenderFunctionList[i]();}restoreScrollBarPositions();@@ -524,7 +585,7 @@ function addAfterAsyncRenderFunction( func_name ) {// (for both form submissions and click events). Restoring them should come// after all async content is rendered.//-var scrollTopMap = {};+let scrollTopMap = {};function saveScrollBarPositions() {@@ -532,7 +593,7 @@ function saveScrollBarPositions() {// save the position.//$('.preserve-scroll-bar').each( function( index ) {- var id = $(this).attr('id');+ let id = $(this).attr('id');if ( id ) {scrollTopMap[id] = $(this).scrollTop();}@@ -541,7 +602,7 @@ function saveScrollBarPositions() {};function restoreScrollBarPositions() {- for ( var id in scrollTopMap ) {+ for ( let id in scrollTopMap ) {$('#'+id).scrollTop( scrollTopMap[id] );}};@@ -564,25 +625,25 @@ function restoreScrollBarPositions() {// properly updated to be null and force it to null so that all future// dialogs are not blocked.//-var AN_modalHideStartMs = null;+let modalHideStartMs = null;// When a modal show event happens while the hide event is active, we will// stash the modal object to be show in this global variable so that when// the hide event triggers, we know that we need to re-show the new modal// content.//-var AN_deferredModalShowObj = null;+let deferredModalShowObj = null;// This is the safety check to make sure missing hidden.bsmodal events do// not prevent modals from showing forever (or page refresh really).//function checkModalHideState() {- if ( AN_modalHideStartMs ) {- var d = new Date();- var nowMs = d.getTime();- var diffMs = nowMs - AN_modalHideStartMs;+ if ( modalHideStartMs ) {+ let d = new Date();+ let nowMs = d.getTime();+ let diffMs = nowMs - modalHideStartMs;if ( diffMs > 5000 ) {- AN_modalHideStartMs = null;+ modalHideStartMs = null;}}};@@ -591,7 +652,7 @@ function checkModalHideState() {// it is contained in a modal, then we will close the modal.//function hideModalIfNeeded( eventObj ) {- var modalObj = $(eventObj).closest('.modal');+ let modalObj = $(eventObj).closest('.modal');if ( modalObj.length > 0 ) {hideModal( modalObj.first() );}@@ -601,7 +662,7 @@ function hideModalIfNeeded( eventObj ) {// show it if it is contained in a modal.//function showModalIfNeeded( targetObj ) {- var modalObj = $(targetObj).closest('.modal');+ let modalObj = $(targetObj).closest('.modal');if ( modalObj.length > 0 ) {showModal( modalObj.first() );}@@ -612,8 +673,8 @@ function showModal( modalObj ) {return;}checkModalHideState();- if ( AN_modalHideStartMs ) {- AN_deferredModalShowObj = modalObj;+ if ( modalHideStartMs ) {+ deferredModalShowObj = modalObj;} else {$(modalObj).modal("show");}@@ -625,27 +686,27 @@ function hideModal( modalObj ) {}// Note that the globally registered hidden.bs.modal event will be// called once the hide is finished, and that will flip- // AN_modalHideStartMs to 'false'.+ // modalHideStartMs to 'false'.//- var d = new Date();- AN_modalHideStartMs = d.getTime();+ let d = new Date();+ modalHideStartMs = d.getTime();$(modalObj).modal("hide");};function handleModalHiddenEvent( modalObj ) {try {- AN_modalHideStartMs = null;- if ( AN_deferredModalShowObj ) {- showModal( AN_deferredModalShowObj );+ modalHideStartMs = null;+ if ( deferredModalShowObj ) {+ showModal( deferredModalShowObj );}} catch (e) {console.error('Problem handling modal hidden event');}finally {- AN_modalHideStartMs = null;- AN_deferredModalShowObj = null;+ modalHideStartMs = null;+ deferredModalShowObj = null;$(modalObj).remove();}};@@ -668,8 +729,8 @@ function asyncRedirect( $target, $mode, url ) {asyncUpdateData( $target, $mode, data, xhr );},error: function (xhr, ajaxOptions, thrownError) {- var http_code = xhr.status;- var error_msg = thrownError;+ let http_code = xhr.status;+ let error_msg = thrownError;asyncUpdateData( $target, $mode, xhr.responseText, xhr );}});@@ -690,7 +751,7 @@ $.ajaxSetup({return;}- var csrftoken = Cookies.get('csrftoken');+ let csrftoken = Cookies.get('csrftoken');if ( ! this.crossDomain ) {xhr.setRequestHeader("X-CSRFToken", csrftoken);}@@ -706,7 +767,7 @@ $.ajaxSetup({// will pass that along with the rest of the form contents.//function lastButtonClickHandler(event) {- var theForm = $(this).closest('form');+ let theForm = $(this).closest('form');$(theForm).data('lastSubmitButtonName', this.name);$(theForm).data('lastSubmitButtonValue', this.value);};@@ -728,7 +789,7 @@ jQuery(function($) {// Always want to show some visual indication that an async request// is in progress.//- AN_insertLoadingImage();+ insertLoadingImage();// These ensure that we'll pay attention to the special async attributes.//@@ -740,7 +801,7 @@ jQuery(function($) {// This is to support auto-submitting from SELECT elements asnychronously.//$('body').on('change', 'select[onchange-async]', function() {- var $form = $(this.form);+ let $form = $(this.form);return asyncSubmitHandlerHelper( $form );});@@ -755,9 +816,9 @@ jQuery(function($) {$('body').find('[autofocus]').focus();});- var initial_modal_content = $('#antinode-initial-modal');+ let initial_modal_content = $('#antinode-initial-modal');if ( initial_modal_content.length > 0 ) {- var targetObj = AN_getNewModal();+ let targetObj = getNewModal();targetObj.append( initial_modal_content )showModal( targetObj );}@@ -772,3 +833,4 @@ $(document)$('#antinode-loader').hide();});+})();diff --git a/src/hi/static/js/edit.js b/src/hi/static/js/edit.jsindex 7b691b06..86fee889 100644--- a/src/hi/static/js/edit.js+++ b/src/hi/static/js/edit.js@@ -85,7 +85,13 @@return;}displayElementInfo( 'SVG Target Element', enclosingSvgGroup );-++ const svgItemId = enclosingSvgGroup.attr('id');+ if ( ! svgItemId ) {+ return;+ }++ AN.get( `/edit/details/${svgItemId}` );}function handleDoubleClick( event ) {@@ -186,10 +192,21 @@if ( dragData == null ) {return;}+displayEventInfo( 'End Drag', event );displayElementInfo( 'Drag Element', dragData.element );updateDrag( event );++ let svgItemId = dragData.element.attr('id');+ data = {+ svg_x: dragData.elementSvgCenterPoint.x,+ svg_y: dragData.elementSvgCenterPoint.y,+ svg_scale: dragData.originalSvgScale,+ svg_rotate: dragData.originalSvgRotate+ };+ AN.post( `/edit/svg/position/${svgItemId}`, data );+dragData = null;}diff --git a/src/hi/templates/panes/main_default.html b/src/hi/templates/panes/main_default.htmlnew file mode 100644index 00000000..e3984e54--- /dev/null+++ b/src/hi/templates/panes/main_default.html@@ -0,0 +1,3 @@+<div class="" >+ TBD - DEFAULT MAIN CONTENT+</div>diff --git a/src/hi/templates/panes/side_panel.html b/src/hi/templates/panes/side_panel.htmlindex 4d22acdd..c5b314a7 100644--- a/src/hi/templates/panes/side_panel.html+++ b/src/hi/templates/panes/side_panel.html@@ -1,3 +1,6 @@+{% if request.is_editing %}+{% include "edit/panes/side.html" %}+{% else %}<div class="border-left" >SIDE PANEL@@ -16,3 +19,4 @@</div></div>+{% endif %}diff --git a/src/hi/view_parameters.py b/src/hi/view_parameters.pyindex 221e12ec..58760a77 100644--- a/src/hi/view_parameters.py+++ b/src/hi/view_parameters.py@@ -9,9 +9,11 @@ from .enums import EditModeclass ViewParameters:location_view_id : int = None- edit_mode : EditMode = False+ edit_mode : EditMode = Nonedef __post_init__(self):+ if self.edit_mode is None:+ self.edit_mode = EditMode.default()self._location_view = None # Lazy loadedreturn