Home Information - Your home, your data, organized.
Python
Code cleanup after basic SVG element drag-n-drop working.
Anthony Cassandracfb85f2ad05a
diff --git a/src/hi/apps/collection/enums.py b/src/hi/apps/collection/enums.pyindex 9b6a9e3c..4d50b00d 100644--- a/src/hi/apps/collection/enums.py+++ b/src/hi/apps/collection/enums.py@@ -12,16 +12,29 @@ class CollectionType(LabeledEnum):return cls.DEFAULT@property- def svg_bounding_box(self):+ def svg_icon_bounding_box(self):"""- This defines the bounding box of the SVG, which we need to properly- position, rotate and scale the icon.+ This defines the bounding box or extents of the SVG drawing commands,+ which we need in order to properly position, rotate and scale the icon.+ We need to be ab le to comute the center, since the adjustable location+ is defining the center point of the icon."""# TODO: Change this after creating initial iconsreturn SvgViewBox( x = 0, y = 0, width = 32, height = 32 )@propertydef svg_icon_template_name(self):+ """+ A template containing SVG drawing commands for the icon. It should not+ contain the <svg> tag as this template will be inserted as part of+ the basr location SVG. This file can be one or more SVG drawing+ commands. A <g> tag will be automatically provided to wrap the+ content os this since that <g> wrapper also need to define the SVG+ transformations needed to properly position, scale and rotate the+ icon. For entities with states, this should also use the "hi-state"+ attribute in order to adjust its appearance (via CSS) based on its+ state.+ """# TODO: Change this after creating initial icons## return f'templates/entity/svg/type.{self.name.lower()}.svg'diff --git a/src/hi/apps/collection/models.py b/src/hi/apps/collection/models.pyindex 3d9291fe..757fd0fe 100644--- a/src/hi/apps/collection/models.py+++ b/src/hi/apps/collection/models.py@@ -112,7 +112,7 @@ class CollectionPosition( SvgPositionModel ):template_name = self.collection.collection_type.svg_icon_template_name,position_x = float( self.svg_x ),position_y = float( self.svg_y ),- bounding_box = self.collection.collection_type.svg_bounding_box,+ bounding_box = self.collection.collection_type.svg_icon_bounding_box,rotate = float( self.svg_rotation ),scale = float( self.svg_scale ),)diff --git a/src/hi/apps/common/svg_models.py b/src/hi/apps/common/svg_models.pyindex 9200a688..e5ad3493 100644--- a/src/hi/apps/common/svg_models.py+++ b/src/hi/apps/common/svg_models.py@@ -69,6 +69,27 @@ class SvgPathStyle:@dataclassclass SvgItem:+ """+ Encapsulates an iten to be inserted in a base SVG file. A item is a+ sequence of drawing commands stored in a template. The shape that the+ drawing commands define can be transformed to scale, roate and chnage+ its position as provided.+ """++ # The SVG Transformations needed to move, scale and rotate SVG+ # fragments are tricky and inconsistent.+ #+ # - Scaling changes the coordinate system.+ # - 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.+ # - 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.++ # Template namehtml_id : strtemplate_name : strbounding_box : SvgViewBoxdiff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex 91ec74ee..dcca6710 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -67,16 +67,29 @@ class EntityType(LabeledEnum):return cls.OTHER@property- def svg_bounding_box(self):+ def svg_icon_bounding_box(self):"""- This defines the bounding box of the SVG, which we need to properly- position, rotate and scale the icon.+ This defines the bounding box or extents of the SVG drawing commands,+ which we need in order to properly position, rotate and scale the icon.+ We need to be ab le to comute the center, since the adjustable location+ is defining the center point of the icon."""# TODO: Change this after creating initial iconsreturn SvgViewBox( x = 0, y = 0, width = 32, height = 32 )@propertydef svg_icon_template_name(self):+ """+ A template containing SVG drawing commands for the icon. It should not+ contain the <svg> tag as this template will be inserted as part of+ the basr location SVG. This file can be one or more SVG drawing+ commands. A <g> tag will be automatically provided to wrap the+ content os this since that <g> wrapper also need to define the SVG+ transformations needed to properly position, scale and rotate the+ icon. For entities with states, this should also use the "hi-state"+ attribute in order to adjust its appearance (via CSS) based on its+ state.+ """# TODO: Change this after creating initial icons## return f'templates/entity/svg/type.{self.name.lower()}.svg'diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.pyindex ca8c56e1..8d51d8f8 100644--- a/src/hi/apps/entity/models.py+++ b/src/hi/apps/entity/models.py@@ -314,7 +314,7 @@ class EntityPosition( SvgPositionModel ):template_name = self.entity.entity_type.svg_icon_template_name,position_x = float( self.svg_x ),position_y = float( self.svg_y ),- bounding_box = self.entity.entity_type.svg_bounding_box,+ bounding_box = self.entity.entity_type.svg_icon_bounding_box,# rotate = float( self.svg_rotation ),# scale = float( self.svg_scale ),rotate = 0,diff --git a/src/hi/static/js/edit.js b/src/hi/static/js/edit.jsindex e2dbaa3f..7b691b06 100644--- a/src/hi/static/js/edit.js+++ b/src/hi/static/js/edit.js@@ -1,4 +1,6 @@(function() {+ const DEBUG = true;+window.Hi = window.Hi || {};const HiEdit = {@@ -9,77 +11,160 @@window.Hi.edit = HiEdit;- const DEBUG = true;- const clickThreshold = 300; // Adjust the threshold as needed (in milliseconds)+ const locationViewAreaSelector = '#hi-location-view-main';+ const baseSvgSelector = '#hi-location-view-main > svg';++ let clickStart = null;+ let clickTimeout = null;+ const doubleClickDelayMs = 300;++ let isDragging = false;let dragData = null;-- $(document).on('mousedown', function(event) {- startDrag( event );-- });- $(document).on('mousemove', function(event) {- updateDrag( event );- });- $(document).on('mouseup', function() {- endDrag( event );- });- $(document).on('keydown', function(event) {- console.log(`Key down: ${event.key}`);- });- $(document).on('keyup', function(event) {- console.log(`Key up: ${event.key}`);+ const dragThreshold = 3;++ $(document).ready(function() {+ $(document).on('mousedown', locationViewAreaSelector, function(event) {+ isDragging = false;+ clickStart = {+ x: event.clientX,+ y: event.clientY,+ time: Date.now()+ }+ createDragData( event );+ });+ $(document).on('mousemove', locationViewAreaSelector, function(event) {+ if ( ! dragData ) {+ return;+ }+ const distanceX = Math.abs( event.clientX - clickStart.x );+ const distanceY = Math.abs( event.clientY - clickStart.y );++ if ( isDragging || ( distanceX > dragThreshold ) || ( distanceY > dragThreshold )) {+ isDragging = true;+ updateDrag(event);+ }+ });+ $(document).on('mouseup', locationViewAreaSelector, function(event) {+ if ( isDragging ) {+ endDrag( event );+ return;+ }+ dragData = null;++ if ( clickTimeout ) {+ const clickEndTime = Date.now();+ const elapsedTime = clickEndTime - clickStart.time;+ console.log( `Click Elapsed: ${elapsedTime}` );+ clearTimeout( clickTimeout );+ clickTimeout = null;+ handleDoubleClick( event );+ } else {+ clickTimeout = setTimeout(() => {+ const clickEndTime = Date.now();+ const elapsedTime = clickEndTime - clickStart.time;+ console.log( `Click Elapsed: ${elapsedTime}` );+ handleClick( event );+ clickTimeout = null;+ }, doubleClickDelayMs );+ }+ });+ $(document).on('keydown', locationViewAreaSelector, function(event) {+ handleKeyDown( event );+ });+ $(document).on('keyup', locationViewAreaSelector, function(event) {+ handleKeyUp( event );+ });});- function startDrag( event ) {- displayEventInfo( event );+ function handleClick( event ) {+ displayEventInfo( 'Click', event );+ displayElementInfo( 'Event Target', $(event.target) );++ const enclosingSvgGroup = $(event.target).closest('g');+ if ( enclosingSvgGroup.length < 1 ) {+ return;+ }+ displayElementInfo( 'SVG Target Element', enclosingSvgGroup );++ }++ function handleDoubleClick( event ) {+ displayEventInfo( 'Double Click', event );displayElementInfo( 'Event Target', $(event.target) );const enclosingSvgGroup = $(event.target).closest('g');- if ( enclosingSvgGroup.length > 0 ) {- dragData = {};- dragData.element = enclosingSvgGroup;- displayElementInfo( 'Drag Element', dragData.element );+ if ( enclosingSvgGroup.length < 1 ) {+ return;+ }+ displayElementInfo( 'SVG Target Element', enclosingSvgGroup );- dragData.startTime = Date.now();+ }++ function handleKeyDown( event ) {+ displayEventInfo( 'Key Down', event );+ }++ function handleKeyUp( event ) {+ displayEventInfo( 'Key Up', event );+ }++ function createDragData( event ) {+ displayEventInfo( 'Create Drag', event );+ displayElementInfo( 'Event Target', $(event.target) );++ const enclosingSvgGroup = $(event.target).closest('g');+ if ( enclosingSvgGroup.length < 1 ) {+ return;+ }- dragData.baseSvg = $('#hi-location-view-main > svg');- displayElementInfo( 'Base SVG', dragData.baseSvg );+ const dragElement = enclosingSvgGroup;+ displayElementInfo( 'Drag Element', dragElement );++ const baseSvgElement = $(baseSvgSelector);+ displayElementInfo( 'Base SVG', baseSvgElement );- let transform = dragData.element.attr('transform') || '';- let { scale, translate, rotate } = getTransformValues( transform );- let svgPoint = toSvgPoint( dragData.baseSvg[0], event.clientX, event.clientY );+ let transform = dragElement.attr('transform') || '';+ let { scale, translate, rotate } = getTransformValues( transform );+ let cursorSvgPoint = toSvgPoint( baseSvgElement, event.clientX, event.clientY );- dragData.offsetSvgX = (svgPoint.x / scale.x) - translate.x;- dragData.offsetSvgY = (svgPoint.y / scale.y) - translate.y;+ const cursorSvgOffset = {+ x : (cursorSvgPoint.x / scale.x) - translate.x,+ y : (cursorSvgPoint.y / scale.y) - translate.y+ }- dragData.svgCenter = getSvgCenterPoint( dragData.element, dragData.baseSvg[0] );+ dragData = {+ element: dragElement,+ baseSvgElement: baseSvgElement,+ cursorSvgOffset: cursorSvgOffset,+ elementSvgCenterPoint: getSvgCenterPoint( dragElement, baseSvgElement ),+ originalSvgScale: scale,+ originalSvgRotate: rotate,- dragData.scale = scale;- dragData.rotate = rotate;-- if ( DEBUG ) {- console.log( `Drag Start:- SVG Cursor Point: ( ${svgPoint.x}, ${svgPoint.y} ),- SVG Cursor Offset: ( ${dragData.offsetSvgX}, ${dragData.offsetSvgY} ),- SVG Center Point: ( ${dragData.svgCenter.x}, ${dragData.svgCenter.y} )`);- }}++ if ( DEBUG ) {+ console.log( `Drag Start:+ SVG Cursor Point: ( ${cursorSvgPoint.x}, ${cursorSvgPoint.y} ),+ SVG Cursor Offset: ( ${dragData.cursorSvgOffset.x}, ${dragData.cursorSvgOffset.y} ),+ SVG Center Point: ( ${dragData.elementSvgCenterPoint.x}, ${dragData.elementSvgCenterPoint.y} )`);+ }+}function updateDrag( event ) {if ( dragData == null ) {return;}- displayEventInfo( event );+ displayEventInfo( 'Update Drag', event );displayElementInfo( 'Drag Element', dragData.element );- let svgPoint = toSvgPoint( dragData.baseSvg[0], event.clientX, event.clientY );+ let cursorSvgPoint = toSvgPoint( dragData.baseSvgElement, event.clientX, event.clientY );- let scale = dragData.scale;- let rotate = dragData.rotate+ let scale = dragData.originalSvgScale;+ let rotate = dragData.originalSvgRotate- let newX = (svgPoint.x / scale.x) - dragData.offsetSvgX;- let newY = (svgPoint.y / scale.y) - dragData.offsetSvgY;+ let newX = (cursorSvgPoint.x / scale.x) - dragData.cursorSvgOffset.x;+ let newY = (cursorSvgPoint.y / scale.y) - dragData.cursorSvgOffset.y;let transform = dragData.element.attr('transform') || '';@@ -87,13 +172,13 @@dragData.element.attr('transform', newTransform);- dragData.svgCenter = getSvgCenterPoint( dragData.element, dragData.baseSvg[0] );+ dragData.elementSvgCenterPoint = getSvgCenterPoint( dragData.element, dragData.baseSvgElement );if ( DEBUG ) {console.log( `Drag Update:- SVG Cursor Point: ( ${svgPoint.x}, ${svgPoint.y} ),+ SVG Cursor Point: ( ${cursorSvgPoint.x}, ${cursorSvgPoint.y} ),TRANSFORM Result: ${newTransform},- SVG Center Point: ( ${dragData.svgCenter.x}, ${dragData.svgCenter.y} )`);+ SVG Center Point: ( ${dragData.elementSvgCenterPoint.x}, ${dragData.elementSvgCenterPoint.y} )`);}}@@ -102,16 +187,9 @@return;}- displayEventInfo( event );+ displayEventInfo( 'End Drag', event );displayElementInfo( 'Drag Element', dragData.element );-updateDrag( event );-- let dragEndTime = Date.now();- const elapsedTime = dragEndTime - dragData.startTime;- if (elapsedTime <= clickThreshold) {- console.log( `CLICK: ${elapsedTime}` );- }dragData = null;}@@ -173,20 +251,21 @@}function toSvgPoint( svgElement, clientX, clientY) {- let point = svgElement.createSVGPoint();+ let point = svgElement[0].createSVGPoint();point.x = clientX;point.y = clientY;- return point.matrixTransform( svgElement.getScreenCTM().inverse());+ return point.matrixTransform( svgElement[0].getScreenCTM().inverse());}- function displayEventInfo( event ) {+ function displayEventInfo( label, event ) {if ( ! DEBUG ) { return; }if ( ! event ) {console.log( 'No element to display info for.' );return;}- console.log( `Event:+ console.log( `${label} Event:Type: ${event.type},+ Key: ${event.key},Pos: ( ${event.clientX}, ${event.clientY} )` );}