Skip to content

Home Information - Your home, your data, organized.

Python

Should have been with last commit.

Anthony Cassandra128c357502b3
diff --git a/src/hi/apps/collection/edit/views.py b/src/hi/apps/collection/edit/views.py
index 046544a0..375c6bf6 100644
--- a/src/hi/apps/collection/edit/views.py
+++ b/src/hi/apps/collection/edit/views.py
@@ -39,10 +39,10 @@ class CollectionAddView( View ):
)
def post( self, request, *args, **kwargs ):
- name_form = forms.CollectionForm( request.POST )
- if not name_form.is_valid():
+ collection_form = forms.CollectionForm( request.POST )
+ if not collection_form.is_valid():
context = {
- 'collection_form': name_form,
+ 'collection_form': collection_form,
}
return antinode.modal_from_template(
request = request,
@@ -50,7 +50,7 @@ class CollectionAddView( View ):
context = context,
)
- cleaned_data = name_form.clean()
+ cleaned_data = collection_form.clean()
collection_type = CollectionType.from_name_safe( cleaned_data.get('collection_type') )
name = cleaned_data.get('name')
diff --git a/src/hi/apps/collection/models.py b/src/hi/apps/collection/models.py
index 8c4cec5b..a24595c7 100644
--- a/src/hi/apps/collection/models.py
+++ b/src/hi/apps/collection/models.py
@@ -1,6 +1,6 @@
from django.db import models
-from hi.apps.common.svg_models import SvgItem
+from hi.apps.common.svg_models import SvgIconItem
from hi.apps.entity.models import Entity
from hi.apps.location.models import (
Location,
@@ -116,8 +116,8 @@ class CollectionPosition( SvgPositionModel ):
]
@property
- def svg_item(self):
- return SvgItem(
+ def svg_icon_item(self) -> SvgIconItem:
+ return SvgIconItem(
html_id = f'hi-collection-{self.collection.id}',
template_name = self.collection.collection_type.svg_icon_template_name,
position_x = float( self.svg_x ),
diff --git a/src/hi/apps/common/svg_models.py b/src/hi/apps/common/svg_models.py
index fd32e29c..55f86e9b 100644
--- a/src/hi/apps/common/svg_models.py
+++ b/src/hi/apps/common/svg_models.py
@@ -68,12 +68,12 @@ class SvgPathStyle:
@dataclass
-class SvgItem:
+class SvgIconItem:
"""
- 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.
+ Encapsulates an iten to be inserted in a base SVG file as an icon. The
+ icon is defined as a sequence of drawing commands stored in a template
+ file. The shape that the icon drawing commands define can be
+ transformed to scale, roate and change its position as provided.
"""
# The SVG Transformations needed to move, scale and rotate SVG
@@ -89,14 +89,13 @@ class SvgItem:
# come before can impact things that come after.
# - Scaling does not always have to be taken into account.
- # Template name
html_id : str
template_name : str
bounding_box : SvgViewBox
position_x : float
position_y : float
- rotate : float = 0.0
- scale : float = 1.0
+ rotate : float
+ scale : float
@property
def transform_str(self):
@@ -123,3 +122,16 @@ class SvgItem:
if self.scale < 0.000001:
return 0
return ( self.position_y / self.scale ) - self.bounds_center_y
+
+
+@dataclass
+class SvgPathItem:
+ """
+ Encapsulates an item to be inserted in a base SVG file as a path. A path item is a
+ sequence of drawing commands defined in 'svg_path'.
+ """
+
+ html_id : str
+ svg_path : str
+ path_style : SvgPathStyle
+
diff --git a/src/hi/apps/edit/views.py b/src/hi/apps/edit/views.py
index e59c4a9e..3753b023 100644
--- a/src/hi/apps/edit/views.py
+++ b/src/hi/apps/edit/views.py
@@ -165,13 +165,13 @@ class EditSvgPositionView( View, EditViewMixin ):
svg_position_form = SvgPositionForm(
request.POST,
- item_html_id = svg_position_model.svg_item.html_id,
+ item_html_id = svg_position_model.svg_icon_item.html_id,
)
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
+ svg_icon_item = svg_position_model.svg_icon_item
context = {
'svg_position_form': svg_position_form,
}
@@ -182,8 +182,8 @@ class EditSvgPositionView( View, EditViewMixin ):
svg_position_form.content_html_id: content,
}
set_attributes_map = {
- svg_position_item.html_id: {
- 'transform': svg_position_item.transform_str,
+ svg_icon_item.html_id: {
+ 'transform': svg_icon_item.transform_str,
}
}
return antinode.response(
diff --git a/src/hi/apps/entity/edit/urls.py b/src/hi/apps/entity/edit/urls.py
index 816c071d..9ab7f58e 100644
--- a/src/hi/apps/entity/edit/urls.py
+++ b/src/hi/apps/entity/edit/urls.py
@@ -8,5 +8,10 @@ urlpatterns = [
re_path( r'^entity/details/(?P<entity_id>\d+)$',
views.EntityDetailsView.as_view(),
name='entity_edit_entity_details' ),
+
+ re_path( r'^entity/add$',
+ views.EntityAddView.as_view(),
+ name='entity_edit_entity_add' ),
+
]
diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.py
index 7a861478..5580fb60 100644
--- a/src/hi/apps/entity/edit/views.py
+++ b/src/hi/apps/entity/edit/views.py
@@ -1,10 +1,13 @@
import logging
+from django.shortcuts import redirect
from django.template.loader import get_template
+from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.generic import View
import hi.apps.common.antinode as antinode
+from hi.apps.entity.enums import EntityType
from hi.apps.entity.models import Entity, EntityPosition
from hi.apps.location.forms import SvgPositionForm
@@ -12,6 +15,8 @@ from hi.constants import DIVID
from hi.decorators import edit_required
from hi.views import bad_request_response, page_not_found_response
+from . import forms
+from .helpers import EntityEditHelpers
logger = logging.getLogger(__name__)
@@ -50,3 +55,48 @@ class EntityDetailsView( View ):
DIVID['EDIT_ITEM']: content,
},
)
+
+
+@method_decorator( edit_required, name='dispatch' )
+class EntityAddView( View ):
+
+ def get( self, request, *args, **kwargs ):
+ context = {
+ 'entity_form': forms.EntityForm(),
+ }
+ return antinode.modal_from_template(
+ request = request,
+ template_name = 'entity/edit/modals/entity_add.html',
+ context = context,
+ )
+
+ def post( self, request, *args, **kwargs ):
+ entity_form = forms.EntityForm( request.POST )
+ if not entity_form.is_valid():
+ context = {
+ 'entity_form': entity_form,
+ }
+ return antinode.modal_from_template(
+ request = request,
+ template_name = 'entity/edit/modals/entity_add.html',
+ context = context,
+ )
+
+ cleaned_data = entity_form.clean()
+ entity_type = EntityType.from_name_safe( cleaned_data.get('entity_type') )
+ name = cleaned_data.get('name')
+
+ try:
+ _ = EntityEditHelpers.create_entity(
+ request = request,
+ entity_type = entity_type,
+ name = name,
+ )
+ except ValueError as e:
+ return bad_request_response( request, message = str(e) )
+
+ redirect_url = reverse('home')
+ return redirect( redirect_url )
+
+
+
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index df1c14e5..f855f4e2 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -107,8 +107,8 @@ class EntityType(LabeledEnum):
def svg_path_style(self):
# TODO: Change this to be based on type
return SvgPathStyle(
- stroke_color = '888888',
- stroke_width = 1.0,
+ stroke_color = '#40f040',
+ stroke_width = 5.0,
fill_color = 'none',
)
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 4593592d..6e81612d 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -1,6 +1,6 @@
from django.db import models
-from hi.apps.common.svg_models import SvgItem
+from hi.apps.common.svg_models import SvgIconItem, SvgPathItem
from hi.apps.location.models import (
Location,
LocationView,
@@ -311,8 +311,8 @@ class EntityPosition( SvgPositionModel ):
]
@property
- def svg_item(self):
- return SvgItem(
+ def svg_icon_item(self) -> SvgIconItem:
+ return SvgIconItem(
html_id = f'hi-entity-{self.entity.id}',
template_name = self.entity.entity_type.svg_icon_template_name,
position_x = float( self.svg_x ),
@@ -361,7 +361,15 @@ class EntityPath( SvgPathModel ):
name = 'entity_path_location_entity', ),
]
-
+ @property
+ def svg_path_item(self) -> SvgPathItem:
+ return SvgPathItem(
+ html_id = f'hi-entity-{self.entity.id}',
+ svg_path = self.svg_path,
+ path_style = self.entity.entity_type.svg_path_style,
+ )
+
+
class EntityView(models.Model):
entity = models.ForeignKey(
diff --git a/src/hi/apps/location/forms.py b/src/hi/apps/location/forms.py
index eb6c17b2..4251a4ad 100644
--- a/src/hi/apps/location/forms.py
+++ b/src/hi/apps/location/forms.py
@@ -41,7 +41,7 @@ class SvgPositionForm(forms.Form):
def from_svg_position_model( cls, svg_position_model : SvgPositionModel ):
if svg_position_model:
return cls(
- item_html_id = svg_position_model.svg_item.html_id,
+ item_html_id = svg_position_model.svg_icon_item.html_id,
initial = {
'svg_x': svg_position_model.svg_x,
'svg_y': svg_position_model.svg_y,
@@ -50,7 +50,7 @@ class SvgPositionForm(forms.Form):
},
)
return cls(
- item_html_id = svg_position_model.svg_item.html_id,
+ item_html_id = svg_position_model.svg_icon_item.html_id,
initial = {
'svg_scale': Decimal( 1.0 ),
'svg_rotate': Decimal( 0.0 ),
diff --git a/src/hi/apps/location/models.py b/src/hi/apps/location/models.py
index 05fcbac8..5f05ad9b 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 SvgItem, SvgViewBox
+from hi.apps.common.svg_models import SvgIconItem, SvgPathItem, SvgViewBox
from .enums import LocationViewType
@@ -180,7 +180,7 @@ class SvgPositionModel(models.Model):
)
@property
- def svg_item(self) -> SvgItem:
+ def svg_icon_item(self) -> SvgIconItem:
raise NotImplementedError('Subclasses must implement this method.')
@@ -197,3 +197,7 @@ class SvgPathModel(models.Model):
'Path',
null = False, blank = False,
)
+
+ @property
+ def svg_path_item(self) -> SvgPathItem:
+ raise NotImplementedError('Subclasses must implement this method.')
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_add_remove_item.html b/src/hi/apps/location/templates/location/edit/panes/location_view_add_remove_item.html
index 606d475c..c30d277b 100644
--- a/src/hi/apps/location/templates/location/edit/panes/location_view_add_remove_item.html
+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_add_remove_item.html
@@ -1,6 +1,14 @@
<div class="">ADD/REMOVE</div>
-{% for entity_view_group in entity_view_group_list %}
+<div class="">
+ <a href="{% url 'entity_edit_entity_add' %}"
+ class="btn btn-success btn-control" role="button"
+ data-async="modal" >
+ NEW ITEM
+ </a>
+</div>
+
+ {% for entity_view_group in entity_view_group_list %}
<div class="">
<div class="">{{ entity_view_group.entity_type.label }}</div>
{% for entity_view_item in entity_view_group.item_list %}
diff --git a/src/hi/apps/location/templates/location/location_view.html b/src/hi/apps/location/templates/location/location_view.html
index bf25121e..33a7b8aa 100644
--- a/src/hi/apps/location/templates/location/location_view.html
+++ b/src/hi/apps/location/templates/location/location_view.html
@@ -8,14 +8,15 @@
{% include_media_template location_view_data.location_view.location.svg_filename %}
{% for entity_path in location_view_data.entity_paths %}
+ {% include "location/svg_path_item.html" with svg_path_item=entity_path.svg_path_item %}
{% endfor %}
{% for entity_position in location_view_data.entity_positions %}
- {% include "location/svg_position_item.html" with svg_position_item=entity_position.svg_item %}
+ {% include "location/svg_icon_item.html" with svg_icon_item=entity_position.svg_icon_item %}
{% endfor %}
{% for collection_position in location_view_data.collection_positions %}
- {% include "location/svg_position_item.html" with svg_position_item=collection_position.svg_item %}
+ {% include "location/svg_icon_item.html" with svg_icon_item=collection_position.svg_icon_item %}
{% endfor %}
</svg>
diff --git a/src/hi/apps/location/templates/location/svg_position_item.html b/src/hi/apps/location/templates/location/svg_position_item.html
deleted file mode 100644
index 2adeb42d..00000000
--- a/src/hi/apps/location/templates/location/svg_position_item.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<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/static/js/edit.js b/src/hi/static/js/edit.js
index 888c7a2e..9dc011f9 100644
--- a/src/hi/static/js/edit.js
+++ b/src/hi/static/js/edit.js
@@ -27,15 +27,20 @@
const DoubleClickDelayMs = 300;
const CursorMovementThreshold = 3;
- let gSvgActionState = SvgActionStateType.MOVE;
- let gSelectedElement = null;
+ let gSvgIconActionState = SvgActionStateType.MOVE;
+ let gSelectedIconSvgGroup = null;
+ let gSvgIconDragData = null;
+ let gSvgIconActionData = null;
+ let gSelectedPathSvgGroup = null;
+ let gSvgPathEditData = null;
+
let gClickStart = null;
let gClickTimeout = null;
let gLastMousePosition = { x: 0, y: 0 };
- let gSvgDragData = null;
- let gSvgActionData = null;
+
+ // For re-ordering items (buttons, lists, etc)
let gDraggedElement = null;
$(document).ready(function() {
@@ -152,6 +157,15 @@
}
function handleMouseDown( event ) {
+ if ( DEBUG ) {
+ displayEventInfo( 'Mouse down event: ', event );
+ displayElementInfo( 'Event target: ', $(event.target) );
+ }
+
+ if ( gSvgPathEditData ) {
+ return;
+ }
+
// Need to track start time to differentiate drag/scale/rotate actions from regular clicks.
gClickStart = {
x: event.clientX,
@@ -159,40 +173,49 @@
time: Date.now()
};
- if ( gSvgActionState == SvgActionStateType.MOVE ) {
- createDragData( event );
+ if ( gSvgIconActionState == SvgActionStateType.MOVE ) {
+
+ const enclosingSvgGroup = $(event.target).closest('g');
+ if ( enclosingSvgGroup.length < 1 ) {
+ return;
+ }
+ const svgDataType = $(enclosingSvgGroup).attr('data-type');
+ if ( svgDataType == 'svg-icon' ) {
+ createIconDragData( event, enclosingSvgGroup );
+ }
return;
}
- if ( gSvgActionData ) {
- if ( gSvgActionState == SvgActionStateType.SCALE ) {
- gSvgActionData.isScaling = true;
- } else if ( gSvgActionState == SvgActionStateType.ROTATE ) {
- gSvgActionData.isRotating = true;
+ if ( gSvgIconActionData ) {
+ if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
+ gSvgIconActionData.isScaling = true;
+ } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
+ gSvgIconActionData.isRotating = true;
}
}
}
function handleMouseMove( event ) {
+
const currentMousePosition = {
x: event.clientX,
y: event.clientY
};
- if ( gSvgDragData ) {
+ if ( gSvgIconDragData ) {
const distanceX = Math.abs( currentMousePosition.x - gClickStart.x );
const distanceY = Math.abs( currentMousePosition.y - gClickStart.y );
- if ( gSvgDragData.isDragging || ( distanceX > CursorMovementThreshold ) || ( distanceY > CursorMovementThreshold )) {
- gSvgDragData.isDragging = true;
+ if ( gSvgIconDragData.isDragging || ( distanceX > CursorMovementThreshold ) || ( distanceY > CursorMovementThreshold )) {
+ gSvgIconDragData.isDragging = true;
$(baseSvgSelector).attr( SvgActionStateAttrName, SvgActionStateType.MOVE);
updateDrag(event);
}
}
- else if ( gSvgActionData ) {
- if ( gSvgActionData.isScaling ) {
- actionScaleUpdate( currentMousePosition );
- } else if ( gSvgActionData.isRotating ) {
- actionRotateUpdate( currentMousePosition );
+ else if ( gSvgIconActionData ) {
+ if ( gSvgIconActionData.isScaling ) {
+ iconActionScaleUpdate( currentMousePosition );
+ } else if ( gSvgIconActionData.isRotating ) {
+ iconActionRotateUpdate( currentMousePosition );
}
}
@@ -200,27 +223,27 @@
}
function handleMouseUp( event ) {
- if ( gSvgDragData ) {
- if ( gSvgDragData.isDragging ) {
+ if ( gSvgIconDragData ) {
+ if ( gSvgIconDragData.isDragging ) {
endDrag( event );
$(baseSvgSelector).attr( SvgActionStateAttrName, '');
return;
}
$(baseSvgSelector).attr( SvgActionStateAttrName, '' );
- gSvgDragData = null;
+ gSvgIconDragData = null;
}
- else if ( gSvgActionData ) {
- if ( gSvgActionState == SvgActionStateType.SCALE ) {
- gSvgActionData.isScaling = false;
- actionScaleApply();
- } else if ( gSvgActionState == SvgActionStateType.ROTATE ) {
- gSvgActionData.isRotating = false;
- actionRotateApply();
+ else if ( gSvgIconActionData ) {
+ if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
+ gSvgIconActionData.isScaling = false;
+ iconActionScaleApply();
+ } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
+ gSvgIconActionData.isRotating = false;
+ iconActionRotateApply();
}
- gSvgActionState = SvgActionStateType.MOVE;
+ gSvgIconActionState = SvgActionStateType.MOVE;
$(baseSvgSelector).attr( SvgActionStateAttrName, '');
- gSvgActionData = null;
+ gSvgIconActionData = null;
}
if ( gClickTimeout ) {
@@ -242,6 +265,18 @@
}
function handleKeyDown( event ) {
+ if ( $(event.target).is('input[type="text"], textarea') ) {
+ return;
+ }
+ else if ( gSelectedIconSvgGroup ) {
+ handleSvgIconSelectedKeyDown( event );
+ }
+ else if ( gSvgPathEditData ) {
+ handleSvgPathEditKeyDown( event );
+ }
+ }
+
+ function handleSvgIconSelectedKeyDown( event ) {
const targetArea = $(locationViewAreaSelector);
const targetOffset = targetArea.offset();
const targetWidth = targetArea.outerWidth();
@@ -255,17 +290,17 @@
displayEventInfo( 'Key Down', event );
if ( event.key == ActionScaleKey ) {
- actionRotateAbort();
- actionScaleStart();
+ iconActionRotateAbort();
+ iconActionScaleStart();
} else if ( event.key == ActionRotateKey ) {
- actionScaleAbort();
- actionRotateStart();
+ iconActionScaleAbort();
+ iconActionRotateStart();
} else if ( event.key == 'Escape' ) {
- actionScaleAbort();
- actionRotateAbort();
- gSvgActionState = SvgActionStateType.MOVE;
+ iconActionScaleAbort();
+ iconActionRotateAbort();
+ gSvgIconActionState = SvgActionStateType.MOVE;
$(baseSvgSelector).attr( SvgActionStateAttrName, '');
} else {
@@ -284,28 +319,47 @@
function handleClick( event ) {
displayEventInfo( 'Click', event );
displayElementInfo( 'Event Target', $(event.target) );
-
+
const enclosingSvgGroup = $(event.target).closest('g');
- if ( enclosingSvgGroup.length < 1 ) {
- if ( DEBUG ) { console.log( 'NO TARGET' ); }
- gSelectedElement = null;
- $('.draggable').removeClass('highlighted');
- AN.get( `/edit/details` );
- return;
+ if ( enclosingSvgGroup.length > 0 ) {
+ displayElementInfo( 'SVG Target Element', enclosingSvgGroup );
+ const selectable = $(enclosingSvgGroup).hasClass('selectable');
+ const svgItemId = enclosingSvgGroup.attr('id');
+ if ( selectable && svgItemId ) {
+ handleSvgItemClick( event, enclosingSvgGroup );
+ return;
+ }
}
- displayElementInfo( 'SVG Target Element', enclosingSvgGroup );
- const svgItemId = enclosingSvgGroup.attr('id');
- if ( ! svgItemId ) {
+ if ( gSvgPathEditData ) {
+ handleSvgPathEditClick( event );
+ } else {
+ if ( DEBUG ) { console.log( 'No SVG group for click target' ); }
+ clearSelectedAll();
+ AN.get( `/edit/details` );
return;
}
+ }
- gSelectedElement = enclosingSvgGroup;
-
- $('.draggable').removeClass('highlighted');
- $(enclosingSvgGroup).addClass('highlighted');
+ function handleSvgItemClick( event, enclosingSvgGroup ) {
+ const svgItemId = $(enclosingSvgGroup).attr('id');
+ const svgDataType = $(enclosingSvgGroup).attr('data-type');
+ if ( svgDataType == 'svg-icon' ) {
+ clearSelectedAll();
+ gSelectedIconSvgGroup = enclosingSvgGroup;
+ $(enclosingSvgGroup).addClass('highlighted');
+ AN.get( `/edit/details/${svgItemId}` );
+
+ } else if ( svgDataType == 'svg-path' ) {
+ clearSelectedAll();
+ gSelectedPathSvgGroup = enclosingSvgGroup;
+ expandSvgPath( enclosingSvgGroup );
+ AN.get( `/edit/details/${svgItemId}` );
+
+ } else {
+ if ( DEBUG ) { console.log( `Unrecognized SVG group "${svgDataType}" for click target` ); }
+ }
- AN.get( `/edit/details/${svgItemId}` );
}
function handleDoubleClick( event ) {
@@ -313,14 +367,27 @@
handleClick( event );
}
- function createDragData( event ) {
- displayEventInfo( 'Create Drag', event );
- displayElementInfo( 'Event Target', $(event.target) );
+ function clearSelectedAll() {
+ clearSelectedSvgIcon();
+ clearSelectedSvgPath();
+ $('.selectable').removeClass('highlighted');
+ }
- const enclosingSvgGroup = $(event.target).closest('g');
- if ( enclosingSvgGroup.length < 1 ) {
- return;
+ function clearSelectedSvgIcon() {
+ if ( gSelectedIconSvgGroup ) {
+ $(gSelectedIconSvgGroup).removeClass('highlighted');
+ gSelectedIconSvgGroup = null;
}
+ }
+
+ function clearSelectedSvgPath() {
+ if ( gSelectedPathSvgGroup ) {
+ collapseSvgPath( gSelectedPathSvgGroup );
+ gSelectedPathSvgGroup = null;
+ }
+ }
+
+ function createIconDragData( event, enclosingSvgGroup ) {
const dragElement = enclosingSvgGroup;
displayElementInfo( 'Drag Element', dragElement );
@@ -337,7 +404,7 @@
y : (cursorSvgPoint.y / scale.y) - translate.y
};
- gSvgDragData = {
+ gSvgIconDragData = {
element: dragElement,
baseSvgElement: baseSvgElement,
cursorSvgOffset: cursorSvgOffset,
@@ -350,66 +417,66 @@
if ( DEBUG ) {
console.log( `Drag Start:
SVG Cursor Point: ( ${cursorSvgPoint.x}, ${cursorSvgPoint.y} ),
- SVG Cursor Offset: ( ${gSvgDragData.cursorSvgOffset.x}, ${gSvgDragData.cursorSvgOffset.y} ),
- SVG Center Point: ( ${gSvgDragData.elementSvgCenterPoint.x}, ${gSvgDragData.elementSvgCenterPoint.y} )`);
+ SVG Cursor Offset: ( ${gSvgIconDragData.cursorSvgOffset.x}, ${gSvgIconDragData.cursorSvgOffset.y} ),
+ SVG Center Point: ( ${gSvgIconDragData.elementSvgCenterPoint.x}, ${gSvgIconDragData.elementSvgCenterPoint.y} )`);
}
}
function updateDrag( event ) {
- if ( gSvgDragData == null ) {
+ if ( gSvgIconDragData == null ) {
return;
}
displayEventInfo( 'Update Drag', event );
- displayElementInfo( 'Drag Element', gSvgDragData.element );
+ displayElementInfo( 'Drag Element', gSvgIconDragData.element );
- let cursorSvgPoint = toSvgPoint( gSvgDragData.baseSvgElement, event.clientX, event.clientY );
+ let cursorSvgPoint = toSvgPoint( gSvgIconDragData.baseSvgElement, event.clientX, event.clientY );
- let scale = gSvgDragData.originalSvgScale;
- let rotate = gSvgDragData.originalSvgRotate;
+ let scale = gSvgIconDragData.originalSvgScale;
+ let rotate = gSvgIconDragData.originalSvgRotate;
- let newX = (cursorSvgPoint.x / scale.x) - gSvgDragData.cursorSvgOffset.x;
- let newY = (cursorSvgPoint.y / scale.y) - gSvgDragData.cursorSvgOffset.y;
+ let newX = (cursorSvgPoint.x / scale.x) - gSvgIconDragData.cursorSvgOffset.x;
+ let newY = (cursorSvgPoint.y / scale.y) - gSvgIconDragData.cursorSvgOffset.y;
- let transform = gSvgDragData.element.attr('transform') || '';
+ let transform = gSvgIconDragData.element.attr('transform') || '';
let newTransform = `scale(${scale.x} ${scale.y}) translate(${newX}, ${newY}) rotate(${rotate.angle}, ${rotate.cx}, ${rotate.cy})`;
- gSvgDragData.element.attr('transform', newTransform);
+ gSvgIconDragData.element.attr('transform', newTransform);
- gSvgDragData.elementSvgCenterPoint = getSvgCenterPoint( gSvgDragData.element, gSvgDragData.baseSvgElement );
+ gSvgIconDragData.elementSvgCenterPoint = getSvgCenterPoint( gSvgIconDragData.element, gSvgIconDragData.baseSvgElement );
if ( DEBUG ) {
console.log( `Drag Update:
SVG Cursor Point: ( ${cursorSvgPoint.x}, ${cursorSvgPoint.y} ),
TRANSFORM Result: ${newTransform},
- SVG Center Point: ( ${gSvgDragData.elementSvgCenterPoint.x}, ${gSvgDragData.elementSvgCenterPoint.y} )`);
+ SVG Center Point: ( ${gSvgIconDragData.elementSvgCenterPoint.x}, ${gSvgIconDragData.elementSvgCenterPoint.y} )`);
}
}
function endDrag( event ) {
- if ( gSvgDragData == null ) {
+ if ( gSvgIconDragData == null ) {
return;
}
displayEventInfo( 'End Drag', event );
- displayElementInfo( 'Drag Element', gSvgDragData.element );
+ displayElementInfo( 'Drag Element', gSvgIconDragData.element );
updateDrag( event );
- let svgItemId = gSvgDragData.element.attr('id');
+ let svgItemId = gSvgIconDragData.element.attr('id');
data = {
- svg_x: gSvgDragData.elementSvgCenterPoint.x,
- svg_y: gSvgDragData.elementSvgCenterPoint.y,
- svg_scale: gSvgDragData.originalSvgScale.x,
- svg_rotate: gSvgDragData.originalSvgRotate.angle
+ svg_x: gSvgIconDragData.elementSvgCenterPoint.x,
+ svg_y: gSvgIconDragData.elementSvgCenterPoint.y,
+ svg_scale: gSvgIconDragData.originalSvgScale.x,
+ svg_rotate: gSvgIconDragData.originalSvgRotate.angle
};
AN.post( `/edit/svg/position/${svgItemId}`, data );
- gSvgDragData = null;
+ gSvgIconDragData = null;
}
- function saveSvgPosition( element ) {
+ function saveIconSvgPosition( element ) {
let transform = element.attr('transform');
let { scale, translate, rotate } = getSvgTransformValues( transform );
@@ -427,13 +494,13 @@
AN.post( `/edit/svg/position/${svgItemId}`, data );
}
- function createEditActionData( actionState ) {
- if ( gSelectedElement ) {
- let transform = gSelectedElement.attr('transform');
+ function createIconEditActionData( actionState ) {
+ if ( gSelectedIconSvgGroup ) {
+ let transform = gSelectedIconSvgGroup.attr('transform');
let { scale, translate, rotate } = getSvgTransformValues( transform );
- gSvgActionData = {
- element: gSelectedElement,
+ gSvgIconActionData = {
+ element: gSelectedIconSvgGroup,
scaleStart: scale,
translateStart: translate,
rotateStart: rotate,
@@ -441,33 +508,33 @@
isRotating: false
};
- gSvgActionState = actionState;
+ gSvgIconActionState = actionState;
$(baseSvgSelector).attr( SvgActionStateAttrName, actionState );
}
}
- function revertAction( element ) {
- if ( gSvgActionData ) {
- setSvgTransformAttr( gSvgActionData.element,
- gSvgActionData.scaleStart,
- gSvgActionData.translateStart,
- gSvgActionData.rotateStart );
- gSvgActionData = null;
+ function revertIconAction( element ) {
+ if ( gSvgIconActionData ) {
+ setSvgTransformAttr( gSvgIconActionData.element,
+ gSvgIconActionData.scaleStart,
+ gSvgIconActionData.translateStart,
+ gSvgIconActionData.rotateStart );
+ gSvgIconActionData = null;
}
}
- function actionScaleStart() {
- createEditActionData( SvgActionStateType.SCALE );
+ function iconActionScaleStart() {
+ createIconEditActionData( SvgActionStateType.SCALE );
}
- function actionScaleUpdate( currentMousePosition ) {
+ function iconActionScaleUpdate( currentMousePosition ) {
- let center = getScreenCenterPoint( gSvgActionData.element );
+ let center = getScreenCenterPoint( gSvgIconActionData.element );
let scaleFactor = getScaleFactor( center.x, center.y,
gLastMousePosition.x, gLastMousePosition.y,
currentMousePosition.x, currentMousePosition.y );
- let transform = gSvgActionData.element.attr('transform');
+ let transform = gSvgIconActionData.element.attr('transform');
let { scale, translate, rotate } = getSvgTransformValues( transform );
const newScale = {
@@ -484,57 +551,43 @@
Scale = ${scale.x}, T = ${translate.x}, R = ${rotate.angle}` );
}
- setSvgTransformAttr( gSvgActionData.element, newScale, translate, rotate );
+ setSvgTransformAttr( gSvgIconActionData.element, newScale, translate, rotate );
}
- function getScaleFactor( centerX, centerY, startX, startY, endX, endY ) {
-
- const startDistance = Math.sqrt( Math.pow(startX - centerX, 2) + Math.pow(startY - centerY, 2) );
- const endDistance = Math.sqrt( Math.pow(endX - centerX, 2) + Math.pow(endY - centerY, 2) );
-
- let scaleFactor = 1;
- if (endDistance > startDistance) {
- scaleFactor = 1 + (endDistance - startDistance) / 100;
- } else if (endDistance < startDistance) {
- scaleFactor = 1 - (startDistance - endDistance) / 100;
- }
- return scaleFactor;
- }
-
- function actionScaleApply() {
+ function iconActionScaleApply() {
if ( DEBUG ) { console.log( 'Scale Apply' ); }
- saveSvgPosition( gSvgActionData.element );
+ saveIconSvgPosition( gSvgIconActionData.element );
}
- function actionScaleAbort() {
- if ( gSvgActionState != SvgActionStateType.SCALE ) {
+ function iconActionScaleAbort() {
+ if ( gSvgIconActionState != SvgActionStateType.SCALE ) {
return;
}
- revertAction();
+ revertIconAction();
}
- function actionRotateStart() {
- createEditActionData( SvgActionStateType.ROTATE );
+ function iconActionRotateStart() {
+ createIconEditActionData( SvgActionStateType.ROTATE );
}
- function actionRotateUpdate( currentMousePosition ) {
+ function iconActionRotateUpdate( currentMousePosition ) {
if ( DEBUG ) { console.log( 'Rotate Update' ); }
- center = getScreenCenterPoint( gSvgActionData.element );
+ center = getScreenCenterPoint( gSvgIconActionData.element );
- let deltaAngle = getRotationAngle( center.x, center.y,
+ let deltaAngle = getIconRotationAngle( center.x, center.y,
gLastMousePosition.x, gLastMousePosition.y,
currentMousePosition.x, currentMousePosition.y );
- let transform = gSvgActionData.element.attr('transform');
+ let transform = gSvgIconActionData.element.attr('transform');
let { scale, translate, rotate } = getSvgTransformValues( transform );
rotate.angle += deltaAngle;
rotate.angle = normalizeAngle( rotate.angle );
- setSvgTransformAttr( gSvgActionData.element, scale, translate, rotate );
+ setSvgTransformAttr( gSvgIconActionData.element, scale, translate, rotate );
}
- function getRotationAngle( centerX, centerY, startX, startY, endX, endY ) {
+ function getIconRotationAngle( centerX, centerY, startX, startY, endX, endY ) {
const startVectorX = startX - centerX;
const startVectorY = startY - centerY;
@@ -560,15 +613,15 @@
}
- function actionRotateApply() {
- saveSvgPosition( gSvgActionData.element );
+ function iconActionRotateApply() {
+ saveIconSvgPosition( gSvgIconActionData.element );
}
- function actionRotateAbort() {
- if ( gSvgActionState != SvgActionStateType.ROTATE ) {
+ function iconActionRotateAbort() {
+ if ( gSvgIconActionState != SvgActionStateType.ROTATE ) {
return;
}
- revertAction();
+ revertIconAction();
}
function getScreenCenterPoint( element ) {
@@ -683,9 +736,279 @@
return { x, y, width, height };
}
+ function getScaleFactor( centerX, centerY, startX, startY, endX, endY ) {
+
+ const startDistance = Math.sqrt( Math.pow(startX - centerX, 2) + Math.pow(startY - centerY, 2) );
+ const endDistance = Math.sqrt( Math.pow(endX - centerX, 2) + Math.pow(endY - centerY, 2) );
+
+ let scaleFactor = 1;
+ if (endDistance > startDistance) {
+ scaleFactor = 1 + (endDistance - startDistance) / 100;
+ } else if (endDistance < startDistance) {
+ scaleFactor = 1 - (startDistance - endDistance) / 100;
+ }
+ return scaleFactor;
+ }
+
function normalizeAngle(angle) {
return (angle % 360 + 360) % 360;
}
+
+
+ /* ========================================
+ SVG PATH EDITING
+
+ - Two types of paths: closed (with ending 'Z') and open.
+ - The type is determined by the initial path and not editable.
+ - An open path must have at least two control points.
+ - A closed path must have at least 3 control points.
+ - The behavior of adding to the path depends on its type.
+ - An open path gets extended when adding.
+ - A closed path has its lines subdivided when adding.
+ - Adding is relative to the last selected item.
+ - You can select a line or a control point.
+ */
+
+ function handleSvgPathEditClick( event ) {
+
+
+
+ /*
+ If on control point, set as current and highlight.
+ If on line, set as current and highlight.
+ If in space, create a new control point, extend line from "end" control point, set as current
+ if not end, then floating control point.
+ */
+
+ console.log( 'PATH EDIT CLICK' );
+ }
+
+ function handleSvgPathEditKeyDown( event ) {
+
+ /*
+ DEL/x = if control, delete and connecting lines (must always have two control points
+ 'a/i' = add control, extend line from end of selected. If closed, subdivide line connected to current
+ */
+
+ console.log( 'PATH EDIT KEYDOWN' );
+ }
+
+
+ function expandSvgPath( pathSvgGroup ) {
+ if ( DEBUG ) { console.log( 'Expand SVG Path', pathSvgGroup ); }
+
+ pathSvgGroup.hide();
+
+ gSvgPathEditData = {
+ proxyPaths: [],
+ selectedControlPoint: null,
+ selectedLine: null
+ };
+
+ const baseSvgElement = $(baseSvgSelector)[0];
+ let svgPathElement = $(pathSvgGroup).find('path');
+ const pathData = svgPathElement.attr('d');
+ const segments = pathData.match(/[ML][^MLZ]+|Z/g);
+ if ( DEBUG ) { console.log('Path segments', segments ); }
+
+ /* Algorithm Description:
+
+ - We first create all the control points in the first loop.
+ - This builds the data structures to handle possibly having multiple line segments.
+ - We then iterate though all the line segments.
+ - We'll create all the lines and handlers for "interior" lines/points.
+ - Finally, we deal with the special cases of the first and last control points.
+ - First and last control points have only one line unless it is a closed path.
+ - If it is a closed path, we also need to add an extra line to close the figure.
+ */
+
+ // Create all control points.
+ let currentProxyPath = null;
+ for ( let i = 0; i < segments.length; i++ ) {
+
+ let command = segments[i].charAt(0); // M or L or Z
+ let coords = segments[i].substring(1).trim().split(/[\s,]+/).map(Number);
+
+ if (command === 'M') {
+ currentProxyPath = {
+ pathType: 'open',
+ controlPoints: []
+ };
+ gSvgPathEditData.proxyPaths.push( currentProxyPath );
+
+ let controlPoint = createProxyPathControlPoint( baseSvgElement, coords[0], coords[1] );
+ currentProxyPath.controlPoints.push( controlPoint );
+
+ } else if (command === 'L' && currentProxyPath ) {
+ let controlPoint = createProxyPathControlPoint( baseSvgElement, coords[0], coords[1] );
+ currentProxyPath.controlPoints.push( controlPoint );
+
+ } else if (command === 'Z' && currentProxyPath ) {
+ currentProxyPath.pathType = 'closed';
+ currentProxyPath = null;
+ }
+ }
+
+ // Paths can have multiple segments
+ for ( let i = 0; i < gSvgPathEditData.proxyPaths.length; i++ ) {
+ let proxyPath = gSvgPathEditData.proxyPaths[i];
+
+ if ( DEBUG ) { console.log( 'Proxy path: ', proxyPath ); }
+
+ // Create interior lines and control point handlers with bookkeeping for first/last edge cases.
+ let previousControlPoint = null;
+ let firstLine = null;
+ let previousLine = null;
+ for ( let j = 0; j < proxyPath.controlPoints.length; j++ ) {
+ let currentControlPoint = proxyPath.controlPoints[j];
+
+ if ( previousControlPoint ) {
+ const x1 = parseFloat(previousControlPoint.getAttribute('cx'));
+ const y1 = parseFloat(previousControlPoint.getAttribute('cy'));
+ const x2 = parseFloat(currentControlPoint.getAttribute('cx'));
+ const y2 = parseFloat(currentControlPoint.getAttribute('cy'));
+ let currentLine = createProxyPathLine( baseSvgElement, x1, y1, x2, y2 );
+
+ if ( previousLine ) {
+ addControlPointEventHandler( previousControlPoint, previousLine, currentLine );
+ }
+ if ( ! firstLine ) {
+ firstLine = currentLine;
+ }
+ previousLine = currentLine;
+ }
+
+ previousControlPoint = currentControlPoint;
+ }
+
+ // Degerate cases of zero or one point and no lines.
+ if ( proxyPath.controlPoints.length < 2 ) {
+ addControlPointEventHandler( previousControlPoint, null, null );
+ continue;
+ }
+
+ // Edge cases for first and last points.
+ let firstControlPoint = proxyPath.controlPoints[0];
+ let lastControlPoint = proxyPath.controlPoints[proxyPath.controlPoints.length -1];
+
+ if ( proxyPath.pathType == 'open' ) {
+ addControlPointEventHandler( firstControlPoint, null, firstLine );
+ addControlPointEventHandler( lastControlPoint, previousLine, null );
+ } else {
+ const x1 = parseFloat(lastControlPoint.getAttribute('cx'));
+ const y1 = parseFloat(lastControlPoint.getAttribute('cy'));
+ const x2 = parseFloat(firstControlPoint.getAttribute('cx'));
+ const y2 = parseFloat(firstControlPoint.getAttribute('cy'));
+ let closureLine = createProxyPathLine( baseSvgElement, x1, y1, x2, y2 );
+ addControlPointEventHandler( firstControlPoint, closureLine, firstLine );
+ addControlPointEventHandler( lastControlPoint, previousLine, closureLine );
+ }
+ }
+
+ }
+
+ function createProxyPathControlPoint( svg, cx, cy ) {
+ const controlPoint = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
+ controlPoint.setAttribute('cx', cx);
+ controlPoint.setAttribute('cy', cy);
+ controlPoint.setAttribute('r', 25);
+ controlPoint.setAttribute('fill', 'red');
+ controlPoint.setAttribute('class', 'draggable');
+ controlPoint.setAttribute('vector-effect', 'non-scaling-stroke');
+ svg.appendChild(controlPoint);
+ return controlPoint;
+ }
+
+ function createProxyPathLine( svg, x1, y1, x2, y2 ) {
+ const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
+ line.setAttribute('x1', x1);
+ line.setAttribute('y1', y1);
+ line.setAttribute('x2', x2);
+ line.setAttribute('y2', y2);
+ line.setAttribute('stroke', 'red');
+ line.setAttribute('stroke-width', '5');
+ line.setAttribute('vector-effect', 'non-scaling-stroke');
+ svg.appendChild(line);
+ return line;
+ }
+
+ function addControlPointEventHandler( controlPoint, beforeLine, afterLine ) {
+
+ // Drag logic for the control point
+ controlPoint.addEventListener('mousedown', function(e) {
+ e.preventDefault();
+ const offsetX = e.clientX - parseFloat(controlPoint.getAttribute('cx'));
+ const offsetY = e.clientY - parseFloat(controlPoint.getAttribute('cy'));
+
+ function onMouseMove(e) {
+ const newCx = e.clientX - offsetX;
+ const newCy = e.clientY - offsetY;
+ controlPoint.setAttribute('cx', newCx);
+ controlPoint.setAttribute('cy', newCy);
+
+ // Update the line endpoints based on the control point being dragged
+ if ( beforeLine ) {
+ beforeLine.setAttribute('x2', newCx);
+ beforeLine.setAttribute('y2', newCy);
+ }
+ if ( afterLine ) {
+ afterLine.setAttribute('x1', newCx);
+ afterLine.setAttribute('y1', newCy);
+ }
+ }
+
+ function onMouseUp() {
+ document.removeEventListener('mousemove', onMouseMove);
+ document.removeEventListener('mouseup', onMouseUp);
+ }
+
+ document.addEventListener('mousemove', onMouseMove);
+ document.addEventListener('mouseup', onMouseUp);
+ });
+ }
+
+ function collapseSvgPath( pathSvgGroup ) {
+ if ( DEBUG ) { console.log( 'Collapse SVG Path', pathSvgGroup ); }
+
+ // zzz adjust path
+
+
+ /*
+ const svg = document.getElementById('my-svg');
+ const lines = svg.querySelectorAll('line');
+ let newPathData = '';
+
+ // Loop through lines and recombine them into a single path
+ lines.forEach(line => {
+ const x1 = line.getAttribute('x1');
+ const y1 = line.getAttribute('y1');
+ const x2 = line.getAttribute('x2');
+ const y2 = line.getAttribute('y2');
+ newPathData += `M ${x1} ${y1} L ${x2} ${y2} `;
+ svg.removeChild(line); // Remove each line after processing
+ });
+
+ controlPoints.forEach(point => svg.removeChild(point)); // Remove control points
+
+ if (selectedPath) {
+ selectedPath.setAttribute('d', newPathData.trim()); // Set the new path data
+ selectedPath.style.display = ''; // Make the path visible again
+ }
+*/
+
+
+ pathSvgGroup.show();
+
+
+
+ gSvgPathEditData = null;
+ }
+
+
+
+
+
+
function displayEventInfo( label, event ) {
if ( ! DEBUG ) { return; }