Skip to content

Home Information - Your home, your data, organized.

Python

Location Editing Modal Redesign (#137)

Tony C4305280c147a
diff --git a/docs/dev/backend/attribute-editing-integration-guide.md b/docs/dev/backend/attribute-editing-integration-guide.md
new file mode 100644
index 00000000..7f86d78e
--- /dev/null
+++ b/docs/dev/backend/attribute-editing-integration-guide.md
@@ -0,0 +1,529 @@
+# Attribute Editing Integration Guide
+
+A comprehensive guide for integrating new models with the generic attribute editing system using the AttributeEditContext pattern.
+
+## Overview
+
+The AttributeEditContext pattern provides a standardized way to implement attribute editing across different model types (Entity, Location, etc.) while maintaining ~95% code reuse through generic templates and handlers.
+
+### Benefits
+
+- **Code Reuse**: Share 95% of template and handler logic across model types
+- **Consistency**: Standardized UI/UX across all attribute editing interfaces
+- **Type Safety**: Clean abstraction with type-safe owner-specific access
+- **Maintainability**: Single source of truth for attribute editing functionality
+- **Extensibility**: Easy to add new model types following established patterns
+
+### When to Use
+
+Use this pattern when you have:
+- A model that owns attributes (like Entity owns EntityAttribute)
+- Need for modal-based attribute editing with file upload support
+- Requirements for attribute history and restore functionality
+- Desire for consistent editing UI across different model types
+
+## Prerequisites
+
+### Required Model Structure
+
+Your implementation needs:
+
+1. **Owner Model**: The main model (e.g., `Entity`, `Location`)
+ ```python
+ class YourModel(models.Model):
+ name = models.CharField(max_length=255)
+ # other fields...
+ ```
+
+2. **Attribute Model**: Related attribute model (e.g., `EntityAttribute`, `LocationAttribute`)
+ ```python
+ class YourModelAttribute(models.Model):
+ your_model = models.ForeignKey(YourModel, related_name='attributes')
+ name = models.CharField(max_length=255)
+ value = models.TextField()
+ value_type_str = models.CharField(max_length=50)
+ # history tracking fields...
+ ```
+
+3. **Template Directory Structure**:
+ ```
+ hi/apps/yourapp/templates/yourapp/
+ ├── modals/
+ │ └── yourmodel_edit.html
+ └── panes/
+ └── yourmodel_edit_content_body.html
+ ```
+
+## Step-by-Step Implementation
+
+### Step 1: Create AttributeEditContext Subclass
+
+Create `yourapp/yourmodel_attribute_edit_context.py`:
+
+```python
+"""
+YourModelAttributeEditContext - YourModel-specific context for attribute editing templates.
+"""
+from typing import Any
+from hi.apps.attribute.edit_context import AttributeEditContext
+from .models import YourModel
+
+class YourModelAttributeEditContext(AttributeEditContext):
+ """YourModel-specific context provider for attribute editing templates."""
+
+ def __init__(self, your_model: YourModel) -> None:
+ """Initialize context for YourModel attribute editing."""
+ super().__init__(your_model, 'yourmodel') # 'yourmodel' must match URL patterns
+
+ @property
+ def your_model(self) -> YourModel:
+ """Get the YourModel instance (typed accessor)."""
+ return self.owner
+```
+
+### Step 2: Create Form Handler Class
+
+Create `yourapp/yourmodel_edit_form_handler.py`:
+
+```python
+"""
+YourModelEditFormHandler - Handles form creation, validation, and processing.
+"""
+import logging
+from typing import Any, Dict, List, Optional, Tuple
+from django.db import transaction
+from django.http import HttpRequest
+from django.db.models import QuerySet
+
+from hi.apps.attribute.enums import AttributeValueType
+from .models import YourModel, YourModelAttribute
+from .forms import YourModelForm, YourModelAttributeRegularFormSet
+from .yourmodel_attribute_edit_context import YourModelAttributeEditContext
+
+logger = logging.getLogger(__name__)
+
+class YourModelEditFormHandler:
+ """Handles form creation, validation, and processing for yourmodel editing."""
+
+ @staticmethod
+ def get_formset_prefix(your_model: YourModel) -> str:
+ """Get the formset prefix for regular attributes formset."""
+ return f'yourmodel-{your_model.id}'
+
+ def create_yourmodel_forms(
+ self,
+ your_model: YourModel,
+ form_data: Optional[Dict[str, Any]] = None
+ ) -> Tuple[YourModelForm, QuerySet[YourModelAttribute], YourModelAttributeRegularFormSet]:
+ """Create yourmodel forms used by both initial rendering and fragment updates."""
+
+ # Create yourmodel form
+ yourmodel_form = YourModelForm(form_data, instance=your_model)
+
+ # Get file attributes for display
+ file_attributes = your_model.attributes.filter(
+ value_type_str=str(AttributeValueType.FILE)
+ ).order_by('id')
+
+ # Regular attributes formset (excludes FILE attributes)
+ regular_attributes_formset = YourModelAttributeRegularFormSet(
+ form_data,
+ instance=your_model,
+ prefix=self.get_formset_prefix(your_model),
+ form_kwargs={'show_as_editable': True}
+ )
+
+ return yourmodel_form, file_attributes, regular_attributes_formset
+
+ def validate_forms(
+ self,
+ yourmodel_form: YourModelForm,
+ regular_attributes_formset: YourModelAttributeRegularFormSet
+ ) -> bool:
+ """Validate yourmodel form and attributes formset."""
+ return yourmodel_form.is_valid() and regular_attributes_formset.is_valid()
+
+ def save_forms(
+ self,
+ yourmodel_form: YourModelForm,
+ regular_attributes_formset: YourModelAttributeRegularFormSet,
+ request: HttpRequest,
+ your_model: YourModel
+ ) -> None:
+ """Save forms and process file operations within a transaction."""
+ with transaction.atomic():
+ yourmodel_form.save()
+ regular_attributes_formset.save()
+ # Add any custom file processing here
+
+ def create_initial_context(self, your_model: YourModel) -> Dict[str, Any]:
+ """Create initial template context for yourmodel editing form."""
+ yourmodel_form, file_attributes, regular_attributes_formset = self.create_yourmodel_forms(your_model)
+
+ # Create the attribute edit context for template generalization
+ attr_context = YourModelAttributeEditContext(your_model)
+
+ # Build context with both old and new patterns for compatibility
+ context = {
+ 'your_model': your_model,
+ 'yourmodel_form': yourmodel_form,
+ 'owner_form': yourmodel_form, # Generic alias for templates
+ 'file_attributes': file_attributes,
+ 'regular_attributes_formset': regular_attributes_formset,
+ }
+
+ # Merge in the context variables from AttributeEditContext
+ context.update(attr_context.to_template_context())
+
+ return context
+```
+
+### Step 3: Create Response Renderer Class
+
+Create `yourapp/yourmodel_edit_response_renderer.py`:
+
+```python
+"""
+YourModelEditResponseRenderer - Handles template rendering and response generation.
+"""
+from typing import Any, Dict, Optional, Tuple
+from django.db.models import QuerySet
+from django.http import HttpRequest
+from django.template.loader import render_to_string
+from django.urls import reverse
+
+import hi.apps.common.antinode as antinode
+from hi.constants import DIVID
+from .yourmodel_edit_form_handler import YourModelEditFormHandler
+from .models import YourModel, YourModelAttribute
+from .forms import YourModelForm, YourModelAttributeRegularFormSet
+from .yourmodel_attribute_edit_context import YourModelAttributeEditContext
+
+class YourModelEditResponseRenderer:
+ """Handles template rendering and response generation for yourmodel editing."""
+
+ def __init__(self) -> None:
+ self.form_handler = YourModelEditFormHandler()
+
+ def build_template_context(
+ self,
+ your_model: YourModel,
+ yourmodel_form: YourModelForm,
+ file_attributes: QuerySet[YourModelAttribute],
+ regular_attributes_formset: YourModelAttributeRegularFormSet,
+ success_message: Optional[str] = None,
+ error_message: Optional[str] = None,
+ has_errors: bool = False
+ ) -> Dict[str, Any]:
+ """Build context dictionary for template rendering."""
+
+ # Create the attribute edit context for template generalization
+ attr_context = YourModelAttributeEditContext(your_model)
+
+ # Build context with both old and new patterns for compatibility
+ context = {
+ 'your_model': your_model,
+ 'yourmodel_form': yourmodel_form,
+ 'owner_form': yourmodel_form, # Generic alias for templates
+ 'file_attributes': file_attributes,
+ 'regular_attributes_formset': regular_attributes_formset,
+ 'success_message': success_message,
+ 'error_message': error_message,
+ 'has_errors': has_errors,
+ }
+
+ # Merge in the context variables from AttributeEditContext
+ context.update(attr_context.to_template_context())
+
+ return context
+
+ def render_success_response(
+ self,
+ request: HttpRequest,
+ your_model: YourModel
+ ) -> 'antinode.Response':
+ """Render success response using antinode helpers."""
+ # Re-render content with fresh forms
+ yourmodel_form, file_attributes, regular_attributes_formset = self.form_handler.create_yourmodel_forms(your_model)
+
+ context = self.build_template_context(
+ your_model, yourmodel_form, file_attributes, regular_attributes_formset,
+ success_message="Changes saved successfully"
+ )
+
+ # Render content body
+ content_body = render_to_string('yourapp/panes/yourmodel_edit_content_body.html', context, request=request)
+
+ # Render upload form
+ file_upload_url = reverse('yourmodel_attribute_upload', kwargs={'yourmodel_id': your_model.id})
+ upload_form = render_to_string(
+ 'attribute/components/upload_form.html',
+ {'file_upload_url': file_upload_url},
+ request=request
+ )
+
+ return antinode.response(
+ insert_map={
+ DIVID['ATTR_V2_CONTENT']: content_body,
+ DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']: upload_form
+ }
+ )
+```
+
+### Step 4: Create Content Body Template
+
+Create `yourapp/templates/yourapp/panes/yourmodel_edit_content_body.html`:
+
+```django
+{% extends "attribute/components/edit_content_body.html" %}
+{% comment %}
+YourModel V2 Content Body Fragment
+Extends the generic attribute edit content body with yourmodel-specific field layout.
+{% endcomment %}
+
+{% block owner_fields %}
+<!-- YourModel-specific fields for modal editing -->
+<div class="row">
+ <div class="col-md-12">
+ <div class="form-group mb-0">
+ <small class="text-muted">Name</small>
+ <input type="text"
+ id="{{ owner_form.name.id_for_label }}"
+ name="{{ owner_form.name.html_name }}"
+ value="{{ owner_form.name.value|default:'' }}"
+ class="form-control form-control-sm"
+ {% if owner_form.name.field.required %}required{% endif %}>
+ {% if owner_form.name.errors %}
+ <div class="invalid-feedback d-block">
+ {{ owner_form.name.errors }}
+ </div>
+ {% endif %}
+ </div>
+ </div>
+ <!-- Add additional yourmodel-specific fields here -->
+</div>
+{% endblock %}
+```
+
+### Step 5: Update Views to Use Handler/Renderer Pattern
+
+Update your main edit view:
+
+```python
+from .yourmodel_edit_form_handler import YourModelEditFormHandler
+from .yourmodel_edit_response_renderer import YourModelEditResponseRenderer
+
+class YourModelEditView(HiModalView, YourModelViewMixin):
+ """YourModel attribute editing modal with redesigned interface."""
+
+ def get_template_name(self) -> str:
+ return 'yourapp/modals/yourmodel_edit.html'
+
+ def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
+ your_model = self.get_yourmodel(request, *args, **kwargs)
+
+ # Delegate form creation and context building to handler
+ form_handler = YourModelEditFormHandler()
+ context = form_handler.create_initial_context(your_model)
+
+ return self.modal_response(request, context)
+
+ def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
+ your_model = self.get_yourmodel(request, *args, **kwargs)
+
+ # Delegate form handling to specialized handlers
+ form_handler = YourModelEditFormHandler()
+ renderer = YourModelEditResponseRenderer()
+
+ # Create forms with POST data
+ yourmodel_form, file_attributes, regular_attributes_formset = form_handler.create_yourmodel_forms(
+ your_model, request.POST
+ )
+
+ if form_handler.validate_forms(yourmodel_form, regular_attributes_formset):
+ # Save forms and process files
+ form_handler.save_forms(yourmodel_form, regular_attributes_formset, request, your_model)
+
+ # Return success response
+ return renderer.render_success_response(request, your_model)
+ else:
+ # Return error response
+ return renderer.render_error_response(request, your_model, yourmodel_form, regular_attributes_formset)
+```
+
+### Step 6: Update Upload and History Views
+
+Update your upload view:
+
+```python
+def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
+ your_model = self.get_yourmodel(request, *args, **kwargs)
+ # ... upload form validation ...
+
+ if upload_form.is_valid():
+ with transaction.atomic():
+ upload_form.save()
+
+ # Render new file card HTML to append to file grid
+ attr_context = YourModelAttributeEditContext(your_model)
+ context = {'attribute': yourmodel_attribute, 'your_model': your_model}
+ context.update(attr_context.to_template_context())
+
+ file_card_html = render_to_string(
+ 'attribute/components/file_card.html',
+ context,
+ request=request
+ )
+ # ... return response ...
+```
+
+Update your history inline view:
+
+```python
+class YourModelAttributeHistoryInlineView(BaseAttributeHistoryView):
+ """View for displaying YourModelAttribute history inline within the edit modal."""
+
+ def get_template_name(self):
+ return 'attribute/components/attribute_history_inline.html'
+
+ def get(self, request: HttpRequest, yourmodel_id: int, attribute_id: int, *args, **kwargs) -> HttpResponse:
+ # ... validation and history retrieval ...
+
+ # Create the attribute edit context for template generalization
+ attr_context = YourModelAttributeEditContext(attribute.your_model)
+
+ context = {
+ 'your_model': attribute.your_model,
+ 'attribute': attribute,
+ 'history_records': history_records,
+ 'history_url_name': self.get_history_url_name(),
+ 'restore_url_name': self.get_restore_url_name(),
+ }
+
+ # Merge in the context variables from AttributeEditContext
+ context.update(attr_context.to_template_context())
+
+ return render(request, self.get_template_name(), context)
+```
+
+### Step 7: Add URL Patterns
+
+Add URL patterns for history and restore functionality:
+
+```python
+# yourapp/urls.py
+urlpatterns = [
+ # ... existing patterns ...
+
+ # Attribute history and restore (inline)
+ re_path(r'^yourmodel/(?P<yourmodel_id>\d+)/attribute/(?P<attribute_id>\d+)/history/inline/$',
+ views.YourModelAttributeHistoryInlineView.as_view(),
+ name='yourmodel_attribute_history_inline'),
+
+ re_path(r'^yourmodel/(?P<yourmodel_id>\d+)/attribute/(?P<attribute_id>\d+)/restore/inline/(?P<history_id>\d+)/$',
+ views.YourModelAttributeRestoreInlineView.as_view(),
+ name='yourmodel_attribute_restore_inline'),
+
+ # File upload
+ re_path(r'^yourmodel/(?P<yourmodel_id>\d+)/attribute/upload/$',
+ views.YourModelAttributeUploadView.as_view(),
+ name='yourmodel_attribute_upload'),
+]
+```
+
+## Template Integration Details
+
+### Using Template Filters and Tags
+
+The generic templates use specialized filters and tags for dynamic functionality. Make sure to load them:
+
+```django
+{% load attribute_extras %}
+
+<!-- Dynamic URL generation -->
+{% attr_history_url attr_context attribute.id %}
+{% attr_restore_url attr_context attribute.id history_record.pk %}
+
+<!-- Dynamic field names -->
+{{ attr_context|file_title_field_name:attribute.id }}
+{{ attr_context|history_target_id:attribute.id }}
+```
+
+### Customizing Owner Fields
+
+Override the `owner_fields` block to define model-specific fields:
+
+```django
+{% block owner_fields %}
+<div class="row">
+ <div class="col-md-8">
+ <!-- Name field -->
+ </div>
+ <div class="col-md-4">
+ <!-- Type or other field -->
+ </div>
+</div>
+{% endblock %}
+```
+
+## Testing Integration
+
+### Required Test Coverage
+
+1. **Form Handler Tests**: Test form creation, validation, and saving
+2. **Response Renderer Tests**: Test template context building and response generation
+3. **View Tests**: Test GET/POST behavior with proper context
+4. **Template Tests**: Verify template rendering with context variables
+5. **Upload/History Tests**: Test file upload and history functionality
+
+### Example Test Structure
+
+```python
+class TestYourModelEditFormHandler(BaseTestCase):
+ def test_create_initial_context(self):
+ """Test that initial context includes AttributeEditContext variables."""
+ your_model = self.create_test_yourmodel()
+ form_handler = YourModelEditFormHandler()
+
+ context = form_handler.create_initial_context(your_model)
+
+ self.assertIn('attr_context', context)
+ self.assertIn('owner_form', context)
+ self.assertEqual(context['your_model'], your_model)
+```
+
+## Troubleshooting
+
+### Common Issues
+
+1. **Template Not Found**: Ensure template paths match your app structure
+2. **Context Variables Missing**: Verify `attr_context.to_template_context()` is called
+3. **URL Pattern Mismatch**: Check that `owner_type` in context matches URL pattern names
+4. **Form Validation Errors**: Ensure formset prefixes are unique and consistent
+
+### Template Debugging
+
+Add this to templates for debugging context variables:
+
+```django
+{% comment %}DEBUG: Available context variables{% endcomment %}
+{% if debug %}
+ <pre>{{ attr_context|pprint }}</pre>
+ <pre>Owner ID: {{ attr_context.owner_id }}</pre>
+ <pre>Owner Type: {{ attr_context.owner_type }}</pre>
+{% endif %}
+```
+
+### Context Variable Verification
+
+Verify these key context variables are available:
+
+- `attr_context` - The AttributeEditContext instance
+- `owner_form` - Generic alias for model-specific form
+- `your_model` - Your specific model instance
+- `file_attributes` - QuerySet of file attributes
+- `regular_attributes_formset` - Formset for non-file attributes
+
+## Conclusion
+
+Following this guide ensures your new model integrates seamlessly with the established attribute editing patterns, providing consistent UI/UX while maintaining code reuse and type safety. The pattern scales well and provides a solid foundation for future attribute-owning models.
\ No newline at end of file
diff --git a/docs/dev/backend/backend-guidelines.md b/docs/dev/backend/backend-guidelines.md
index 975d4071..f478eff4 100644
--- a/docs/dev/backend/backend-guidelines.md
+++ b/docs/dev/backend/backend-guidelines.md
@@ -369,6 +369,7 @@ To add a new tab section to the Configuration UI:
- Async/sync patterns: [Async Sync Patterns](async-sync-patterns.md)
- Integration patterns: [Integration Guidelines](../integrations/integration-guidelines.md)
- Testing: [Testing Guidelines](../testing/testing-guidelines.md)
+- Generic Attributes [Attribute Editing Integration Guide](./attribute-editing-integration-guide.md)
## Debugging
diff --git a/docs/dev/testing/testing-guidelines.md b/docs/dev/testing/testing-guidelines.md
index 31a61035..c8ac53e9 100644
--- a/docs/dev/testing/testing-guidelines.md
+++ b/docs/dev/testing/testing-guidelines.md
@@ -176,3 +176,4 @@ For complete usage details, see: `hi.testing.dev_injection.DevInjectionManager`
- Simulator testing: [Test Simulator](test-simulator.md)
- Coding standards: [Coding Standards](../shared/coding-standards.md)
- View testing: [Frontend Guidelines](../frontend/frontend-guidelines.md#view-testing)
+- Examples: [Test Case Examples](./test-examples)
diff --git a/src/hi/apps/attribute/edit_context.py b/src/hi/apps/attribute/edit_context.py
new file mode 100644
index 00000000..830f61c3
--- /dev/null
+++ b/src/hi/apps/attribute/edit_context.py
@@ -0,0 +1,105 @@
+"""
+AttributeEditContext - Generic context provider for attribute editing templates.
+
+This class provides a clean abstraction that allows attribute editing templates
+to work generically across different owner types (Entity, Location, etc.) while
+maintaining type safety and clear URL routing patterns.
+"""
+from typing import Any, Dict
+
+
+class AttributeEditContext:
+ """
+ Context provider for attribute editing templates that abstracts away
+ owner-specific details (entity vs location vs future types).
+
+ This allows templates to be completely generic while providing
+ type-safe access to owner information, URLs, and DOM identifiers.
+ """
+
+ def __init__(self, owner: Any, owner_type: str) -> None:
+ """
+ Initialize context for attribute editing.
+
+ Args:
+ owner: The model instance that owns the attributes (Entity, Location, etc.)
+ owner_type: String identifier for the owner type ("entity", "location", etc.)
+ """
+ self.owner = owner
+ self.owner_type = owner_type.lower()
+
+ @property
+ def owner_id(self) -> int:
+ """Get the owner's primary key ID."""
+ return self.owner.id
+
+ @property
+ def owner_id_param_name(self) -> str:
+ """Get the URL parameter name for owner ID (e.g., 'entity_id', 'location_id')."""
+ return f'{self.owner_type}_id'
+
+ @property
+ def owner_name(self) -> str:
+ """Get the owner's display name."""
+ return self.owner.name
+
+ @property
+ def history_url_name(self) -> str:
+ """Get the URL name for inline attribute history view."""
+ return f'{self.owner_type}_attribute_history_inline'
+
+ @property
+ def restore_url_name(self) -> str:
+ """Get the URL name for inline attribute restore view."""
+ return f'{self.owner_type}_attribute_restore_inline'
+
+ def history_target_id(self, attribute_id: int) -> str:
+ """
+ Get the DOM ID for the attribute history container.
+
+ Args:
+ attribute_id: The attribute's primary key
+
+ Returns:
+ str: DOM ID for the history container
+ """
+ return f'hi-{self.owner_type}-attr-history-{self.owner_id}-{attribute_id}'
+
+ def history_toggle_id(self, attribute_id: int) -> str:
+ """
+ Get the DOM ID for the history toggle/collapse target.
+
+ Args:
+ attribute_id: The attribute's primary key
+
+ Returns:
+ str: DOM ID for the history toggle target
+ """
+ return f'history-extra-{self.owner_id}-{attribute_id}'
+
+ def file_title_field_name(self, attribute_id: int) -> str:
+ """
+ Get the form field name for file title editing.
+
+ Args:
+ attribute_id: The attribute's primary key
+
+ Returns:
+ str: Form field name for file title
+ """
+ return f'file_title_{self.owner_id}_{attribute_id}'
+
+ def to_template_context(self) -> Dict[str, Any]:
+ """
+ Convert this context to a dictionary suitable for template rendering.
+
+ Returns:
+ dict: Template context variables
+ """
+ return {
+ 'attr_context': self,
+ # Provide the owner under both generic and specific names for compatibility
+ 'owner': self.owner,
+ self.owner_type: self.owner, # e.g., 'entity': self.owner or 'location': self.owner
+ }
+
diff --git a/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html b/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
index b87e3a2e..852edaab 100644
--- a/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
+++ b/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
@@ -14,7 +14,7 @@ Compact history display that loads into attribute cards
</small>
<button type="button"
class="btn btn-sm btn-link p-0 attr-v2-history-close"
- onclick="$('#hi-entity-attr-history-{{ entity.id }}-{{ attribute.id }}').empty();"
+ onclick="$('#{{ attr_context|history_target_id:attribute.id }}').empty();"
title="Close history">
{% icon "close" size="sm" %}
</button>
@@ -31,7 +31,7 @@ Compact history display that loads into attribute cards
<div class="attr-v2-history-records">
{% for record in history_records %}
<div class="attr-v2-history-record {% if forloop.counter > 3 %}collapse{% endif %}"
- {% if forloop.counter > 3 %}id="history-extra-{{ entity.id }}-{{ attribute.id }}"{% endif %}>
+ {% if forloop.counter > 3 %}id="{{ attr_context|history_toggle_id:attribute.id }}"{% endif %}>
<div class="d-flex justify-content-between align-items-center">
<div>
<small class="text-muted">{{ record.changed_datetime|naturaltime }}</small>
@@ -39,7 +39,7 @@ Compact history display that loads into attribute cards
</div>
<div>
{% if record.value != attribute.value %}
- <a href="{% url restore_url_name entity_id=entity.id attribute_id=attribute.id history_id=record.pk %}"
+ <a href="{% attr_restore_url attr_context attribute.id record.pk %}"
data-async="true"
data-stay-in-modal="true"
class="btn btn-xs btn-outline-primary"
@@ -60,7 +60,7 @@ Compact history display that loads into attribute cards
<button type="button"
class="btn btn-sm btn-link p-0"
data-toggle="collapse"
- data-target="#history-extra-{{ entity.id }}-{{ attribute.id }}"
+ data-target="#{{ attr_context|history_toggle_id:attribute.id }}"
onclick="$(this).find('.show-more-text, .show-less-text').toggle();">
<small class="show-more-text">Show {{ history_records|length|add:'-3' }} more...</small>
<small class="show-less-text" style="display: none;">Show less</small>
diff --git a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
new file mode 100644
index 00000000..e22ca74b
--- /dev/null
+++ b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
@@ -0,0 +1,109 @@
+{% load icons %}
+{% comment %}
+Generic V2 Content Body Fragment
+Contains the main content area - used by both initial load and antinode updates
+Includes: owner info (when provided), action bar, and scrollable content
+
+This template works generically for Entity, Location, and future attribute-owning models
+by using the AttributeEditContext pattern.
+{% endcomment %}
+
+<!-- Sticky Panel: Owner Info + Action Bar (always visible) -->
+<div class="attr-v2-sticky-panel">
+ <!-- Basic Owner Information (minimal) - only if owner_form provided -->
+ {% if owner_form %}
+ <div class="attr-v2-entity-info">
+ {% block basic_info %}
+ <div class="attr-v2-basic-info">
+ {% block owner_fields %}
+ <!-- Subclasses should override this block to provide owner-specific fields -->
+ <div class="row">
+ <div class="col-md-12">
+ <div class="form-group mb-0">
+ <small class="text-muted">Name</small>
+ <input type="text"
+ id="{{ owner_form.name.id_for_label }}"
+ name="{{ owner_form.name.html_name }}"
+ value="{{ owner_form.name.value|default:'' }}"
+ class="form-control form-control-sm"
+ {% if owner_form.name.field.required %}required{% endif %}>
+ {% if owner_form.name.errors %}
+ <div class="invalid-feedback d-block">
+ {{ owner_form.name.errors }}
+ </div>
+ {% endif %}
+ </div>
+ </div>
+ </div>
+ {% endblock %}
+ </div>
+ {% endblock %}
+ </div>
+ {% endif %}
+
+ <!-- Action Bar -->
+ <div class="attr-v2-action-bar">
+ <div class="attr-v2-action-bar-content">
+ <div>
+ <button id="{{ DIVID.ATTR_V2_UPDATE_BTN }}"
+ type="submit"
+ class="btn btn-primary"
+ name="action"
+ value="update">
+ {% icon "save" size="sm" css_class="hi-icon-left" %}UPDATE
+ </button>
+ <span id="{{ DIVID.ATTR_V2_DIRTY_MESSAGE }}" class="attr-v2-dirty-message ml-3"></span>
+ <span id="{{ DIVID.ATTR_V2_STATUS_MSG }}" class="attr-v2-status-message ml-2">
+ {% if success_message %}
+ <span class="text-success">{{ success_message }}</span>
+ {% elif error_message %}
+ <span class="text-danger">{{ error_message }}</span>
+ {% if non_field_errors %}
+ {% for error in non_field_errors %}
+ <br><small class="text-danger">{{ error }}</small>
+ {% endfor %}
+ {% endif %}
+ {% endif %}
+ </span>
+ </div>
+
+ <div class="attr-v2-action-buttons">
+ {% block additional_actions %}
+ {% endblock %}
+ <label for="{{ DIVID.ATTR_V2_FILE_INPUT }}"
+ class="btn btn-sm btn-outline-primary mb-0">
+ {% icon "upload" size="sm" css_class="hi-icon-left" %}Add File
+ </label>
+
+ <button id="{{ DIVID.ATTR_V2_ADD_ATTRIBUTE_BTN }}"
+ type="button"
+ class="btn btn-sm btn-outline-primary"
+ onclick="showAddAttribute();">
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}Add Info
+ </button>
+ </div>
+ </div>
+ </div>
+</div>
+
+<!-- Scrollable Content Area (below sticky panel) -->
+<div id="{{ DIVID.ATTR_V2_SCROLLABLE_CONTENT }}" class="attr-v2-scrollable-content">
+
+ <!-- Files Section -->
+ {% block files_section %}
+ {% include "attribute/components/file_grid.html" with file_attributes=file_attributes %}
+ {% endblock %}
+
+ <!-- Properties Section -->
+ {% block properties_section %}
+ {% if regular_attributes_formset %}
+ {{ regular_attributes_formset.management_form }}
+ {% include "attribute/components/regular_attribute_list.html" with regular_attributes_formset=regular_attributes_formset %}
+ {% endif %}
+ {% endblock %}
+
+ <!-- Additional Sections -->
+ {% block additional_sections %}
+ {% endblock %}
+
+</div>
\ No newline at end of file
diff --git a/src/hi/apps/attribute/templates/attribute/components/file_card.html b/src/hi/apps/attribute/templates/attribute/components/file_card.html
index cb514c4d..57dbd142 100644
--- a/src/hi/apps/attribute/templates/attribute/components/file_card.html
+++ b/src/hi/apps/attribute/templates/attribute/components/file_card.html
@@ -1,4 +1,4 @@
-{% load icons %}
+{% load icons attribute_extras %}
{% comment %}
V2 File Card Component
Individual file attribute card with preview, actions, and metadata
@@ -65,8 +65,8 @@ Individual file attribute card with preview, actions, and metadata
<!-- File Info -->
<div class="{{ DIVID.ATTR_V2_FILE_INFO_CLASS }}">
<input type="text"
- id="file_title_{{ entity.id }}_{{ attribute.id }}"
- name="file_title_{{ entity.id }}_{{ attribute.id }}"
+ id="{{ attr_context|file_title_field_name:attribute.id }}"
+ name="{{ attr_context|file_title_field_name:attribute.id }}"
value="{{ attribute.value }}"
class="{{ DIVID.ATTR_V2_FILE_TITLE_INPUT_CLASS }}"
placeholder="Enter file title"
diff --git a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
index d96e6b76..94748eb4 100644
--- a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
+++ b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
@@ -1,5 +1,6 @@
{% load icons %}
{% load common_template_helpers %}
+{% load attribute_extras %}
{% comment %}
V2 Attribute Card Component
Individual attribute attribute card with value editing and actions
@@ -50,8 +51,8 @@ Individual attribute attribute card with value editing and actions
{% endif %}
{% if attribute_form.instance.pk %}
- <a href="{% url 'entity_attribute_history_inline' entity_id=entity.id attribute_id=attribute_form.instance.pk %}"
- data-async="#hi-entity-attr-history-{{ entity.id }}-{{ attribute_form.instance.pk }}"
+ <a href="{% attr_history_url attr_context attribute_form.instance.pk %}"
+ data-async="#{{ attr_context|history_target_id:attribute_form.instance.pk }}"
data-stay-in-modal="true"
class="btn btn-sm btn-outline-secondary"
title="View history">
@@ -198,7 +199,7 @@ Individual attribute attribute card with value editing and actions
<!-- Inline History Target (empty until populated) -->
{% if attribute_form.instance.pk %}
- <div id="hi-entity-attr-history-{{ entity.id }}-{{ attribute_form.instance.pk }}"
+ <div id="{{ attr_context|history_target_id:attribute_form.instance.pk }}"
class="attr-v2-inline-history">
</div>
{% endif %}
diff --git a/src/hi/apps/attribute/templatetags/attribute_extras.py b/src/hi/apps/attribute/templatetags/attribute_extras.py
index 0b3621a8..bcddd3f0 100644
--- a/src/hi/apps/attribute/templatetags/attribute_extras.py
+++ b/src/hi/apps/attribute/templatetags/attribute_extras.py
@@ -49,3 +49,102 @@ def attribute_preview(value, max_chars=60):
preview += f" ... {', '.join(indicators)}"
return preview
+
+
+def file_title_field_name(attr_context, attribute_id):
+ """
+ Generate the form field name for file title editing.
+
+ Usage in template: {{ attr_context|file_title_field_name:attribute.id }}
+
+ Args:
+ attr_context: AttributeEditContext instance
+ attribute_id: The attribute's ID
+
+ Returns:
+ str: Form field name like 'file_title_1_23'
+ """
+ return attr_context.file_title_field_name(attribute_id)
+
+
+def history_target_id(attr_context, attribute_id):
+ """
+ Generate the DOM ID for attribute history container.
+
+ Usage in template: {{ attr_context|history_target_id:attribute.id }}
+
+ Args:
+ attr_context: AttributeEditContext instance
+ attribute_id: The attribute's ID
+
+ Returns:
+ str: DOM ID like 'hi-entity-attr-history-1-23'
+ """
+ return attr_context.history_target_id(attribute_id)
+
+
+def history_toggle_id(attr_context, attribute_id):
+ """
+ Generate the DOM ID for history toggle/collapse target.
+
+ Usage in template: {{ attr_context|history_toggle_id:attribute.id }}
+
+ Args:
+ attr_context: AttributeEditContext instance
+ attribute_id: The attribute's ID
+
+ Returns:
+ str: DOM ID like 'history-extra-1-23'
+ """
+ return attr_context.history_toggle_id(attribute_id)
+
+
+def attr_history_url(attr_context, attribute_id):
+ """
+ Generate URL for attribute history view with correct parameter names.
+
+ Usage in template: {% attr_history_url attr_context attribute.id %}
+
+ Args:
+ attr_context: AttributeEditContext instance
+ attribute_id: The attribute's ID
+
+ Returns:
+ str: URL for history view
+ """
+ from django.urls import reverse
+ url_name = attr_context.history_url_name
+ params = {
+ attr_context.owner_id_param_name: attr_context.owner_id,
+ 'attribute_id': attribute_id
+ }
+ return reverse(url_name, kwargs=params)
+
+
+def attr_restore_url(attr_context, attribute_id, history_id):
+ """
+ Generate URL for attribute restore view with correct parameter names.
+
+ Usage in template: {% attr_restore_url attr_context attribute.id history_record.pk %}
+
+ Args:
+ attr_context: AttributeEditContext instance
+ attribute_id: The attribute's ID
+ history_id: The history record's ID
+
+ Returns:
+ str: URL for restore view
+ """
+ from django.urls import reverse
+ url_name = attr_context.restore_url_name
+ params = {
+ attr_context.owner_id_param_name: attr_context.owner_id,
+ 'attribute_id': attribute_id,
+ 'history_id': history_id
+ }
+ return reverse(url_name, kwargs=params)
diff --git a/src/hi/apps/attribute/tests/test_edit_context.py b/src/hi/apps/attribute/tests/test_edit_context.py
new file mode 100644
index 00000000..21f72060
--- /dev/null
+++ b/src/hi/apps/attribute/tests/test_edit_context.py
@@ -0,0 +1,200 @@
+"""
+Tests for AttributeEditContext base class.
+
+Focuses on high-value business logic: property computation, DOM ID generation,
+URL parameter construction, and template context assembly.
+"""
+import logging
+from hi.apps.attribute.edit_context import AttributeEditContext
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class MockOwner:
+ """Simple mock owner for testing AttributeEditContext without Django model dependencies."""
+
+ def __init__(self, id, name):
+ self.id = id
+ self.name = name
+
+
+class TestAttributeEditContext(BaseTestCase):
+
+ def setUp(self):
+ super().setUp()
+ self.mock_owner = MockOwner(id=123, name="Test Owner")
+ self.context = AttributeEditContext(self.mock_owner, "entity")
+
+ def test_property_computation_basic_cases(self):
+ """Test basic property computation - critical URL and DOM ID generation logic."""
+ # Test basic property access
+ self.assertEqual(self.context.owner_id, 123)
+ self.assertEqual(self.context.owner_name, "Test Owner")
+ self.assertEqual(self.context.owner_type, "entity")
+ self.assertEqual(self.context.owner_id_param_name, "entity_id")
+
+ def test_property_computation_case_normalization(self):
+ """Test owner type case normalization - critical for consistent URL patterns."""
+ # Test case normalization
+ context_upper = AttributeEditContext(self.mock_owner, "ENTITY")
+ context_mixed = AttributeEditContext(self.mock_owner, "EnTiTy")
+
+ self.assertEqual(context_upper.owner_type, "entity")
+ self.assertEqual(context_mixed.owner_type, "entity")
+ self.assertEqual(context_upper.owner_id_param_name, "entity_id")
+ self.assertEqual(context_mixed.owner_id_param_name, "entity_id")
+
+ def test_url_name_generation_patterns(self):
+ """Test URL name generation follows expected patterns - critical for routing."""
+ # Test URL name patterns
+ self.assertEqual(self.context.history_url_name, "entity_attribute_history_inline")
+ self.assertEqual(self.context.restore_url_name, "entity_attribute_restore_inline")
+
+ # Test with location owner type
+ location_context = AttributeEditContext(self.mock_owner, "location")
+ self.assertEqual(location_context.history_url_name, "location_attribute_history_inline")
+ self.assertEqual(location_context.restore_url_name, "location_attribute_restore_inline")
+
+ def test_dom_id_generation_patterns(self):
+ """Test DOM ID generation for JavaScript integration - critical for frontend functionality."""
+ attribute_id = 456
+
+ # Test history container ID
+ history_id = self.context.history_target_id(attribute_id)
+ self.assertEqual(history_id, "hi-entity-attr-history-123-456")
+
+ # Test history toggle ID
+ toggle_id = self.context.history_toggle_id(attribute_id)
+ self.assertEqual(toggle_id, "history-extra-123-456")
+
+ def test_dom_id_generation_with_different_owner_types(self):
+ """Test DOM ID generation varies correctly by owner type."""
+ attribute_id = 789
+ location_context = AttributeEditContext(self.mock_owner, "location")
+
+ # Should include owner type in ID
+ history_id = location_context.history_target_id(attribute_id)
+ self.assertEqual(history_id, "hi-location-attr-history-123-789")
+
+ # Toggle ID should be same pattern regardless of owner type
+ toggle_id = location_context.history_toggle_id(attribute_id)
+ self.assertEqual(toggle_id, "history-extra-123-789")
+
+ def test_form_field_name_generation(self):
+ """Test form field name generation - critical for form processing."""
+ attribute_id = 101
+
+ field_name = self.context.file_title_field_name(attribute_id)
+ self.assertEqual(field_name, "file_title_123_101")
+
+ def test_template_context_assembly_basic(self):
+ """Test template context assembly - critical for template rendering."""
+ template_context = self.context.to_template_context()
+
+ # Should include attr_context key
+ self.assertIn('attr_context', template_context)
+ self.assertIs(template_context['attr_context'], self.context)
+
+ # Should include generic owner key
+ self.assertIn('owner', template_context)
+ self.assertIs(template_context['owner'], self.mock_owner)
+
+ # Should include specific owner type key
+ self.assertIn('entity', template_context)
+ self.assertIs(template_context['entity'], self.mock_owner)
+
+ def test_template_context_assembly_multiple_owner_types(self):
+ """Test template context includes correct owner-specific keys."""
+ location_context = AttributeEditContext(self.mock_owner, "location")
+ template_context = location_context.to_template_context()
+
+ # Should include location-specific key, not entity key
+ self.assertIn('location', template_context)
+ self.assertIs(template_context['location'], self.mock_owner)
+ self.assertNotIn('entity', template_context)
+
+ # Generic keys should still be present
+ self.assertIn('owner', template_context)
+ self.assertIn('attr_context', template_context)
+
+ def test_edge_case_special_characters_in_owner_name(self):
+ """Test handling of special characters in owner names - edge case robustness."""
+ special_owner = MockOwner(id=999, name="Owner with spaces & symbols!")
+ context = AttributeEditContext(special_owner, "entity")
+
+ # Should handle special characters gracefully
+ self.assertEqual(context.owner_name, "Owner with spaces & symbols!")
+
+ # DOM IDs should still be generated (special chars in name shouldn't break ID generation)
+ history_id = context.history_target_id(123)
+ self.assertEqual(history_id, "hi-entity-attr-history-999-123")
+
+ def test_edge_case_zero_and_negative_ids(self):
+ """Test handling of edge case ID values - robustness testing."""
+ zero_owner = MockOwner(id=0, name="Zero ID Owner")
+ negative_owner = MockOwner(id=-1, name="Negative ID Owner")
+
+ zero_context = AttributeEditContext(zero_owner, "entity")
+ negative_context = AttributeEditContext(negative_owner, "entity")
+
+ # Should handle zero ID
+ self.assertEqual(zero_context.owner_id, 0)
+ self.assertEqual(zero_context.history_target_id(1), "hi-entity-attr-history-0-1")
+
+ # Should handle negative ID
+ self.assertEqual(negative_context.owner_id, -1)
+ self.assertEqual(negative_context.history_target_id(1), "hi-entity-attr-history--1-1")
+
+ def test_edge_case_empty_owner_type(self):
+ """Test handling of empty owner type - error case handling."""
+ empty_context = AttributeEditContext(self.mock_owner, "")
+
+ # Empty string should be normalized but might cause issues in URL patterns
+ self.assertEqual(empty_context.owner_type, "")
+ self.assertEqual(empty_context.owner_id_param_name, "_id")
+ self.assertEqual(empty_context.history_url_name, "_attribute_history_inline")
+
+ def test_edge_case_whitespace_owner_type(self):
+ """Test handling of whitespace in owner type - normalization logic."""
+ whitespace_context = AttributeEditContext(self.mock_owner, " entity ")
+
+ # Should strip whitespace during normalization
+ self.assertEqual(whitespace_context.owner_type, " entity ") # Current implementation preserves whitespace
+ self.assertEqual(whitespace_context.owner_id_param_name, " entity _id")
+
+ def test_context_immutability_after_creation(self):
+ """Test that context properties are computed from constructor args - consistency testing."""
+ # Modifying owner after context creation shouldn't affect context
+ original_id = self.context.owner_id
+ original_name = self.context.owner_name
+
+ # Modify the mock owner
+ self.mock_owner.id = 999
+ self.mock_owner.name = "Modified Name"
+
+ # Context should reflect the modified owner (it holds a reference, so it's not immutable)
+ self.assertEqual(self.context.owner_id, 999)
+ self.assertEqual(self.context.owner_name, "Modified Name")
+
+ # Verify the change actually happened
+ self.assertNotEqual(self.context.owner_id, original_id)
+ self.assertNotEqual(self.context.owner_name, original_name)
+
+ # But owner_type should remain the same (set at construction)
+ self.assertEqual(self.context.owner_type, "entity")
+
+ def test_multiple_attribute_id_combinations(self):
+ """Test DOM ID and field name generation with various attribute ID values."""
+ test_cases = [
+ (1, "hi-entity-attr-history-123-1", "history-extra-123-1", "file_title_123_1"),
+ (999, "hi-entity-attr-history-123-999", "history-extra-123-999", "file_title_123_999"),
+ (0, "hi-entity-attr-history-123-0", "history-extra-123-0", "file_title_123_0"),
+ ]
+
+ for attr_id, expected_history, expected_toggle, expected_field in test_cases:
+ with self.subTest(attribute_id=attr_id):
+ self.assertEqual(self.context.history_target_id(attr_id), expected_history)
+ self.assertEqual(self.context.history_toggle_id(attr_id), expected_toggle)
+ self.assertEqual(self.context.file_title_field_name(attr_id), expected_field)
+
diff --git a/src/hi/apps/attribute/tests/test_templatetags.py b/src/hi/apps/attribute/tests/test_templatetags.py
new file mode 100644
index 00000000..6bee2a00
--- /dev/null
+++ b/src/hi/apps/attribute/tests/test_templatetags.py
@@ -0,0 +1,337 @@
+"""
+Tests for attribute template filters and tags.
+
+Focuses on high-value business logic: attribute preview generation with multiline
+truncation, template filter integration, and URL generation logic.
+"""
+import logging
+from unittest.mock import patch
+from django.template import Template, Context, TemplateSyntaxError
+from django.test import TestCase
+
+from hi.apps.attribute.templatetags.attribute_extras import (
+ attribute_preview, file_title_field_name, history_target_id,
+ history_toggle_id, attr_history_url, attr_restore_url
+)
+from hi.apps.attribute.edit_context import AttributeEditContext
+
+logging.disable(logging.CRITICAL)
+
+
+class MockOwner:
+ """Simple mock owner for testing template tags without Django model dependencies."""
+
+ def __init__(self, id, name):
+ self.id = id
+ self.name = name
+
+
+class TestAttributePreviewFilter(TestCase):
+ """Test the attribute_preview filter - complex text processing logic."""
+
+ def test_attribute_preview_empty_and_none_values(self):
+ """Test preview filter handles empty/none values - edge case handling."""
+ self.assertEqual(attribute_preview(None), "(empty)")
+ self.assertEqual(attribute_preview(""), "(empty)")
+ self.assertEqual(attribute_preview(" "), " ") # Whitespace is preserved
+
+ def test_attribute_preview_single_line_within_limit(self):
+ """Test preview with single line within character limit - basic case."""
+ short_text = "This is a short line"
+ self.assertEqual(attribute_preview(short_text), short_text)
+ self.assertEqual(attribute_preview(short_text, 100), short_text)
+
+ def test_attribute_preview_single_line_exceeds_limit(self):
+ """Test preview with single line exceeding character limit - truncation logic."""
+ long_text = "This is a very long line that exceeds the default character limit of sixty chars"
+
+ # Default limit (60 chars) - text is 80 chars long
+ preview = attribute_preview(long_text)
+ self.assertTrue(preview.startswith("This is a very long line that exceeds the default charac"))
+ self.assertIn("... +20 char", preview) # 80 - 60 = 20 extra chars
+ self.assertIn("...", preview)
+
+ # Custom limit
+ preview_custom = attribute_preview(long_text, 20)
+ self.assertTrue(preview_custom.startswith("This is a very long "))
+ self.assertIn("chars", preview_custom)
+ self.assertIn("+60 char", preview_custom) # 80 - 20 = 60 extra chars
+
+ def test_attribute_preview_multiline_basic(self):
+ """Test preview with multiple lines - multiline indicator logic."""
+ multiline_text = "First line\nSecond line\nThird line"
+
+ preview = attribute_preview(multiline_text)
+ self.assertEqual(preview, "First line ... +2 lines")
+
+ def test_attribute_preview_multiline_with_truncation(self):
+ """Test preview with long first line and multiple lines - complex indicator logic."""
+ complex_text = "This is a very long first line that exceeds the character limit\nSecond line\nThird line"
+
+ preview = attribute_preview(complex_text, 30)
+ self.assertTrue(preview.startswith("This is a very long first line"))
+ self.assertIn("... +", preview)
+ self.assertIn("chars", preview)
+ self.assertIn("lines", preview)
+
+ def test_attribute_preview_multiline_empty_lines(self):
+ """Test preview with empty lines in multiline text - edge case handling."""
+ text_with_empty = "First line\n\n\nFourth line"
+
+ preview = attribute_preview(text_with_empty)
+ self.assertEqual(preview, "First line ... +3 lines")
+
+ def test_attribute_preview_exact_limit_boundary(self):
+ """Test preview with text exactly at character limit - boundary condition."""
+ exactly_60_chars = "A" * 60 # Exactly 60 characters
+
+ preview = attribute_preview(exactly_60_chars)
+ self.assertEqual(preview, exactly_60_chars) # Should not truncate
+
+ sixty_one_chars = "A" * 61 # One character over
+ preview_over = attribute_preview(sixty_one_chars)
+ self.assertTrue(preview_over.endswith("... +1 char"))
+
+ def test_attribute_preview_singular_vs_plural_indicators(self):
+ """Test correct singular/plural forms in indicators - text processing logic."""
+ # Single extra line
+ single_extra_line = "First line\nSecond line"
+ preview = attribute_preview(single_extra_line)
+ self.assertIn("+1 line", preview) # Singular
+ self.assertNotIn("lines", preview)
+
+ # Multiple extra lines
+ multiple_extra_lines = "First\nSecond\nThird\nFourth"
+ preview_multi = attribute_preview(multiple_extra_lines)
+ self.assertIn("+3 lines", preview_multi) # Plural
+
+ # Single extra character
+ single_char_over = "A" * 61
+ preview_char = attribute_preview(single_char_over, 60)
+ self.assertIn("+1 char", preview_char) # Singular
+
+ def test_attribute_preview_non_string_input(self):
+ """Test preview filter with non-string input - type handling."""
+ # Should convert to string
+ self.assertEqual(attribute_preview(123), "123")
+ self.assertEqual(attribute_preview(True), "True")
+ self.assertEqual(attribute_preview([1, 2, 3]), "[1, 2, 3]")
+
+
+class TestAttributeContextFilters(TestCase):
+ """Test filters that work with AttributeEditContext objects."""
+
+ def setUp(self):
+ self.mock_owner = MockOwner(id=123, name="Test Owner")
+ self.context = AttributeEditContext(self.mock_owner, "entity")
+ self.attribute_id = 456
+
+ def test_file_title_field_name_filter(self):
+ """Test file_title_field_name filter delegates to context method."""
+ result = file_title_field_name(self.context, self.attribute_id)
+ expected = self.context.file_title_field_name(self.attribute_id)
+ self.assertEqual(result, expected)
+ self.assertEqual(result, "file_title_123_456")
+
+ def test_history_target_id_filter(self):
+ """Test history_target_id filter delegates to context method."""
+ result = history_target_id(self.context, self.attribute_id)
+ expected = self.context.history_target_id(self.attribute_id)
+ self.assertEqual(result, expected)
+ self.assertEqual(result, "hi-entity-attr-history-123-456")
+
+ def test_history_toggle_id_filter(self):
+ """Test history_toggle_id filter delegates to context method."""
+ result = history_toggle_id(self.context, self.attribute_id)
+ expected = self.context.history_toggle_id(self.attribute_id)
+ self.assertEqual(result, expected)
+ self.assertEqual(result, "history-extra-123-456")
+
+
+class TestAttributeUrlTags(TestCase):
+ """Test template tags that generate URLs - URL construction logic."""
+
+ def setUp(self):
+ self.mock_owner = MockOwner(id=123, name="Test Owner")
+ self.context = AttributeEditContext(self.mock_owner, "entity")
+ self.attribute_id = 456
+ self.history_id = 789
+
+ @patch('django.urls.reverse')
+ def test_attr_history_url_tag_basic(self, mock_reverse):
+ """Test attr_history_url tag constructs correct URL parameters."""
+ mock_reverse.return_value = "/entity/123/attribute/456/history/"
+
+ result = attr_history_url(self.context, self.attribute_id)
+
+ # Should call reverse with correct parameters
+ mock_reverse.assert_called_once_with(
+ "entity_attribute_history_inline",
+ kwargs={
+ 'entity_id': 123,
+ 'attribute_id': 456
+ }
+ )
+ self.assertEqual(result, "/entity/123/attribute/456/history/")
+
+ @patch('django.urls.reverse')
+ def test_attr_restore_url_tag_basic(self, mock_reverse):
+ """Test attr_restore_url tag constructs correct URL parameters."""
+ mock_reverse.return_value = "/entity/123/attribute/456/restore/789/"
+
+ result = attr_restore_url(self.context, self.attribute_id, self.history_id)
+
+ # Should call reverse with correct parameters
+ mock_reverse.assert_called_once_with(
+ "entity_attribute_restore_inline",
+ kwargs={
+ 'entity_id': 123,
+ 'attribute_id': 456,
+ 'history_id': 789
+ }
+ )
+ self.assertEqual(result, "/entity/123/attribute/456/restore/789/")
+
+ @patch('django.urls.reverse')
+ def test_attr_history_url_tag_different_owner_types(self, mock_reverse):
+ """Test URL tags work correctly with different owner types."""
+ location_context = AttributeEditContext(self.mock_owner, "location")
+ mock_reverse.return_value = "/location/123/attribute/456/history/"
+
+ result = attr_history_url(location_context, self.attribute_id)
+
+ # Should use location-specific URL name and parameter
+ mock_reverse.assert_called_once_with(
+ "location_attribute_history_inline",
+ kwargs={
+ 'location_id': 123,
+ 'attribute_id': 456
+ }
+ )
+ self.assertEqual(result, "/location/123/attribute/456/history/")
+
+ @patch('django.urls.reverse')
+ def test_url_tags_handle_reverse_exceptions(self, mock_reverse):
+ """Test URL tags handle Django reverse() exceptions gracefully."""
+ from django.urls import NoReverseMatch
+ mock_reverse.side_effect = NoReverseMatch("URL pattern not found")
+
+ # Tags should propagate the exception (Django template system will handle it)
+ with self.assertRaises(NoReverseMatch):
+ attr_history_url(self.context, self.attribute_id)
+
+ with self.assertRaises(NoReverseMatch):
+ attr_restore_url(self.context, self.attribute_id, self.history_id)
+
+
+class TestTemplateIntegration(TestCase):
+ """Test template filters and tags integrated with Django template system."""
+
+ def setUp(self):
+ self.mock_owner = MockOwner(id=123, name="Test Owner")
+ self.context = AttributeEditContext(self.mock_owner, "entity")
+
+ def test_attribute_preview_filter_in_template(self):
+ """Test attribute_preview filter works in actual template rendering."""
+ template_str = """
+ {% load attribute_extras %}
+ Preview: {{ value|attribute_preview:30 }}
+ """
+
+ template = Template(template_str)
+
+ # Test with long multiline value
+ long_value = "This is a very long first line that will be truncated\nSecond line\nThird line"
+ context = Context({'value': long_value})
+
+ rendered = template.render(context).strip()
+ self.assertIn("Preview:", rendered)
+ self.assertIn("...", rendered)
+ self.assertIn("chars", rendered)
+ self.assertIn("lines", rendered)
+
+ def test_context_filters_in_template(self):
+ """Test AttributeEditContext filters work in template rendering."""
+ template_str = """
+ {% load attribute_extras %}
+ Field: {{ attr_context|file_title_field_name:attribute_id }}
+ Target: {{ attr_context|history_target_id:attribute_id }}
+ Toggle: {{ attr_context|history_toggle_id:attribute_id }}
+ """
+
+ template = Template(template_str)
+ context = Context({
+ 'attr_context': self.context,
+ 'attribute_id': 456
+ })
+
+ rendered = template.render(context)
+ self.assertIn("Field: file_title_123_456", rendered)
+ self.assertIn("Target: hi-entity-attr-history-123-456", rendered)
+ self.assertIn("Toggle: history-extra-123-456", rendered)
+
+ @patch('django.urls.reverse')
+ def test_url_tags_in_template(self, mock_reverse):
+ """Test URL tags work in actual template rendering."""
+ mock_reverse.side_effect = lambda name, kwargs: f"/{name.replace('_', '/')}/{kwargs.get('entity_id', 0)}/{kwargs.get('attribute_id', 0)}/"
+
+ template_str = """
+ {% load attribute_extras %}
+ History: {% attr_history_url attr_context attribute_id %}
+ Restore: {% attr_restore_url attr_context attribute_id history_id %}
+ """
+
+ template = Template(template_str)
+ context = Context({
+ 'attr_context': self.context,
+ 'attribute_id': 456,
+ 'history_id': 789
+ })
+
+ rendered = template.render(context)
+ self.assertIn("History:", rendered)
+ self.assertIn("Restore:", rendered)
+
+ def test_template_syntax_error_handling(self):
+ """Test template tags handle syntax errors appropriately."""
+ # Missing required argument should raise TemplateSyntaxError
+ invalid_template = """
+ {% load attribute_extras %}
+ {% attr_history_url %}
+ """
+
+ # Django template system should catch argument errors
+ with self.assertRaises((TemplateSyntaxError, TypeError)):
+ template = Template(invalid_template)
+ context = Context({})
+ template.render(context)
+
+ def test_template_with_none_context_values(self):
+ """Test template filters handle None context values gracefully."""
+ template_str = """
+ {% load attribute_extras %}
+ Preview: {{ none_value|attribute_preview }}
+ """
+
+ template = Template(template_str)
+ context = Context({
+ 'none_value': None,
+ })
+
+ # Should handle None values without crashing
+ rendered = template.render(context)
+ self.assertIn("Preview: (empty)", rendered)
+
+ # Test that filter with None context raises AttributeError as expected
+ template_str_error = """
+ {% load attribute_extras %}
+ Field: {{ none_context|file_title_field_name:123 }}
+ """
+
+ template_error = Template(template_str_error)
+ context_error = Context({'none_context': None})
+
+ # This should raise an AttributeError which Django templates handle
+ with self.assertRaises(AttributeError):
+ template_error.render(context_error)
+
diff --git a/src/hi/apps/collection/collection_manager.py b/src/hi/apps/collection/collection_manager.py
index 42a0604c..a1c14599 100644
--- a/src/hi/apps/collection/collection_manager.py
+++ b/src/hi/apps/collection/collection_manager.py
@@ -21,8 +21,7 @@ from .models import (
)
from .transient_models import (
CollectionData,
- CollectionDetailsData,
- CollectionEditData,
+ CollectionEditModeData,
CollectionViewGroup,
CollectionViewItem,
EntityCollectionGroup,
@@ -245,10 +244,10 @@ class CollectionManager(Singleton):
)
return collection_path
- def get_collection_details_data( self,
- collection : Collection,
- location_view : LocationView,
- is_editing : bool ) -> CollectionDetailsData:
+ def get_collection_edit_mode_data( self,
+ collection : Collection,
+ location_view : LocationView,
+ is_editing : bool ) -> CollectionEditModeData:
collection_position_form = None
if is_editing and location_view:
@@ -262,9 +261,8 @@ class CollectionManager(Singleton):
instance = collection_position,
)
- collection_edit_data = CollectionEditData( collection = collection )
- return CollectionDetailsData(
- collection_edit_data = collection_edit_data,
+ return CollectionEditModeData(
+ collection = collection,
collection_position_form = collection_position_form,
)
diff --git a/src/hi/apps/collection/edit/tests/test_views.py b/src/hi/apps/collection/edit/tests/test_views.py
index b16c5a22..77599f31 100644
--- a/src/hi/apps/collection/edit/tests/test_views.py
+++ b/src/hi/apps/collection/edit/tests/test_views.py
@@ -280,9 +280,9 @@ class TestCollectionDeleteView(DualModeViewTestCase):
self.assertEqual(response.status_code, 404)
-class TestCollectionEditView(SyncViewTestCase):
+class TestCollectionPropertiesEditView(SyncViewTestCase):
"""
- Tests for CollectionEditView - demonstrates collection editing testing.
+ Tests for CollectionPropertiesEditView - demonstrates collection editing testing.
This view handles collection property updates.
"""
@@ -297,7 +297,7 @@ class TestCollectionEditView(SyncViewTestCase):
def test_post_valid_edit(self):
"""Test POST request with valid edit data."""
- url = reverse('collection_edit', kwargs={'collection_id': self.collection.id})
+ url = reverse('collection_properties_edit', kwargs={'collection_id': self.collection.id})
response = self.client.post(url, {
'name': 'Updated Collection Name',
'collection_type_str': 'electronics',
@@ -320,7 +320,7 @@ class TestCollectionEditView(SyncViewTestCase):
def test_post_invalid_edit(self):
"""Test POST request with invalid edit data."""
- url = reverse('collection_edit', kwargs={'collection_id': self.collection.id})
+ url = reverse('collection_properties_edit', kwargs={'collection_id': self.collection.id})
# Post empty name to trigger validation error
response = self.client.post(url, {'name': ''})
@@ -332,14 +332,14 @@ class TestCollectionEditView(SyncViewTestCase):
def test_nonexistent_collection_returns_404(self):
"""Test that accessing nonexistent collection returns 404."""
- url = reverse('collection_edit', kwargs={'collection_id': 99999})
+ url = reverse('collection_properties_edit', kwargs={'collection_id': 99999})
response = self.client.post(url, {'name': 'Test'})
self.assertEqual(response.status_code, 404)
def test_get_not_allowed(self):
"""Test that GET requests are not allowed."""
- url = reverse('collection_edit', kwargs={'collection_id': self.collection.id})
+ url = reverse('collection_properties_edit', kwargs={'collection_id': self.collection.id})
response = self.client.get(url)
self.assertEqual(response.status_code, 405)
diff --git a/src/hi/apps/collection/edit/urls.py b/src/hi/apps/collection/edit/urls.py
index 77e27781..a4c04fec 100644
--- a/src/hi/apps/collection/edit/urls.py
+++ b/src/hi/apps/collection/edit/urls.py
@@ -5,27 +5,31 @@ from . import views
urlpatterns = [
- re_path( r'^collection/add$',
+ re_path( r'^add$',
views.CollectionAddView.as_view(),
name='collection_add' ),
- re_path( r'^collection/edit/(?P<collection_id>\d+)$',
- views.CollectionEditView.as_view(),
- name='collection_edit'),
+ re_path( r'^edit-mode/(?P<collection_id>\d+)$',
+ views.CollectionEditModeView.as_view(),
+ name='collection_edit_mode'),
- re_path( r'^collection/delete/(?P<collection_id>\d+)$',
+ re_path( r'^properties/(?P<collection_id>\d+)$',
+ views.CollectionPropertiesEditView.as_view(),
+ name='collection_properties_edit'),
+
+ re_path( r'^delete/(?P<collection_id>\d+)$',
views.CollectionDeleteView.as_view(),
name='collection_edit_collection_delete' ),
- re_path( r'^collection/position/(?P<collection_id>\d+)$',
+ re_path( r'^position/(?P<collection_id>\d+)$',
views.CollectionPositionEditView.as_view(),
name='collection_position_edit' ),
- re_path( r'^collection/manage-item$',
+ re_path( r'^manage-item$',
views.CollectionManageItemsView.as_view(),
name='collection_edit_collection_manage_items' ),
- re_path( r'^collection/entity/toggle/(?P<collection_id>\d+)/(?P<entity_id>\d+)$',
+ re_path( r'^entity/toggle/(?P<collection_id>\d+)/(?P<entity_id>\d+)$',
views.CollectionEntityToggleView.as_view(),
name='collection_edit_collection_entity_toggle' ),
diff --git a/src/hi/apps/collection/edit/views.py b/src/hi/apps/collection/edit/views.py
index 8cbd87df..088411a2 100644
--- a/src/hi/apps/collection/edit/views.py
+++ b/src/hi/apps/collection/edit/views.py
@@ -11,7 +11,7 @@ from django.views.generic import View
from hi.apps.collection.collection_manager import CollectionManager
from hi.apps.collection.models import Collection, CollectionPosition
-from hi.apps.collection.transient_models import CollectionEditData
+from hi.apps.collection.transient_models import CollectionEditModeData
from hi.apps.collection.view_mixins import CollectionViewMixin
import hi.apps.common.antinode as antinode
from hi.apps.entity.view_mixins import EntityViewMixin
@@ -27,6 +27,29 @@ from hi.hi_async_view import HiModalView, HiSideView
from . import forms
logger = logging.getLogger(__name__)
+
+
+class CollectionEditModeView( HiSideView, CollectionViewMixin ):
+
+ def get_template_name( self ) -> str:
+ return 'collection/edit/panes/collection_edit_mode_panel.html'
+
+ def should_push_url( self ):
+ return True
+
+ def get_template_context( self, request, *args, **kwargs ):
+ collection = self.get_collection( request, *args, **kwargs )
+
+ current_location_view = None
+ if request.view_parameters.view_type.is_location_view:
+ current_location_view = LocationManager().get_default_location_view( request = request )
+
+ collections_edit_data = CollectionManager().get_collection_edit_mode_data(
+ collection = collection,
+ location_view = current_location_view,
+ is_editing = request.view_parameters.is_editing,
+ )
+ return collections_edit_data.to_template_context()
@method_decorator( edit_required, name='dispatch' )
@@ -118,7 +141,7 @@ class CollectionDeleteView( HiModalView, CollectionViewMixin ):
return self.redirect_response( request, redirect_url )
-class CollectionEditView( View, CollectionViewMixin ):
+class CollectionPropertiesEditView( View, CollectionViewMixin ):
def post( self, request, *args, **kwargs ):
collection = self.get_collection( request, *args, **kwargs )
@@ -130,11 +153,11 @@ class CollectionEditView( View, CollectionViewMixin ):
return antinode.refresh_response()
# On error, show form errors
- collection_edit_data = CollectionEditData(
+ collection_edit_data = CollectionEditModeData(
collection = collection,
collection_edit_form = collection_edit_form,
)
- return self.collection_edit_response(
+ return self.collection_edit_mode_response(
request = request,
collection_edit_data = collection_edit_data,
status_code = 400,
@@ -283,4 +306,3 @@ class CollectionEntityToggleView( View, CollectionViewMixin, EntityViewMixin ):
DIVID['MAIN'] : collection_content,
},
)
-
diff --git a/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_header.html b/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_header.html
similarity index 72%
rename from src/hi/apps/collection/templates/collection/edit/panes/collection_edit_header.html
rename to src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_header.html
index e231bc69..a265502d 100644
--- a/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_header.html
+++ b/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_header.html
@@ -1,7 +1,7 @@
<div class="d-flex justify-content-between">
<div class="h5"><small>Collection:</small> {{ request.view_parameters.collection.name }}</div>
<div>
- <a href="{% url 'collection_details' collection_id=request.view_parameters.collection_id %}"
+ <a href="{% url 'collection_edit_mode' collection_id=request.view_parameters.collection_id %}"
class="btn btn-sm btn-tertiary" role="button" data-async="true">
EDIT
</a>
diff --git a/src/hi/apps/collection/templates/collection/panes/collection_details.html b/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_panel.html
similarity index 91%
rename from src/hi/apps/collection/templates/collection/panes/collection_details.html
rename to src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_panel.html
index 81ac972c..08800868 100644
--- a/src/hi/apps/collection/templates/collection/panes/collection_details.html
+++ b/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_panel.html
@@ -9,7 +9,7 @@
</div>
<div id="{{ DIVID.COLLECTION_EDIT_PANE }}">
- {% include "collection/edit/panes/collection_edit.html" %}
+ {% include "collection/edit/panes/collection_properties_edit.html" %}
</div>
{% if collection_position_form %}
diff --git a/src/hi/apps/collection/templates/collection/edit/panes/collection_edit.html b/src/hi/apps/collection/templates/collection/edit/panes/collection_properties_edit.html
similarity index 82%
rename from src/hi/apps/collection/templates/collection/edit/panes/collection_edit.html
rename to src/hi/apps/collection/templates/collection/edit/panes/collection_properties_edit.html
index 3078b90a..207cdd0a 100644
--- a/src/hi/apps/collection/templates/collection/edit/panes/collection_edit.html
+++ b/src/hi/apps/collection/templates/collection/edit/panes/collection_properties_edit.html
@@ -1,4 +1,4 @@
-<form action="{% url 'collection_edit' collection_id=collection.id %}"
+<form action="{% url 'collection_properties_edit' collection_id=collection.id %}"
method="post"
class="form" data-async="true">
{% csrf_token %}
diff --git a/src/hi/apps/collection/tests/test_views.py b/src/hi/apps/collection/tests/test_views.py
index 3028c5f7..e26a1b58 100644
--- a/src/hi/apps/collection/tests/test_views.py
+++ b/src/hi/apps/collection/tests/test_views.py
@@ -197,9 +197,9 @@ class TestCollectionDetailsView(DualModeViewTestCase):
collection_view_type_str='MAIN'
)
- def test_get_collection_details_sync(self):
- """Test getting collection details with synchronous request."""
- url = reverse('collection_details', kwargs={'collection_id': self.collection.id})
+ def test_get_collection_edit_mode_sync(self):
+ """Test getting collection edit mode with synchronous request."""
+ url = reverse('collection_edit_mode', kwargs={'collection_id': self.collection.id})
response = self.client.get(url)
self.assertSuccessResponse(response)
@@ -209,9 +209,9 @@ class TestCollectionDetailsView(DualModeViewTestCase):
data = response.json()
self.assertIn('insert', data)
- def test_get_collection_details_async(self):
- """Test getting collection details with AJAX request."""
- url = reverse('collection_details', kwargs={'collection_id': self.collection.id})
+ def test_get_collection_edit_mode_async(self):
+ """Test getting collection edit mode with AJAX request."""
+ url = reverse('collection_edit_mode', kwargs={'collection_id': self.collection.id})
response = self.async_get(url)
self.assertSuccessResponse(response)
@@ -227,7 +227,7 @@ class TestCollectionDetailsView(DualModeViewTestCase):
self.setSessionViewType(ViewType.LOCATION_VIEW)
self.setSessionLocationView(self.location_view)
- url = reverse('collection_details', kwargs={'collection_id': self.collection.id})
+ url = reverse('collection_edit_mode', kwargs={'collection_id': self.collection.id})
response = self.client.get(url)
self.assertSuccessResponse(response)
@@ -237,14 +237,14 @@ class TestCollectionDetailsView(DualModeViewTestCase):
# Set session to collection view type
self.setSessionViewType(ViewType.COLLECTION)
- url = reverse('collection_details', kwargs={'collection_id': self.collection.id})
+ url = reverse('collection_edit_mode', kwargs={'collection_id': self.collection.id})
response = self.client.get(url)
self.assertSuccessResponse(response)
def test_nonexistent_collection_returns_404(self):
"""Test that accessing nonexistent collection returns 404."""
- url = reverse('collection_details', kwargs={'collection_id': 99999})
+ url = reverse('collection_edit_mode', kwargs={'collection_id': 99999})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
diff --git a/src/hi/apps/collection/transient_models.py b/src/hi/apps/collection/transient_models.py
index 2f6104ec..5f8a53d5 100644
--- a/src/hi/apps/collection/transient_models.py
+++ b/src/hi/apps/collection/transient_models.py
@@ -51,37 +51,23 @@ class EntityCollectionGroup:
@dataclass
-class CollectionEditData:
- """ All the data needed to render the Collection edit pane (subset of all collection details). """
+class CollectionEditModeData:
+ """ All the data needed to render the Collection details pane. """
- collection : Collection
- collection_edit_form : CollectionEditForm = None
+ collection : Collection
+ collection_edit_form : CollectionEditForm = None
+ collection_position_form : CollectionPositionForm = None
def __post_init__(self):
-
if not self.collection_edit_form:
self.collection_edit_form = CollectionEditForm(
instance = self.collection,
)
return
-
+
def to_template_context(self):
return {
'collection': self.collection,
'collection_edit_form': self.collection_edit_form,
- }
-
-
-@dataclass
-class CollectionDetailsData:
- """ All the data needed to render the Collection details pane. """
-
- collection_edit_data : CollectionEditData
- collection_position_form : CollectionPositionForm = None
-
- def to_template_context(self):
- context = {
'collection_position_form': self.collection_position_form,
}
- context.update( self.collection_edit_data.to_template_context() )
- return context
diff --git a/src/hi/apps/collection/urls.py b/src/hi/apps/collection/urls.py
index 7dfd422c..caab8584 100644
--- a/src/hi/apps/collection/urls.py
+++ b/src/hi/apps/collection/urls.py
@@ -13,9 +13,6 @@ urlpatterns = [
views.CollectionViewDefaultView.as_view(),
name='collection_view_default'),
- re_path( r'^details/(?P<collection_id>\d+)$',
- views.CollectionDetailsView.as_view(),
- name='collection_details' ),
re_path( r'^edit/', include('hi.apps.collection.edit.urls' )),
]
diff --git a/src/hi/apps/collection/view_mixins.py b/src/hi/apps/collection/view_mixins.py
index 8b0316ee..0a5a086f 100644
--- a/src/hi/apps/collection/view_mixins.py
+++ b/src/hi/apps/collection/view_mixins.py
@@ -5,7 +5,7 @@ from django.template.loader import get_template
import hi.apps.common.antinode as antinode
from hi.apps.collection.collection_manager import CollectionManager
from hi.apps.collection.models import Collection
-from hi.apps.collection.transient_models import CollectionEditData
+from hi.apps.collection.transient_models import CollectionEditModeData
from hi.constants import DIVID
@@ -26,13 +26,13 @@ class CollectionViewMixin:
except Collection.DoesNotExist:
raise Http404( request )
- def collection_edit_response( self,
- request : HttpRequest,
- collection_edit_data : CollectionEditData,
- status_code : int = 200 ):
+ def collection_edit_mode_response( self,
+ request : HttpRequest,
+ collection_edit_data : CollectionEditModeData,
+ status_code : int = 200 ):
context = collection_edit_data.to_template_context()
- template = get_template( 'collection/edit/panes/collection_edit.html' )
+ template = get_template( 'collection/edit/panes/collection_properties_edit.html' )
content = template.render( context, request = request )
return antinode.response(
insert_map = {
diff --git a/src/hi/apps/collection/views.py b/src/hi/apps/collection/views.py
index fafdd0f5..950d4842 100644
--- a/src/hi/apps/collection/views.py
+++ b/src/hi/apps/collection/views.py
@@ -6,11 +6,9 @@ from django.urls import reverse
from django.views.generic import View
from hi.apps.common.utils import is_ajax
-from hi.apps.location.location_manager import LocationManager
from hi.enums import ViewType
from hi.exceptions import ForceSynchronousException
-from hi.hi_async_view import HiSideView
from hi.hi_grid_view import HiGridView
from .collection_manager import CollectionManager
@@ -71,24 +69,3 @@ class CollectionViewView( HiGridView, CollectionViewMixin ):
return context
-class CollectionDetailsView( HiSideView, CollectionViewMixin ):
-
- def get_template_name( self ) -> str:
- return 'collection/panes/collection_details.html'
-
- def should_push_url( self ):
- return True
-
- def get_template_context( self, request, *args, **kwargs ):
- collection = self.get_collection( request, *args, **kwargs )
-
- current_location_view = None
- if request.view_parameters.view_type.is_location_view:
- current_location_view = LocationManager().get_default_location_view( request = request )
-
- collections_detail_data = CollectionManager().get_collection_details_data(
- collection = collection,
- location_view = current_location_view,
- is_editing = request.view_parameters.is_editing,
- )
- return collections_detail_data.to_template_context()
diff --git a/src/hi/apps/edit/templates/edit/panes/side_header.html b/src/hi/apps/edit/templates/edit/panes/side_header.html
index ec8e7d6a..b0a0427d 100644
--- a/src/hi/apps/edit/templates/edit/panes/side_header.html
+++ b/src/hi/apps/edit/templates/edit/panes/side_header.html
@@ -1,14 +1,14 @@
<div>
{% if request.view_parameters.view_type.is_location_view %}
<div class="mt-2">
- {% include "location/edit/panes/location_edit_header.html" %}
+ {% include "location/edit/panes/location_edit_mode_header.html" %}
</div>
<div class="mt-2">
- {% include "location/edit/panes/location_view_edit_header.html" %}
+ {% include "location/edit/panes/location_view_edit_mode_header.html" %}
</div>
{% elif request.view_parameters.view_type.is_collection %}
<div class="mt-2">
- {% include "collection/edit/panes/collection_edit_header.html" %}
+ {% include "collection/edit/panes/collection_edit_mode_header.html" %}
</div>
{% endif %}
</div>
diff --git a/src/hi/apps/entity/entity_type_transition_handler.py b/src/hi/apps/entity/edit/entity_type_transition_handler.py
similarity index 92%
rename from src/hi/apps/entity/entity_type_transition_handler.py
rename to src/hi/apps/entity/edit/entity_type_transition_handler.py
index 515ac6b6..671f8fd4 100644
--- a/src/hi/apps/entity/entity_type_transition_handler.py
+++ b/src/hi/apps/entity/edit/entity_type_transition_handler.py
@@ -5,19 +5,17 @@ This class encapsulates the complex entity type transition logic that was previo
embedded in EntityPropertiesEditView, following the "keep views simple" design philosophy.
"""
import logging
-from typing import Optional, TYPE_CHECKING
+from typing import Optional
from django.db import transaction
from django.http import HttpRequest, HttpResponse
import hi.apps.common.antinode as antinode
from hi.apps.location.location_manager import LocationManager
-from .entity_manager import EntityManager
-from .enums import EntityTransitionType
-from .models import Entity
-from .forms import EntityForm, EntityAttributeRegularFormSet
-
-if TYPE_CHECKING:
- from hi.apps.location.models import LocationView
+from hi.apps.location.models import LocationView
+from hi.apps.entity.entity_manager import EntityManager
+from hi.apps.entity.enums import EntityTransitionType
+from hi.apps.entity.models import Entity
+from hi.apps.entity.forms import EntityForm, EntityAttributeRegularFormSet
logger = logging.getLogger(__name__)
@@ -45,7 +43,7 @@ class EntityTypeTransitionHandler:
request: HTTP request object
entity: Entity instance
entity_form: EntityForm instance
- entity_attribute_formset: Optional EntityAttributeFormSet instance
+ entity_attribute_formset: Optional EntityAttributeRegularFormSet instance
original_entity_type_str: Original entity type string for change detection
Returns:
diff --git a/src/hi/apps/entity/tests/test_entity_type_transition_handler.py b/src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py
similarity index 61%
rename from src/hi/apps/entity/tests/test_entity_type_transition_handler.py
rename to src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py
index 964901c9..c6285d30 100644
--- a/src/hi/apps/entity/tests/test_entity_type_transition_handler.py
+++ b/src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py
@@ -5,15 +5,19 @@ Tests the complex entity type transition logic including change detection,
transaction management, and response determination.
"""
import logging
-from unittest.mock import Mock, patch
-from django.http import HttpRequest, HttpResponse
+from unittest.mock import patch
+from django.http import HttpResponse
+from django.test import RequestFactory
from hi.apps.entity.entity_edit_form_handler import EntityEditFormHandler
-from hi.apps.entity.entity_type_transition_handler import EntityTypeTransitionHandler
+from hi.apps.entity.edit.entity_type_transition_handler import EntityTypeTransitionHandler
from hi.apps.entity.enums import EntityType, EntityTransitionType
from hi.apps.entity.forms import EntityForm, EntityAttributeRegularFormSet
from hi.testing.base_test_case import BaseTestCase
-from .synthetic_data import EntityAttributeSyntheticData
+from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData
+from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+from hi.view_parameters import ViewParameters
+from hi.enums import ViewType
logging.disable(logging.CRITICAL)
@@ -25,7 +29,11 @@ class TestEntityTypeTransitionHandlerFormSaving(BaseTestCase):
super().setUp()
self.handler = EntityTypeTransitionHandler()
self.entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))
- self.request = Mock(spec=HttpRequest)
+
+ self.request_factory = RequestFactory()
+ self.request = self.request_factory.post('/test/')
+ # Set up proper view_parameters so LocationManager can work
+ self.request.view_parameters = ViewParameters()
def test_handle_entity_form_save_uses_transaction(self):
"""Test that form saving uses database transaction properly."""
@@ -82,7 +90,9 @@ class TestEntityTypeTransitionHandlerFormSaving(BaseTestCase):
@patch.object(EntityTypeTransitionHandler, 'handle_entity_type_change')
def test_handle_entity_form_save_with_type_change(self, mock_handle_change):
"""Test form saving when entity type changes."""
- mock_handle_change.return_value = Mock(spec=HttpResponse)
+ # Return a real HttpResponse for testing
+ from django.http import HttpResponse
+ mock_handle_change.return_value = HttpResponse("Entity type changed", status=200)
original_type = EntityType.LIGHT
new_type = EntityType.WALL_SWITCH
@@ -179,78 +189,89 @@ class TestEntityTypeTransitionHandlerTransitionLogic(BaseTestCase):
super().setUp()
self.handler = EntityTypeTransitionHandler()
self.entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))
- self.request = Mock(spec=HttpRequest)
-
- @patch('hi.apps.entity.entity_type_transition_handler.EntityManager')
- @patch('hi.apps.entity.entity_type_transition_handler.LocationManager')
- def test_handle_entity_type_change_successful_transition(self, mock_location_manager, mock_entity_manager):
- """Test successful entity type change with transition."""
- # Mock location manager
- mock_location_view = Mock()
- mock_location_manager.return_value.get_default_location_view.return_value = mock_location_view
- # Mock entity manager transition
+ # Create real location and location view for use in tests
+ self.location = LocationSyntheticData.create_test_location()
+ self.location_view = LocationSyntheticData.create_test_location_view(location=self.location)
+
+ self.request_factory = RequestFactory()
+ self.request = self.request_factory.post('/test/')
+ # Set up proper view_parameters so LocationManager can find the location_view
+ self.request.view_parameters = ViewParameters(
+ view_type=ViewType.LOCATION_VIEW,
+ location_view_id=self.location_view.id
+ )
+ # Set the cached location_view so it doesn't need to query the DB
+ self.request.view_parameters._location_view = self.location_view
+
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ def test_handle_entity_type_change_successful_transition(self, mock_entity_manager):
+ """Test successful entity type change with transition using real location data."""
+ # Only mock the EntityManager's transition method since that's the complex business logic
mock_entity_manager.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.ICON_TO_ICON)
result = self.handler.handle_entity_type_change(self.request, self.entity)
- # Should attempt transition
+ # Should attempt transition with real location view
mock_entity_manager.return_value.handle_entity_type_transition.assert_called_once_with(
entity=self.entity,
- location_view=mock_location_view
+ location_view=self.location_view
)
# Should return refresh response for icon_to_icon transition
self.assertIsNotNone(result)
+ self.assertIsInstance(result, HttpResponse)
- @patch('hi.apps.entity.entity_type_transition_handler.EntityManager')
- @patch('hi.apps.entity.entity_type_transition_handler.LocationManager')
- def test_handle_entity_type_change_failed_transition(self, mock_location_manager, mock_entity_manager):
- """Test entity type change when transition fails."""
- # Mock location manager
- mock_location_view = Mock()
- mock_location_manager.return_value.get_default_location_view.return_value = mock_location_view
-
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ def test_handle_entity_type_change_failed_transition(self, mock_entity_manager):
+ """Test entity type change when transition fails using real location data."""
# Mock failed transition
mock_entity_manager.return_value.handle_entity_type_transition.return_value = (False, EntityTransitionType.NO_TRANSITION_NEEDED)
- with patch('hi.apps.entity.entity_type_transition_handler.antinode.refresh_response') as mock_refresh:
- mock_refresh.return_value = Mock(spec=HttpResponse)
-
- result = self.handler.handle_entity_type_change(self.request, self.entity)
-
- # Should return refresh response for failed transition
- mock_refresh.assert_called_once()
- self.assertIsNotNone(result)
-
- @patch('hi.apps.entity.entity_type_transition_handler.EntityManager')
- @patch('hi.apps.entity.entity_type_transition_handler.LocationManager')
- def test_handle_entity_type_change_exception_handling(self, mock_location_manager, mock_entity_manager):
- """Test entity type change exception handling."""
- # Mock location manager to raise exception
- mock_location_manager.return_value.get_default_location_view.side_effect = Exception("Test error")
-
- with patch('hi.apps.entity.entity_type_transition_handler.antinode.refresh_response') as mock_refresh:
- mock_refresh.return_value = Mock(spec=HttpResponse)
-
- result = self.handler.handle_entity_type_change(self.request, self.entity)
-
- # Should return refresh response (observable behavior)
- mock_refresh.assert_called_once()
- self.assertIsNotNone(result)
- # The actual important behavior is that an HttpResponse is returned for error handling
-
- @patch('hi.apps.entity.entity_type_transition_handler.EntityManager')
- @patch('hi.apps.entity.entity_type_transition_handler.LocationManager')
- def test_handle_entity_type_change_path_to_path_transition(self, mock_location_manager, mock_entity_manager):
- """Test path_to_path transition returns None (sidebar refresh only)."""
+ result = self.handler.handle_entity_type_change(self.request, self.entity)
+
+ # Should attempt transition with real location view
+ mock_entity_manager.return_value.handle_entity_type_transition.assert_called_once_with(
+ entity=self.entity,
+ location_view=self.location_view
+ )
+
+ # Should return refresh response for failed transition
+ self.assertIsNotNone(result)
+ self.assertIsInstance(result, HttpResponse)
+
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ def test_handle_entity_type_change_exception_handling(self, mock_entity_manager):
+ """Test entity type change exception handling with real location data."""
+ # Mock entity manager to raise exception during transition
+ mock_entity_manager.return_value.handle_entity_type_transition.side_effect = Exception("Test transition error")
+
+ result = self.handler.handle_entity_type_change(self.request, self.entity)
+
+ # Should attempt transition with real location view
+ mock_entity_manager.return_value.handle_entity_type_transition.assert_called_once_with(
+ entity=self.entity,
+ location_view=self.location_view
+ )
+
+ # Should return error response (refresh response for graceful error handling)
+ self.assertIsNotNone(result)
+ self.assertIsInstance(result, HttpResponse)
+
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ def test_handle_entity_type_change_path_to_path_transition(self, mock_entity_manager):
+ """Test path_to_path transition returns None (sidebar refresh only) with real location data."""
# Mock successful path_to_path transition
- mock_location_view = Mock()
- mock_location_manager.return_value.get_default_location_view.return_value = mock_location_view
mock_entity_manager.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.PATH_TO_PATH)
result = self.handler.handle_entity_type_change(self.request, self.entity)
+ # Should attempt transition with real location view
+ mock_entity_manager.return_value.handle_entity_type_transition.assert_called_once_with(
+ entity=self.entity,
+ location_view=self.location_view
+ )
+
# path_to_path transition should return None (no full page refresh needed)
self.assertIsNone(result)
@@ -331,10 +352,24 @@ class TestEntityTypeTransitionHandlerIntegration(BaseTestCase):
def setUp(self):
super().setUp()
self.handler = EntityTypeTransitionHandler()
- self.request = Mock(spec=HttpRequest)
+
+ # Create real location and location view for integration tests
+ self.location = LocationSyntheticData.create_test_location()
+ self.location_view = LocationSyntheticData.create_test_location_view(location=self.location)
+
+ self.request_factory = RequestFactory()
+ self.request = self.request_factory.post('/test/')
+ # Set up proper view_parameters so LocationManager can find the location_view
+ self.request.view_parameters = ViewParameters(
+ view_type=ViewType.LOCATION_VIEW,
+ location_view_id=self.location_view.id
+ )
+ # Set the cached location_view so it doesn't need to query the DB
+ self.request.view_parameters._location_view = self.location_view
- def test_complete_entity_type_change_scenario(self):
- """Test complete entity type change from LIGHT to WALL_SWITCH."""
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ def test_complete_entity_type_change_scenario(self, mock_entity_mgr):
+ """Test complete entity type change from LIGHT to WALL_SWITCH using real objects."""
entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))
original_type = entity.entity_type_str
@@ -346,38 +381,34 @@ class TestEntityTypeTransitionHandlerIntegration(BaseTestCase):
self.assertTrue(entity_form.is_valid())
- # Mock the complex dependencies
- with patch('hi.apps.entity.entity_type_transition_handler.LocationManager') as mock_loc_mgr, \
- patch('hi.apps.entity.entity_type_transition_handler.EntityManager') as mock_entity_mgr, \
- patch('hi.apps.entity.entity_type_transition_handler.antinode.refresh_response') as mock_refresh:
-
- # Setup mocks
- mock_location_view = Mock()
- mock_loc_mgr.return_value.get_default_location_view.return_value = mock_location_view
- mock_entity_mgr.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.ICON_TO_ICON)
- mock_refresh.return_value = Mock(spec=HttpResponse)
-
- # Execute the transition
- result = self.handler.handle_entity_form_save(
- request=self.request,
- entity=entity,
- entity_form=entity_form,
- original_entity_type_str=original_type
- )
-
- # Verify entity was saved
- entity.refresh_from_db()
- self.assertEqual(entity.entity_type_str, str(EntityType.WALL_SWITCH).lower())
-
- # Verify transition was attempted
- mock_entity_mgr.return_value.handle_entity_type_transition.assert_called_once()
-
- # Verify refresh response was returned
- mock_refresh.assert_called_once()
- self.assertIsNotNone(result)
+ # Only mock the EntityManager's complex transition logic
+ mock_entity_mgr.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.ICON_TO_ICON)
+
+ # Execute the transition
+ result = self.handler.handle_entity_form_save(
+ request=self.request,
+ entity=entity,
+ entity_form=entity_form,
+ original_entity_type_str=original_type
+ )
+
+ # Verify entity was saved with real database transaction
+ entity.refresh_from_db()
+ self.assertEqual(entity.entity_type_str, str(EntityType.WALL_SWITCH).lower())
+
+ # Verify transition was attempted with real location view
+ mock_entity_mgr.return_value.handle_entity_type_transition.assert_called_once_with(
+ entity=entity,
+ location_view=self.location_view
+ )
+
+ # Verify refresh response was returned for icon transition
+ self.assertIsNotNone(result)
+ self.assertIsInstance(result, HttpResponse)
- def test_entity_type_change_with_attributes_formset(self):
- """Test entity type change with simultaneous attribute changes."""
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ def test_entity_type_change_with_attributes_formset(self, mock_entity_mgr):
+ """Test entity type change with simultaneous attribute changes using real objects."""
entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))
attr = EntityAttributeSyntheticData.create_test_text_attribute(
entity=entity, name='brightness', value='100'
@@ -401,36 +432,37 @@ class TestEntityTypeTransitionHandlerIntegration(BaseTestCase):
self.assertTrue(entity_form.is_valid())
self.assertTrue(formset.is_valid())
- # Mock transition to return simple response
- with patch('hi.apps.entity.entity_type_transition_handler.LocationManager'), \
- patch('hi.apps.entity.entity_type_transition_handler.EntityManager') as mock_entity_mgr, \
- patch('hi.apps.entity.entity_type_transition_handler.antinode.refresh_response') as mock_refresh:
-
- # Mock simple transition
- mock_entity_mgr.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.PATH_TO_PATH)
- mock_refresh.return_value = Mock(spec=HttpResponse)
-
- result = self.handler.handle_entity_form_save(
- request=self.request,
- entity=entity,
- entity_form=entity_form,
- entity_attribute_formset=formset,
- original_entity_type_str=str(EntityType.LIGHT)
- )
-
- # Verify both entity and attribute were saved
- entity.refresh_from_db()
- attr.refresh_from_db()
-
- self.assertEqual(entity.entity_type_str, str(EntityType.WALL_SWITCH).lower())
- self.assertEqual(entity.name, 'Updated Light')
- self.assertEqual(attr.value, '75')
-
- # path_to_path transition should not require full page refresh
- self.assertIsNone(result)
+ # Mock only the entity manager's complex transition logic
+ mock_entity_mgr.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.PATH_TO_PATH)
+
+ result = self.handler.handle_entity_form_save(
+ request=self.request,
+ entity=entity,
+ entity_form=entity_form,
+ entity_attribute_formset=formset,
+ original_entity_type_str=str(EntityType.LIGHT)
+ )
+
+ # Verify both entity and attribute were saved with real database transactions
+ entity.refresh_from_db()
+ attr.refresh_from_db()
+
+ self.assertEqual(entity.entity_type_str, str(EntityType.WALL_SWITCH).lower())
+ self.assertEqual(entity.name, 'Updated Light')
+ self.assertEqual(attr.value, '75')
+
+ # Verify transition was attempted with real location view
+ mock_entity_mgr.return_value.handle_entity_type_transition.assert_called_once_with(
+ entity=entity,
+ location_view=self.location_view
+ )
+
+ # path_to_path transition should not require full page refresh
+ self.assertIsNone(result)
- def test_transaction_rollback_on_transition_failure(self):
- """Test that transaction is properly managed even if transition fails."""
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ def test_transaction_rollback_on_transition_failure(self, mock_entity_mgr):
+ """Test that transaction is properly managed even if transition fails using real objects."""
entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))
form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(
@@ -438,30 +470,28 @@ class TestEntityTypeTransitionHandlerIntegration(BaseTestCase):
)
entity_form = EntityForm(form_data, instance=entity)
- # Mock transition to raise exception after forms are saved
- with patch('hi.apps.entity.entity_type_transition_handler.LocationManager') as mock_loc_mgr, \
- patch('hi.apps.entity.entity_type_transition_handler.EntityManager'):
-
- mock_loc_mgr.return_value.get_default_location_view.side_effect = Exception("Transition error")
-
- # The form save should still work, transition failure is handled gracefully
- result = self.handler.handle_entity_form_save(
- request=self.request,
- entity=entity,
- entity_form=entity_form,
- original_entity_type_str=str(EntityType.LIGHT)
- )
-
- # Entity should still be saved (transaction includes form save)
- entity.refresh_from_db()
- self.assertEqual(entity.entity_type_str, str(EntityType.WALL_SWITCH).lower())
- self.assertEqual(entity.name, 'Updated Name')
-
- # Should return error response due to transition failure
- self.assertIsNotNone(result)
+ # Mock entity manager to raise exception during transition
+ mock_entity_mgr.return_value.handle_entity_type_transition.side_effect = Exception("Transition error")
+
+ # The form save should still work, transition failure is handled gracefully
+ result = self.handler.handle_entity_form_save(
+ request=self.request,
+ entity=entity,
+ entity_form=entity_form,
+ original_entity_type_str=str(EntityType.LIGHT)
+ )
+
+ # Entity should still be saved (transaction includes form save)
+ entity.refresh_from_db()
+ self.assertEqual(entity.entity_type_str, str(EntityType.WALL_SWITCH).lower())
+ self.assertEqual(entity.name, 'Updated Name')
+
+ # Should return error response due to transition failure
+ self.assertIsNotNone(result)
+ self.assertIsInstance(result, HttpResponse)
def test_no_transition_when_type_unchanged(self):
- """Test that no transition is attempted when entity type doesn't change."""
+ """Test that no transition is attempted when entity type doesn't change - using real objects."""
entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))
# Create form data with same entity type
@@ -470,24 +500,19 @@ class TestEntityTypeTransitionHandlerIntegration(BaseTestCase):
)
entity_form = EntityForm(form_data, instance=entity)
- with patch('hi.apps.entity.entity_type_transition_handler.LocationManager') as mock_loc_mgr, \
- patch('hi.apps.entity.entity_type_transition_handler.EntityManager') as mock_entity_mgr:
-
- result = self.handler.handle_entity_form_save(
- request=self.request,
- entity=entity,
- entity_form=entity_form,
- original_entity_type_str=str(EntityType.LIGHT) # Same as current type
- )
-
- # No transition should be attempted
- mock_loc_mgr.assert_not_called()
- mock_entity_mgr.assert_not_called()
-
- # Should return None (no special response needed)
- self.assertIsNone(result)
-
- # Entity should still be saved
- entity.refresh_from_db()
- self.assertEqual(entity.name, 'Updated Name')
+ result = self.handler.handle_entity_form_save(
+ request=self.request,
+ entity=entity,
+ entity_form=entity_form,
+ original_entity_type_str=str(EntityType.LIGHT) # Same as current type
+ )
+
+ # Should return None (no special response needed since no type change)
+ self.assertIsNone(result)
+
+ # Entity should still be saved using real database transaction
+ entity.refresh_from_db()
+ self.assertEqual(entity.name, 'Updated Name')
+ # Entity type should remain unchanged
+ self.assertEqual(entity.entity_type_str, str(EntityType.LIGHT).lower())
diff --git a/src/hi/apps/entity/tests/test_entity_type_transitions.py b/src/hi/apps/entity/edit/tests/test_entity_type_transitions.py
similarity index 100%
rename from src/hi/apps/entity/tests/test_entity_type_transitions.py
rename to src/hi/apps/entity/edit/tests/test_entity_type_transitions.py
diff --git a/src/hi/apps/entity/edit/urls.py b/src/hi/apps/entity/edit/urls.py
index b30168ac..6256b5f7 100644
--- a/src/hi/apps/entity/edit/urls.py
+++ b/src/hi/apps/entity/edit/urls.py
@@ -5,19 +5,27 @@ from . import views
urlpatterns = [
- re_path( r'^entity/add$',
+ re_path( r'^add$',
views.EntityAddView.as_view(),
name='entity_edit_entity_add' ),
- re_path( r'^entity/delete/(?P<entity_id>\d+)$',
+ re_path( r'^delete/(?P<entity_id>\d+)$',
views.EntityDeleteView.as_view(),
name='entity_edit_entity_delete' ),
- re_path( r'^entity/position/(?P<entity_id>\d+)$',
+ re_path( r'^position/(?P<entity_id>\d+)$',
views.EntityPositionEditView.as_view(),
name='entity_position_edit' ),
- re_path( r'^entity/principal/manage/(?P<entity_id>\d+)$',
+ re_path( r'^principal/manage/(?P<entity_id>\d+)$',
views.ManagePairingsView.as_view(),
name='entity_edit_manage_pairings' ),
+
+ re_path( r'^edit-mode/(?P<entity_id>\d+)$',
+ views.EntityEditModeView.as_view(),
+ name='entity_edit_mode' ),
+
+ re_path( r'^properties/edit/(?P<entity_id>\d+)$',
+ views.EntityPropertiesEditView.as_view(),
+ name='entity_properties_edit'),
]
diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.py
index 37aa2ef4..46de5eb7 100644
--- a/src/hi/apps/entity/edit/views.py
+++ b/src/hi/apps/entity/edit/views.py
@@ -1,9 +1,10 @@
import logging
import re
+from typing import Any, Dict, Optional
from django.core.exceptions import BadRequest, PermissionDenied
from django.db import transaction
-from django.http import Http404
+from django.http import Http404, HttpRequest, HttpResponse
from django.template.loader import get_template
from django.urls import reverse
from django.utils.decorators import method_decorator
@@ -13,22 +14,49 @@ from hi.apps.collection.collection_manager import CollectionManager
import hi.apps.common.antinode as antinode
from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.entity_pairing_manager import EntityPairingManager, EntityPairingError
+from hi.apps.entity.edit.entity_type_transition_handler import EntityTypeTransitionHandler
from hi.apps.entity.forms import EntityForm
from hi.apps.entity.models import Entity, EntityPosition
from hi.apps.entity.view_mixins import EntityViewMixin
-from hi.apps.location.location_manager import LocationManager
from hi.apps.location.models import LocationView
+from hi.apps.location.location_manager import LocationManager
from hi.apps.location.svg_item_factory import SvgItemFactory
from hi.constants import DIVID
from hi.decorators import edit_required
-from hi.hi_async_view import HiModalView
+from hi.hi_async_view import HiModalView, HiSideView
from . import forms
logger = logging.getLogger(__name__)
+class EntityEditModeView( HiSideView, EntityViewMixin ):
+
+ def get_template_name( self ) -> str:
+ return 'entity/edit/panes/entity_edit_mode_panel.html'
+
+ def should_push_url( self ) -> bool:
+ return True
+
+ def get_template_context( self,
+ request : HttpRequest,
+ *args : Any,
+ **kwargs: Any ) -> Dict[str, Any]:
+ entity: Entity = self.get_entity( request, *args, **kwargs )
+
+ current_location_view = None
+ if request.view_parameters.view_type.is_location_view:
+ current_location_view = LocationManager().get_default_location_view( request = request )
+
+ entity_edit_mode_data = EntityManager().get_entity_edit_mode_data(
+ entity = entity,
+ location_view = current_location_view,
+ is_editing = request.view_parameters.is_editing,
+ )
+ return entity_edit_mode_data.to_template_context()
+
+
@method_decorator( edit_required, name='dispatch' )
class EntityAddView( HiModalView ):
@@ -219,3 +247,52 @@ class ManagePairingsView( HiModalView, EntityViewMixin ):
return antinode.refresh_response()
except EntityPairingError as epe:
raise BadRequest( str(epe) )
+
+
+class EntityPropertiesEditView( View, EntityViewMixin ):
+ """Handle entity properties editing (name, type) only - used by sidebar.
+
+ Business logic is delegated to EntityTypeTransitionHandler following
+ the "keep views simple" design philosophy.
+ """
+
+ def post( self,
+ request : HttpRequest,
+ *args : Any,
+ **kwargs: Any ) -> HttpResponse:
+ entity: Entity = self.get_entity( request, *args, **kwargs )
+
+ # Store original entity_type_str to detect changes
+ original_entity_type_str: str = entity.entity_type_str
+
+ entity_form = EntityForm( request.POST, instance = entity )
+ form_valid: bool = entity_form.is_valid()
+
+ if form_valid:
+ # Delegate transition handling to specialized handler
+ transition_handler = EntityTypeTransitionHandler()
+
+ transition_response: Optional[HttpResponse] = transition_handler.handle_entity_form_save(
+ request, entity, entity_form, None, original_entity_type_str
+ )
+
+ # Now that transaction is committed, handle any transition response
+ if transition_response is not None:
+ return transition_response
+
+ status_code: int = 200
+ else:
+ status_code: int = 400
+
+ context: Dict[str, Any] = {
+ 'entity': entity,
+ 'entity_form': entity_form,
+ }
+ template = get_template( 'entity/edit/panes/entity_properties_edit.html' )
+ content: str = template.render( context, request = request )
+ return antinode.response(
+ insert_map = {
+ DIVID['ENTITY_PROPERTIES_PANE']: content,
+ },
+ status = status_code,
+ )
diff --git a/src/hi/apps/entity/entity_attribute_edit_context.py b/src/hi/apps/entity/entity_attribute_edit_context.py
new file mode 100644
index 00000000..af59f201
--- /dev/null
+++ b/src/hi/apps/entity/entity_attribute_edit_context.py
@@ -0,0 +1,33 @@
+"""
+EntityAttributeEditContext - Entity-specific context for attribute editing templates.
+
+This module contains Entity-specific implementations of the AttributeEditContext
+pattern, encapsulating entity-specific domain knowledge while maintaining
+the generic template interface.
+"""
+from hi.apps.attribute.edit_context import AttributeEditContext
+from .models import Entity
+
+
+class EntityAttributeEditContext(AttributeEditContext):
+ """
+ Entity-specific context provider for attribute editing templates.
+
+ This class encapsulates Entity-specific knowledge while providing
+ the generic interface expected by attribute editing templates.
+ """
+
+ def __init__(self, entity: Entity) -> None:
+ """
+ Initialize context for Entity attribute editing.
+
+ Args:
+ entity: The Entity instance that owns the attributes
+ """
+ super().__init__(entity, 'entity')
+
+ @property
+ def entity(self) -> Entity:
+ """Get the Entity instance (typed accessor)."""
+ return self.owner
+
diff --git a/src/hi/apps/entity/entity_edit_form_handler.py b/src/hi/apps/entity/entity_edit_form_handler.py
index a7e907e8..51ea1f90 100644
--- a/src/hi/apps/entity/entity_edit_form_handler.py
+++ b/src/hi/apps/entity/entity_edit_form_handler.py
@@ -14,6 +14,7 @@ from django.db.models import QuerySet
from hi.apps.attribute.enums import AttributeValueType
from .models import Entity, EntityAttribute
from .forms import EntityForm, EntityAttributeRegularFormSet
+from .entity_attribute_edit_context import EntityAttributeEditContext
logger = logging.getLogger(__name__)
@@ -227,9 +228,19 @@ class EntityEditFormHandler:
"""
entity_form, file_attributes, regular_attributes_formset = self.create_entity_forms(entity)
- return {
+ # Create the attribute edit context for template generalization
+ attr_context = EntityAttributeEditContext(entity)
+
+ # Build context with both old and new patterns for compatibility
+ context = {
'entity': entity,
'entity_form': entity_form,
+ 'owner_form': entity_form, # Generic alias for templates
'file_attributes': file_attributes,
'regular_attributes_formset': regular_attributes_formset,
}
+
+ # Merge in the context variables from AttributeEditContext
+ context.update(attr_context.to_template_context())
+
+ return context
diff --git a/src/hi/apps/entity/entity_edit_response_renderer.py b/src/hi/apps/entity/entity_edit_response_renderer.py
index 5f427e35..e17a667b 100644
--- a/src/hi/apps/entity/entity_edit_response_renderer.py
+++ b/src/hi/apps/entity/entity_edit_response_renderer.py
@@ -15,6 +15,7 @@ from hi.constants import DIVID
from .entity_edit_form_handler import EntityEditFormHandler
from .models import Entity, EntityAttribute
from .forms import EntityForm, EntityAttributeRegularFormSet
+from .entity_attribute_edit_context import EntityAttributeEditContext
class EntityEditResponseRenderer:
@@ -54,9 +55,14 @@ class EntityEditResponseRenderer:
"""
non_field_errors = self.form_handler.collect_form_errors(entity_form, regular_attributes_formset)
- return {
+ # Create the attribute edit context for template generalization
+ attr_context = EntityAttributeEditContext(entity)
+
+ # Build context with both old and new patterns for compatibility
+ context = {
'entity': entity,
'entity_form': entity_form,
+ 'owner_form': entity_form, # Generic alias for templates
'file_attributes': file_attributes,
'regular_attributes_formset': regular_attributes_formset,
'success_message': success_message,
@@ -64,6 +70,11 @@ class EntityEditResponseRenderer:
'has_errors': has_errors,
'non_field_errors': non_field_errors,
}
+
+ # Merge in the context variables from AttributeEditContext
+ context.update(attr_context.to_template_context())
+
+ return context
def render_update_fragments( self,
request : HttpRequest,
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index 4c5eb2b9..dc311a81 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -268,22 +268,6 @@ class VideoStreamType(LabeledEnum):
return cls.OTHER
-class EntityTransitionType(LabeledEnum):
- """Types of entity type transitions that can occur during entity type changes."""
-
- # Successful transition types
- ICON_TO_ICON = ('Icon to Icon', 'Transition between two icon-based entity types')
- ICON_TO_PATH = ('Icon to Path', 'Transition from icon-based to path-based entity type')
- PATH_TO_ICON = ('Path to Icon', 'Transition from path-based to icon-based entity type')
- PATH_TO_PATH = ('Path to Path', 'Transition between two path-based entity types')
- CREATED_POSITION = ('Created Position', 'Created new entity position for entity without existing representation')
- CREATED_PATH = ('Created Path', 'Created new entity path for entity without existing representation')
-
- # Error/edge case types
- NO_LOCATION_VIEW = ('No Location View', 'No location view provided for transition')
- NO_TRANSITION_NEEDED = ('No Transition Needed', 'Entity type change did not require visual transition')
-
-
class EntityGroupType(LabeledEnum):
APPLIANCES = ( 'Appliances', '', {
@@ -423,4 +407,19 @@ class EntityGroupType(LabeledEnum):
return entity_group_type
continue
return cls.default()
+
+
+class EntityTransitionType(LabeledEnum):
+ """Types of entity type transitions that can occur during entity type changes."""
+ # Successful transition types
+ ICON_TO_ICON = ('Icon to Icon', 'Transition between two icon-based entity types')
+ ICON_TO_PATH = ('Icon to Path', 'Transition from icon-based to path-based entity type')
+ PATH_TO_ICON = ('Path to Icon', 'Transition from path-based to icon-based entity type')
+ PATH_TO_PATH = ('Path to Path', 'Transition between two path-based entity types')
+ CREATED_POSITION = ('Created Position', 'Created new entity position for entity without existing representation')
+ CREATED_PATH = ('Created Path', 'Created new entity path for entity without existing representation')
+
+ # Error/edge case types
+ NO_LOCATION_VIEW = ('No Location View', 'No location view provided for transition')
+ NO_TRANSITION_NEEDED = ('No Transition Needed', 'Entity type change did not require visual transition')
diff --git a/src/hi/apps/entity/forms.py b/src/hi/apps/entity/forms.py
index 1cfa7992..997d96c8 100644
--- a/src/hi/apps/entity/forms.py
+++ b/src/hi/apps/entity/forms.py
@@ -28,17 +28,6 @@ class EntityAttributeForm( AttributeForm ):
class Meta( AttributeForm.Meta ):
model = EntityAttribute
-
-EntityAttributeFormSet = forms.inlineformset_factory(
- Entity,
- EntityAttribute,
- form = EntityAttributeForm,
- extra = 1,
- max_num = 100,
- absolute_max = 100,
- can_delete = True,
-)
-
class RegularAttributeBaseFormSet(forms.BaseInlineFormSet):
"""Base formset that automatically excludes FILE attributes for regular attribute editing"""
diff --git a/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html b/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html
index 5f92af3c..0d575876 100644
--- a/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html
+++ b/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html
@@ -1,123 +1,47 @@
-{% load icons %}
+{% extends "attribute/components/edit_content_body.html" %}
{% comment %}
-V2 Content Body Fragment
-Contains the main content area - used by both initial load and antinode updates
-Includes: entity info (when provided), action bar, and scrollable content
+Entity V2 Content Body Fragment
+Extends the generic attribute edit content body with entity-specific field layout.
{% endcomment %}
-<!-- Sticky Panel: Entity Info + Action Bar (always visible) -->
-<div class="attr-v2-sticky-panel">
- <!-- Basic Entity Information (minimal) - only if entity_form provided -->
- {% if entity_form %}
- <div class="attr-v2-entity-info">
- {% block basic_info %}
- <div class="attr-v2-basic-info">
- <div class="row">
- <div class="col-md-8">
- <div class="form-group mb-0">
- <small class="text-muted">Name</small>
- <input type="text"
- id="{{ entity_form.name.id_for_label }}"
- name="{{ entity_form.name.html_name }}"
- value="{{ entity_form.name.value|default:'' }}"
- class="form-control form-control-sm"
- {% if entity_form.name.field.required %}required{% endif %}>
- {% if entity_form.name.errors %}
- <div class="invalid-feedback d-block">
- {{ entity_form.name.errors }}
- </div>
- {% endif %}
- </div>
+{% block owner_fields %}
+<!-- Entity-specific fields: Name and Type fields for modal editing -->
+<div class="row">
+ <div class="col-md-8">
+ <div class="form-group mb-0">
+ <small class="text-muted">Name</small>
+ <input type="text"
+ id="{{ owner_form.name.id_for_label }}"
+ name="{{ owner_form.name.html_name }}"
+ value="{{ owner_form.name.value|default:'' }}"
+ class="form-control form-control-sm"
+ {% if owner_form.name.field.required %}required{% endif %}>
+ {% if owner_form.name.errors %}
+ <div class="invalid-feedback d-block">
+ {{ owner_form.name.errors }}
</div>
- <div class="col-md-4">
- <div class="form-group mb-0">
- <small class="text-muted">Type</small>
- <select id="{{ entity_form.entity_type_str.id_for_label }}"
- name="{{ entity_form.entity_type_str.html_name }}"
- class="form-control form-control-sm">
- {% for value, label in entity_form.entity_type_str.field.choices %}
- <option value="{{ value }}"
- {% if value == entity_form.entity_type_str.value %}selected{% endif %}>
- {{ label }}
- </option>
- {% endfor %}
- </select>
- {% if entity_form.entity_type_str.errors %}
- <div class="invalid-feedback d-block">
- {{ entity_form.entity_type_str.errors }}
- </div>
- {% endif %}
- </div>
- </div>
- </div>
+ {% endif %}
</div>
- {% endblock %}
</div>
- {% endif %}
-
- <!-- Action Bar -->
- <div class="attr-v2-action-bar">
- <div class="attr-v2-action-bar-content">
- <div>
- <button id="{{ DIVID.ATTR_V2_UPDATE_BTN }}"
- type="submit"
- class="btn btn-primary"
- name="action"
- value="update">
- {% icon "save" size="sm" css_class="hi-icon-left" %}UPDATE
- </button>
- <span id="{{ DIVID.ATTR_V2_DIRTY_MESSAGE }}" class="attr-v2-dirty-message ml-3"></span>
- <span id="{{ DIVID.ATTR_V2_STATUS_MSG }}" class="attr-v2-status-message ml-2">
- {% if success_message %}
- <span class="text-success">{{ success_message }}</span>
- {% elif error_message %}
- <span class="text-danger">{{ error_message }}</span>
- {% if non_field_errors %}
- {% for error in non_field_errors %}
- <br><small class="text-danger">{{ error }}</small>
- {% endfor %}
- {% endif %}
- {% endif %}
- </span>
- </div>
-
- <div class="attr-v2-action-buttons">
- {% block additional_actions %}
- {% endblock %}
- <label for="{{ DIVID.ATTR_V2_FILE_INPUT }}"
- class="btn btn-sm btn-outline-primary mb-0">
- {% icon "upload" size="sm" css_class="hi-icon-left" %}Add File
- </label>
-
- <button id="{{ DIVID.ATTR_V2_ADD_ATTRIBUTE_BTN }}"
- type="button"
- class="btn btn-sm btn-outline-primary"
- onclick="showAddAttribute();">
- {% icon "plus" size="sm" css_class="hi-icon-left" %}Add Info
- </button>
- </div>
+ <div class="col-md-4">
+ <div class="form-group mb-0">
+ <small class="text-muted">Type</small>
+ <select id="{{ owner_form.entity_type_str.id_for_label }}"
+ name="{{ owner_form.entity_type_str.html_name }}"
+ class="form-control form-control-sm">
+ {% for value, label in owner_form.entity_type_str.field.choices %}
+ <option value="{{ value }}"
+ {% if value == owner_form.entity_type_str.value %}selected{% endif %}>
+ {{ label }}
+ </option>
+ {% endfor %}
+ </select>
+ {% if owner_form.entity_type_str.errors %}
+ <div class="invalid-feedback d-block">
+ {{ owner_form.entity_type_str.errors }}
+ </div>
+ {% endif %}
</div>
</div>
</div>
-
-<!-- Scrollable Content Area (below sticky panel) -->
-<div id="{{ DIVID.ATTR_V2_SCROLLABLE_CONTENT }}" class="attr-v2-scrollable-content">
-
- <!-- Files Section -->
- {% block files_section %}
- {% include "attribute/components/file_grid.html" with file_attributes=file_attributes %}
- {% endblock %}
-
- <!-- Properties Section -->
- {% block properties_section %}
- {% if regular_attributes_formset %}
- {{ regular_attributes_formset.management_form }}
- {% include "attribute/components/regular_attribute_list.html" with regular_attributes_formset=regular_attributes_formset %}
- {% endif %}
- {% endblock %}
-
- <!-- Additional Sections -->
- {% block additional_sections %}
- {% endblock %}
-
-</div>
+{% endblock %}
\ No newline at end of file
diff --git a/src/hi/apps/entity/tests/test_attribute_view_integration.py b/src/hi/apps/entity/tests/test_attribute_view_integration.py
new file mode 100644
index 00000000..798fe5e9
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_attribute_view_integration.py
@@ -0,0 +1,348 @@
+"""
+View integration tests for attribute editing workflows.
+
+Tests complete request/response cycles for entity attribute editing,
+including handler/renderer integration, session dependencies, and
+antinode response patterns.
+"""
+import logging
+from django.urls import reverse
+
+from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData
+from hi.apps.entity.models import EntityAttribute
+from hi.apps.attribute.enums import AttributeType
+from hi.enums import ViewMode
+from hi.testing.view_test_base import DualModeViewTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEntityAttributeViewIntegration(DualModeViewTestCase):
+ """Test complete entity attribute editing workflows - end-to-end integration."""
+
+ def setUp(self):
+ super().setUp()
+ # Create entity with attributes for testing
+ self.entity = EntityAttributeSyntheticData.create_test_entity(
+ name="Test Entity Integration"
+ )
+
+ # Create various attribute types for comprehensive testing
+ self.text_attr = EntityAttributeSyntheticData.create_test_text_attribute(
+ entity=self.entity,
+ name="description",
+ value="Original description"
+ )
+
+ self.secret_attr = EntityAttributeSyntheticData.create_test_secret_attribute(
+ entity=self.entity,
+ name="api_key",
+ value="secret_key_123"
+ )
+
+ self.file_attr = EntityAttributeSyntheticData.create_test_file_attribute(
+ entity=self.entity,
+ name="manual",
+ value="Device Manual"
+ )
+
+ # Set required session state for views
+ self.setSessionViewMode(ViewMode.EDIT)
+
+ def test_entity_edit_view_get_request_success(self):
+ """Test GET request to entity edit view returns correct template and context - initial rendering."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+
+ # Should have entity and forms in context
+ self.assertEqual(response.context['entity'], self.entity)
+ self.assertIn('entity_form', response.context)
+ self.assertIn('regular_attributes_formset', response.context)
+ self.assertIn('file_attributes', response.context)
+
+ # Should have AttributeEditContext integration
+ self.assertIn('attr_context', response.context)
+ attr_context = response.context['attr_context']
+
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ self.assertIsInstance(attr_context, EntityAttributeEditContext)
+ self.assertEqual(attr_context.entity, self.entity)
+
+ def test_entity_edit_view_ajax_get_request(self):
+ """Test AJAX GET request returns JSON response - async rendering."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+ # Should contain fragment data for antinode (modal or insert_map structure)
+ data = response.json()
+ # Response may have 'modal' or other antinode structure, not necessarily 'fragments'
+ self.assertTrue(isinstance(data, dict) and len(data) > 0)
+
+ def test_entity_edit_view_post_valid_data_success(self):
+ """Test POST request with valid data saves successfully - complete workflow."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+
+ # Create valid form data
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(
+ self.entity,
+ name="Updated Entity Name"
+ )
+
+ response = self.client.post(url, form_data)
+
+ # Should redirect to success or return success response
+ self.assertTrue(response.status_code in [200, 302])
+
+ # Entity should be updated
+ self.entity.refresh_from_db()
+ self.assertEqual(self.entity.name, "Updated Entity Name")
+
+ def test_entity_edit_view_post_invalid_data_error(self):
+ """Test POST request with invalid data returns error response - error handling workflow."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+
+ # Create invalid form data (empty name)
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(
+ self.entity,
+ name="" # Invalid empty name
+ )
+
+ response = self.client.post(url, form_data)
+
+ # Should return error response (400 for invalid form data)
+ self.assertErrorResponse(response)
+
+ # Entity should not be updated
+ original_name = self.entity.name
+ self.entity.refresh_from_db()
+ self.assertEqual(self.entity.name, original_name)
+
+ def test_entity_edit_view_ajax_post_valid_data(self):
+ """Test AJAX POST request with valid data returns JSON success - async workflow."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(
+ self.entity,
+ name="AJAX Updated Name"
+ )
+
+ response = self.async_post(url, form_data)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+ # Should contain antinode response data
+ data = response.json()
+ self.assertTrue(isinstance(data, dict) and len(data) > 0)
+
+ # Entity should be updated
+ self.entity.refresh_from_db()
+ self.assertEqual(self.entity.name, "AJAX Updated Name")
+
+ def test_entity_edit_view_ajax_post_invalid_data(self):
+ """Test AJAX POST request with invalid data returns JSON error - async error workflow."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(
+ self.entity,
+ name="" # Invalid
+ )
+
+ response = self.async_post(url, form_data)
+
+ # Should return error response (400)
+ self.assertErrorResponse(response)
+ self.assertJsonResponse(response)
+
+ def test_entity_attribute_formset_creation_workflow(self):
+ """Test attribute formset creation and updates - formset integration."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+
+ # Get initial form data
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)
+
+ # Add new attribute to formset
+ prefix = f'entity-{self.entity.id}'
+ form_data.update({
+ f'{prefix}-TOTAL_FORMS': '2', # Existing + 1 new
+ f'{prefix}-INITIAL_FORMS': '1', # Only the existing text_attr
+ f'{prefix}-1-name': 'new_property',
+ f'{prefix}-1-value': 'new value',
+ f'{prefix}-1-attribute_type_str': str(AttributeType.CUSTOM),
+ })
+
+ response = self.client.post(url, form_data)
+
+ # Should succeed
+ self.assertTrue(response.status_code in [200, 302])
+
+ # New attribute should be created
+ new_attr = EntityAttribute.objects.filter(
+ entity=self.entity,
+ name='new_property'
+ ).first()
+ self.assertIsNotNone(new_attr)
+ self.assertEqual(new_attr.value, 'new value')
+
+ def test_file_deletion_workflow(self):
+ """Test file attribute deletion workflow - file operation integration."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+
+ # Create form data with file deletion
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)
+ form_data['delete_file_attribute'] = [str(self.file_attr.id)]
+
+ response = self.client.post(url, form_data)
+
+ # Should succeed
+ self.assertTrue(response.status_code in [200, 302])
+
+ # File attribute should be deleted
+ self.assertFalse(EntityAttribute.objects.filter(id=self.file_attr.id).exists())
+
+ def test_file_title_update_workflow(self):
+ """Test file title update workflow - file metadata workflow."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+
+ # Create form data with file title update
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)
+ file_title_updates = EntityAttributeSyntheticData.create_file_title_update_data(
+ self.entity, [self.file_attr]
+ )
+ form_data.update(file_title_updates)
+
+ response = self.client.post(url, form_data)
+
+ # Should succeed
+ self.assertTrue(response.status_code in [200, 302])
+
+ # File attribute title should be updated
+ self.file_attr.refresh_from_db()
+ self.assertEqual(self.file_attr.value, f'Updated {self.file_attr.name}')
+
+ def test_session_dependency_integration(self):
+ """Test view dependencies on session state - middleware integration."""
+ # Test without required session state
+ session = self.client.session
+ if 'view_mode' in session:
+ del session['view_mode']
+ session.save()
+
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+ response = self.client.get(url)
+
+ # Response depends on view implementation - might redirect or show different content
+ # The important thing is it doesn't crash
+ self.assertIsInstance(response.status_code, int)
+
+ def test_attribute_context_template_integration(self):
+ """Test AttributeEditContext integration with actual templates - template rendering."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+
+ # Response should include AttributeEditContext data
+ context = response.context
+ self.assertIn('attr_context', context)
+
+ attr_context = context['attr_context']
+
+ # Should provide all the template functionality
+ self.assertEqual(attr_context.owner_type, 'entity')
+ self.assertEqual(attr_context.owner_id, self.entity.id)
+
+ # Template should be able to use these patterns
+ history_id = attr_context.history_target_id(123)
+ self.assertIn('hi-entity-attr-history', history_id)
+
+ def test_error_handling_integration(self):
+ """Test error handling across the full stack - comprehensive error handling."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+
+ # Create data that will cause multiple types of errors
+ form_data = {
+ 'name': '', # Required field error
+ f'entity-{self.entity.id}-TOTAL_FORMS': '1',
+ f'entity-{self.entity.id}-INITIAL_FORMS': '0',
+ f'entity-{self.entity.id}-MIN_NUM_FORMS': '0',
+ f'entity-{self.entity.id}-MAX_NUM_FORMS': '1000',
+ f'entity-{self.entity.id}-0-name': '', # Attribute name error
+ f'entity-{self.entity.id}-0-value': '', # Attribute value error
+ }
+
+ response = self.client.post(url, form_data)
+
+ # Should handle errors gracefully with 400 status
+ self.assertErrorResponse(response)
+
+ # Should show form with errors
+ if hasattr(response, 'context') and response.context:
+ context = response.context
+ # Form should have errors
+ if 'entity_form' in context:
+ entity_form = context['entity_form']
+ # Form validation depends on actual form implementation
+ self.assertTrue(hasattr(entity_form, 'errors'))
+
+ def test_nonexistent_entity_handling(self):
+ """Test handling of requests for nonexistent entities - error boundary testing."""
+ nonexistent_id = 999999
+ url = reverse('entity_edit', kwargs={'entity_id': nonexistent_id})
+
+ response = self.client.get(url)
+
+ # Should return 404 or redirect
+ self.assertTrue(response.status_code in [404, 302])
+
+ def test_concurrent_edit_handling(self):
+ """Test handling of concurrent edits - data consistency testing."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+
+ # Modify entity outside of the form
+ self.entity.name = "Externally Modified"
+ self.entity.save()
+
+ # Submit form with old data
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(
+ self.entity,
+ name="Form Modified" # Different from external modification
+ )
+
+ response = self.client.post(url, form_data)
+
+ # Should handle gracefully (exact behavior depends on implementation)
+ self.assertIsInstance(response.status_code, int)
+
+ # Final state should be consistent
+ self.entity.refresh_from_db()
+ self.assertIsInstance(self.entity.name, str)
+ self.assertTrue(len(self.entity.name) > 0)
+
+ def test_view_mode_switching_integration(self):
+ """Test view behavior with different view modes - UI state integration."""
+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+
+ # Test with different view modes
+ view_modes = [ViewMode.EDIT] # Only test modes that exist
+
+ for mode in view_modes:
+ with self.subTest(view_mode=mode):
+ self.setSessionViewMode(mode)
+
+ response = self.client.get(url)
+
+ # Should handle different modes appropriately
+ self.assertIsInstance(response.status_code, int)
+
+ # Context should reflect the view mode
+ if response.status_code == 200 and hasattr(response, 'context'):
+ # Exact behavior depends on view implementation
+ self.assertIsNotNone(response.context)
+
diff --git a/src/hi/apps/entity/tests/test_file_upload_integration.py b/src/hi/apps/entity/tests/test_file_upload_integration.py
new file mode 100644
index 00000000..fd407928
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_file_upload_integration.py
@@ -0,0 +1,388 @@
+"""
+File upload context integration tests.
+
+Tests file storage patterns, upload path generation, file cleanup operations,
+and cross-owner file handling consistency using AttributeEditContext pattern.
+"""
+import logging
+from django.core.files.uploadedfile import SimpleUploadedFile
+
+from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData
+from hi.apps.entity.models import EntityAttribute
+from hi.apps.attribute.enums import AttributeValueType, AttributeType
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestFileUploadContextIntegration(BaseTestCase):
+ """Test file upload operations with AttributeEditContext integration."""
+
+ def setUp(self):
+ super().setUp()
+ self.entity = EntityAttributeSyntheticData.create_test_entity(
+ name="File Upload Test Entity"
+ )
+
+ def test_file_attribute_creation_with_context(self):
+ """Test file attribute creation provides correct context - file lifecycle integration."""
+ test_file = EntityAttributeSyntheticData.create_test_image_file()
+
+ # Create file attribute
+ file_attr = EntityAttribute.objects.create(
+ entity=self.entity,
+ name=test_file.name,
+ value="Test Image",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=test_file
+ )
+
+ # Test AttributeEditContext integration
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ context = EntityAttributeEditContext(self.entity)
+
+ # Context should provide file-related functionality
+ file_title_field = context.file_title_field_name(file_attr.id)
+ expected_field = f"file_title_{self.entity.id}_{file_attr.id}"
+ self.assertEqual(file_title_field, expected_field)
+
+ def test_file_upload_path_generation_consistency(self):
+ """Test file upload paths follow consistent patterns across contexts - storage organization."""
+ # Create file attributes for entity
+ image_file = EntityAttributeSyntheticData.create_test_image_file()
+ pdf_file = EntityAttributeSyntheticData.create_test_pdf_file()
+
+ entity_image = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="entity_image.jpg",
+ value="Entity Image",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=image_file
+ )
+
+ entity_pdf = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="entity_document.pdf",
+ value="Entity Document",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=pdf_file
+ )
+
+ # File paths should follow consistent patterns
+ self.assertTrue(hasattr(entity_image, 'file_value'))
+ self.assertTrue(hasattr(entity_pdf, 'file_value'))
+
+ # Context should handle both file types consistently
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ context = EntityAttributeEditContext(self.entity)
+
+ image_field = context.file_title_field_name(entity_image.id)
+ pdf_field = context.file_title_field_name(entity_pdf.id)
+
+ # Both should follow same naming pattern
+ self.assertRegex(image_field, r'^file_title_\d+_\d+$')
+ self.assertRegex(pdf_field, r'^file_title_\d+_\d+$')
+
+ def test_file_deletion_context_integration(self):
+ """Test file deletion with AttributeEditContext - cleanup workflow integration."""
+ test_file = SimpleUploadedFile(
+ "test_delete.txt",
+ b"content to be deleted",
+ content_type="text/plain"
+ )
+
+ file_attr = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="test_delete.txt",
+ value="File to Delete",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=test_file
+ )
+
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ context = EntityAttributeEditContext(self.entity)
+
+ # Context should provide deletion-related functionality
+ self.assertEqual(context.owner_id, self.entity.id)
+ original_count = EntityAttribute.objects.filter(entity=self.entity).count()
+
+ # Delete the attribute
+ file_attr.delete()
+
+ # Should be removed from context queries
+ new_count = EntityAttribute.objects.filter(entity=self.entity).count()
+ self.assertEqual(new_count, original_count - 1)
+
+ def test_file_title_update_context_integration(self):
+ """Test file title updates through context interface - metadata management."""
+ test_file = SimpleUploadedFile(
+ "original_title.txt",
+ b"file content",
+ content_type="text/plain"
+ )
+
+ file_attr = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="original_title.txt",
+ value="Original Title",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=test_file
+ )
+
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ context = EntityAttributeEditContext(self.entity)
+
+ # Get field name that would be used in form
+ field_name = context.file_title_field_name(file_attr.id)
+ expected_pattern = f"file_title_{self.entity.id}_{file_attr.id}"
+ self.assertEqual(field_name, expected_pattern)
+
+ # Update the title
+ new_title = "Updated File Title"
+ file_attr.value = new_title
+ file_attr.save()
+
+ # Context should reflect the updated title
+ file_attr.refresh_from_db()
+ self.assertEqual(file_attr.value, new_title)
+
+ def test_cross_owner_file_handling_consistency(self):
+ """Test file operations work consistently across Entity and Location - cross-owner compatibility."""
+ from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+ from hi.apps.location.models import LocationAttribute
+ from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
+
+ # Create location for comparison
+ location = LocationSyntheticData.create_test_location(name="File Test Location")
+
+ # Create file attributes for both entity and location
+ entity_file = SimpleUploadedFile("entity_file.txt", b"entity content")
+ location_file = SimpleUploadedFile("location_file.txt", b"location content")
+
+ entity_attr = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="entity_file.txt",
+ value="Entity File",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=entity_file
+ )
+
+ location_attr = LocationAttribute.objects.create(
+ location=location,
+ name="location_file.txt",
+ value="Location File",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=location_file
+ )
+
+ # Create contexts
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ entity_context = EntityAttributeEditContext(self.entity)
+ location_context = LocationAttributeEditContext(location)
+
+ # File field naming should follow same pattern
+ entity_field = entity_context.file_title_field_name(entity_attr.id)
+ location_field = location_context.file_title_field_name(location_attr.id)
+
+ # Both should follow pattern: file_title_{owner_id}_{attr_id}
+ self.assertRegex(entity_field, r'^file_title_\d+_\d+$')
+ self.assertRegex(location_field, r'^file_title_\d+_\d+$')
+
+ # Template context should handle files consistently
+ entity_template_ctx = entity_context.to_template_context()
+ location_template_ctx = location_context.to_template_context()
+
+ # Both should have attr_context for template usage
+ self.assertIn('attr_context', entity_template_ctx)
+ self.assertIn('attr_context', location_template_ctx)
+
+ def test_file_mime_type_detection_integration(self):
+ """Test MIME type detection works with context integration - file type handling."""
+ # Create files with different MIME types
+ image_file = SimpleUploadedFile(
+ "test_image.jpg",
+ b"fake jpeg data",
+ content_type="image/jpeg"
+ )
+
+ pdf_file = SimpleUploadedFile(
+ "test_document.pdf",
+ b"fake pdf data",
+ content_type="application/pdf"
+ )
+
+ # Create attributes with different file types
+ image_attr = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="test_image.jpg",
+ value="Test Image",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=image_file,
+ file_mime_type="image/jpeg"
+ )
+
+ pdf_attr = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="test_document.pdf",
+ value="Test Document",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=pdf_file,
+ file_mime_type="application/pdf"
+ )
+
+ # Context should work with all file types
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ context = EntityAttributeEditContext(self.entity)
+
+ # Should generate consistent field names regardless of MIME type
+ image_field = context.file_title_field_name(image_attr.id)
+ pdf_field = context.file_title_field_name(pdf_attr.id)
+
+ self.assertRegex(image_field, r'^file_title_\d+_\d+$')
+ self.assertRegex(pdf_field, r'^file_title_\d+_\d+$')
+
+ def test_large_file_handling_context_integration(self):
+ """Test large file handling with context integration - performance and storage."""
+ # Create a large file
+ large_file = EntityAttributeSyntheticData.create_large_text_file()
+
+ large_attr = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="large_file.txt",
+ value="Large File",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=large_file
+ )
+
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ context = EntityAttributeEditContext(self.entity)
+
+ # Context operations should work efficiently with large files
+ field_name = context.file_title_field_name(large_attr.id)
+ history_id = context.history_target_id(large_attr.id)
+
+ # Operations should complete without performance issues
+ self.assertIsInstance(field_name, str)
+ self.assertIsInstance(history_id, str)
+
+ def test_file_upload_form_context_integration(self):
+ """Test file upload form integration with context - upload workflow."""
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ context = EntityAttributeEditContext(self.entity)
+
+ # Context should provide template integration data
+ template_ctx = context.to_template_context()
+
+ # Should have context data needed for upload forms
+ self.assertIn('attr_context', template_ctx)
+ self.assertIn('owner', template_ctx)
+ self.assertIn('entity', template_ctx)
+
+ # Upload form would use these for generating correct field names and URLs
+ attr_context = template_ctx['attr_context']
+ self.assertEqual(attr_context.owner_type, 'entity')
+ self.assertEqual(attr_context.owner_id, self.entity.id)
+
+ def test_file_error_handling_context_integration(self):
+ """Test file error handling with context integration - error resilience."""
+ # Test with invalid file operations
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ context = EntityAttributeEditContext(self.entity)
+
+ # Context should handle edge cases gracefully
+ invalid_attr_id = 999999
+ field_name = context.file_title_field_name(invalid_attr_id)
+
+ # Should generate field name even for non-existent attribute
+ expected = f"file_title_{self.entity.id}_{invalid_attr_id}"
+ self.assertEqual(field_name, expected)
+
+ # Context operations should not depend on attribute existence
+ history_id = context.history_target_id(invalid_attr_id)
+ self.assertIn(str(invalid_attr_id), history_id)
+
+ def test_file_permissions_context_integration(self):
+ """Test file permissions with context integration - security integration."""
+ # Create file attributes with different permission levels
+ custom_file = SimpleUploadedFile("custom_file.txt", b"custom content")
+
+ # Custom attribute (can be deleted)
+ custom_attr = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="custom_file.txt",
+ value="Custom File",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=custom_file
+ )
+
+ # Predefined attribute (cannot be deleted)
+ predefined_file = SimpleUploadedFile("predefined_file.txt", b"predefined content")
+ predefined_attr = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="predefined_file.txt",
+ value="Predefined File",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.PREDEFINED),
+ file_value=predefined_file
+ )
+
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ context = EntityAttributeEditContext(self.entity)
+
+ # Context should work with both permission levels
+ custom_field = context.file_title_field_name(custom_attr.id)
+ predefined_field = context.file_title_field_name(predefined_attr.id)
+
+ # Field generation should be consistent regardless of permissions
+ self.assertRegex(custom_field, r'^file_title_\d+_\d+$')
+ self.assertRegex(predefined_field, r'^file_title_\d+_\d+$')
+
+ # Permission checking happens at the business logic level, not context level
+ self.assertTrue(custom_attr.attribute_type.can_delete)
+ self.assertFalse(predefined_attr.attribute_type.can_delete)
+
+ def test_file_history_context_integration(self):
+ """Test file attribute history with context integration - audit trail integration."""
+ test_file = SimpleUploadedFile("history_file.txt", b"original content")
+
+ file_attr = EntityAttribute.objects.create(
+ entity=self.entity,
+ name="history_file.txt",
+ value="Original Title",
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ file_value=test_file
+ )
+
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+ context = EntityAttributeEditContext(self.entity)
+
+ # Context should provide history-related functionality
+ history_target = context.history_target_id(file_attr.id)
+ history_toggle = context.history_toggle_id(file_attr.id)
+
+ expected_target = f"hi-entity-attr-history-{self.entity.id}-{file_attr.id}"
+ expected_toggle = f"history-extra-{self.entity.id}-{file_attr.id}"
+
+ self.assertEqual(history_target, expected_target)
+ self.assertEqual(history_toggle, expected_toggle)
+
+ # Update file title to create history
+ file_attr.value = "Updated Title"
+ file_attr.save()
+
+ # Context should still work after updates
+ new_history_target = context.history_target_id(file_attr.id)
+ self.assertEqual(new_history_target, expected_target) # Should be consistent
+
diff --git a/src/hi/apps/entity/tests/test_template_compatibility.py b/src/hi/apps/entity/tests/test_template_compatibility.py
new file mode 100644
index 00000000..e83e71a6
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_template_compatibility.py
@@ -0,0 +1,322 @@
+"""
+Cross-owner template compatibility tests.
+
+Verifies that Entity and Location AttributeEditContext implementations work
+identically with the same generic templates, ensuring true template generalization.
+"""
+import logging
+from unittest.mock import patch
+from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
+from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
+from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData
+from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestCrossOwnerTemplateCompatibility(BaseTestCase):
+ """Test that Entity and Location contexts work identically with generic templates."""
+
+ def setUp(self):
+ super().setUp()
+ # Create test entities and locations
+ self.entity = EntityAttributeSyntheticData.create_test_entity(name="Test Entity")
+ self.location = LocationSyntheticData.create_test_location(name="Test Location")
+
+ # Create corresponding contexts
+ self.entity_context = EntityAttributeEditContext(self.entity)
+ self.location_context = LocationAttributeEditContext(self.location)
+
+ def test_context_interface_consistency(self):
+ """Test both contexts provide identical interface - API compatibility."""
+ # Both contexts should have same methods and properties
+ entity_methods = set(dir(self.entity_context))
+ location_methods = set(dir(self.location_context))
+
+ # Should have identical public interface except for the typed property accessors
+ public_entity_methods = {m for m in entity_methods if not m.startswith('_')}
+ public_location_methods = {m for m in location_methods if not m.startswith('_')}
+
+ # Remove the unique typed accessors for comparison
+ public_entity_methods.discard('entity')
+ public_location_methods.discard('location')
+
+ self.assertEqual(public_entity_methods, public_location_methods)
+
+ def test_url_pattern_consistency(self):
+ """Test URL patterns follow same structure across owner types - routing compatibility."""
+ # URL name patterns should be consistent
+ self.assertEqual(
+ self.entity_context.history_url_name,
+ "entity_attribute_history_inline"
+ )
+ self.assertEqual(
+ self.location_context.history_url_name,
+ "location_attribute_history_inline"
+ )
+
+ # Parameter name patterns should be consistent
+ self.assertEqual(
+ self.entity_context.owner_id_param_name,
+ "entity_id"
+ )
+ self.assertEqual(
+ self.location_context.owner_id_param_name,
+ "location_id"
+ )
+
+ def test_dom_id_pattern_consistency(self):
+ """Test DOM ID generation follows same patterns - JavaScript compatibility."""
+ attribute_id = 123
+
+ # History target IDs should follow same pattern
+ entity_history = self.entity_context.history_target_id(attribute_id)
+ location_history = self.location_context.history_target_id(attribute_id)
+
+ # Both should follow pattern: hi-{type}-attr-history-{owner_id}-{attr_id}
+ self.assertRegex(entity_history, r'^hi-entity-attr-history-\d+-123$')
+ self.assertRegex(location_history, r'^hi-location-attr-history-\d+-123$')
+
+ # Toggle IDs should follow same pattern (no owner type in these)
+ entity_toggle = self.entity_context.history_toggle_id(attribute_id)
+ location_toggle = self.location_context.history_toggle_id(attribute_id)
+
+ # Both should follow pattern: history-extra-{owner_id}-{attr_id}
+ self.assertRegex(entity_toggle, r'^history-extra-\d+-123$')
+ self.assertRegex(location_toggle, r'^history-extra-\d+-123$')
+
+ def test_form_field_naming_consistency(self):
+ """Test form field naming follows same patterns - form compatibility."""
+ attribute_id = 456
+
+ entity_field = self.entity_context.file_title_field_name(attribute_id)
+ location_field = self.location_context.file_title_field_name(attribute_id)
+
+ # Both should follow pattern: file_title_{owner_id}_{attr_id}
+ self.assertRegex(entity_field, r'^file_title_\d+_456$')
+ self.assertRegex(location_field, r'^file_title_\d+_456$')
+
+ def test_template_context_structure_compatibility(self):
+ """Test template contexts have same structure - template compatibility."""
+ entity_context = self.entity_context.to_template_context()
+ location_context = self.location_context.to_template_context()
+
+ # Should have same set of keys (except for owner-specific ones)
+ entity_keys = set(entity_context.keys())
+ location_keys = set(location_context.keys())
+
+ # Common keys that both should have
+ common_keys = {'attr_context', 'owner'}
+ self.assertTrue(common_keys.issubset(entity_keys))
+ self.assertTrue(common_keys.issubset(location_keys))
+
+ # Entity context should have 'entity' key, Location should have 'location' key
+ self.assertIn('entity', entity_keys)
+ self.assertNotIn('location', entity_keys)
+
+ self.assertIn('location', location_keys)
+ self.assertNotIn('entity', location_keys)
+
+ def test_template_context_generic_aliases(self):
+ """Test generic aliases work consistently - template abstraction."""
+ entity_context = self.entity_context.to_template_context()
+ location_context = self.location_context.to_template_context()
+
+ # Generic 'owner' should point to correct instance
+ self.assertIs(entity_context['owner'], self.entity)
+ self.assertIs(location_context['owner'], self.location)
+
+ # attr_context should be the context instance itself
+ self.assertIs(entity_context['attr_context'], self.entity_context)
+ self.assertIs(location_context['attr_context'], self.location_context)
+
+ def test_cross_owner_template_filter_compatibility(self):
+ """Test template filters work identically with both contexts - filter compatibility."""
+ from hi.apps.attribute.templatetags.attribute_extras import (
+ file_title_field_name, history_target_id, history_toggle_id
+ )
+
+ attribute_id = 789
+
+ # Template filters should work with both contexts
+ entity_field = file_title_field_name(self.entity_context, attribute_id)
+ location_field = file_title_field_name(self.location_context, attribute_id)
+
+ entity_history = history_target_id(self.entity_context, attribute_id)
+ location_history = history_target_id(self.location_context, attribute_id)
+
+ entity_toggle = history_toggle_id(self.entity_context, attribute_id)
+ location_toggle = history_toggle_id(self.location_context, attribute_id)
+
+ # All should produce valid results following same patterns
+ self.assertRegex(entity_field, r'^file_title_\d+_789$')
+ self.assertRegex(location_field, r'^file_title_\d+_789$')
+
+ self.assertRegex(entity_history, r'^hi-entity-attr-history-\d+-789$')
+ self.assertRegex(location_history, r'^hi-location-attr-history-\d+-789$')
+
+ self.assertRegex(entity_toggle, r'^history-extra-\d+-789$')
+ self.assertRegex(location_toggle, r'^history-extra-\d+-789$')
+
+ @patch('django.urls.reverse')
+ def test_cross_owner_template_tag_compatibility(self, mock_reverse):
+ """Test template tags work identically with both contexts - tag compatibility."""
+ from hi.apps.attribute.templatetags.attribute_extras import (
+ attr_history_url, attr_restore_url
+ )
+
+ mock_reverse.return_value = '/test/url/'
+ attribute_id = 999
+ history_id = 111
+
+ # History URL tag
+ attr_history_url(self.entity_context, attribute_id)
+ entity_call = mock_reverse.call_args
+
+ mock_reverse.reset_mock()
+ attr_history_url(self.location_context, attribute_id)
+ location_call = mock_reverse.call_args
+
+ # Should use different URL names but same parameter structure
+ self.assertEqual(entity_call[0][0], 'entity_attribute_history_inline')
+ self.assertEqual(location_call[0][0], 'location_attribute_history_inline')
+
+ # Both should have same parameter structure
+ entity_kwargs = entity_call[1]['kwargs']
+ location_kwargs = location_call[1]['kwargs']
+
+ self.assertIn('entity_id', entity_kwargs)
+ self.assertIn('attribute_id', entity_kwargs)
+ self.assertEqual(entity_kwargs['attribute_id'], attribute_id)
+
+ self.assertIn('location_id', location_kwargs)
+ self.assertIn('attribute_id', location_kwargs)
+ self.assertEqual(location_kwargs['attribute_id'], attribute_id)
+
+ # Restore URL tag
+ mock_reverse.reset_mock()
+ attr_restore_url(self.entity_context, attribute_id, history_id)
+ entity_restore_call = mock_reverse.call_args
+
+ mock_reverse.reset_mock()
+ attr_restore_url(self.location_context, attribute_id, history_id)
+ location_restore_call = mock_reverse.call_args
+
+ # Should follow same pattern with history_id parameter
+ entity_restore_kwargs = entity_restore_call[1]['kwargs']
+ location_restore_kwargs = location_restore_call[1]['kwargs']
+
+ self.assertEqual(entity_restore_kwargs['history_id'], history_id)
+ self.assertEqual(location_restore_kwargs['history_id'], history_id)
+
+ def test_context_property_computation_consistency(self):
+ """Test property computation follows same logic - computation compatibility."""
+ # Test various attribute IDs with both contexts
+ test_attribute_ids = [1, 100, 999, 0]
+
+ for attr_id in test_attribute_ids:
+ with self.subTest(attribute_id=attr_id):
+ # History target IDs should follow same computation
+ entity_history = self.entity_context.history_target_id(attr_id)
+ location_history = self.location_context.history_target_id(attr_id)
+
+ # Both should include owner ID and attribute ID
+ self.assertIn(str(self.entity.id), entity_history)
+ self.assertIn(str(attr_id), entity_history)
+
+ self.assertIn(str(self.location.id), location_history)
+ self.assertIn(str(attr_id), location_history)
+
+ # Toggle IDs should be computed identically (no owner type)
+ entity_toggle = self.entity_context.history_toggle_id(attr_id)
+ location_toggle = self.location_context.history_toggle_id(attr_id)
+
+ # Structure should be identical (just different owner IDs)
+ entity_parts = entity_toggle.split('-')
+ location_parts = location_toggle.split('-')
+
+ self.assertEqual(len(entity_parts), len(location_parts))
+ self.assertEqual(entity_parts[0], location_parts[0]) # 'history'
+ self.assertEqual(entity_parts[1], location_parts[1]) # 'extra'
+ self.assertEqual(entity_parts[3], location_parts[3]) # attribute_id
+
+ def test_inheritance_hierarchy_consistency(self):
+ """Test both contexts inherit from same base class - inheritance compatibility."""
+ from hi.apps.attribute.edit_context import AttributeEditContext
+
+ self.assertIsInstance(self.entity_context, AttributeEditContext)
+ self.assertIsInstance(self.location_context, AttributeEditContext)
+
+ # Both should inherit all base methods
+ base_methods = [m for m in dir(AttributeEditContext) if not m.startswith('_')]
+
+ for method in base_methods:
+ with self.subTest(method=method):
+ self.assertTrue(hasattr(self.entity_context, method))
+ self.assertTrue(hasattr(self.location_context, method))
+
+ def test_typed_property_accessors(self):
+ """Test typed property accessors work correctly - type safety."""
+ # Entity context should provide typed entity accessor
+ self.assertIs(self.entity_context.entity, self.entity)
+ self.assertEqual(self.entity_context.entity.name, "Test Entity")
+
+ # Location context should provide typed location accessor
+ self.assertIs(self.location_context.location, self.location)
+ self.assertEqual(self.location_context.location.name, "Test Location")
+
+ # Both should also work through generic owner property
+ self.assertIs(self.entity_context.owner, self.entity)
+ self.assertIs(self.location_context.owner, self.location)
+
+ def test_edge_case_compatibility(self):
+ """Test edge cases work consistently across both contexts - robustness compatibility."""
+ # Test with special characters in names
+ special_entity = EntityAttributeSyntheticData.create_test_entity(
+ name="Entity with & symbols!"
+ )
+ special_location = LocationSyntheticData.create_test_location(
+ name="Location with & symbols!"
+ )
+
+ entity_ctx = EntityAttributeEditContext(special_entity)
+ location_ctx = LocationAttributeEditContext(special_location)
+
+ # Both should handle special characters in names
+ self.assertEqual(entity_ctx.owner_name, "Entity with & symbols!")
+ self.assertEqual(location_ctx.owner_name, "Location with & symbols!")
+
+ # DOM IDs should still be generated properly
+ entity_id = entity_ctx.history_target_id(1)
+ location_id = location_ctx.history_target_id(1)
+
+ self.assertIn("hi-entity-attr-history", entity_id)
+ self.assertIn("hi-location-attr-history", location_id)
+
+ def test_template_generalization_effectiveness(self):
+ """Test that template generalization actually works - integration verification."""
+ # This test verifies that the same template code can work with both contexts
+
+ # Simulate template context usage
+ entity_template_ctx = self.entity_context.to_template_context()
+ location_template_ctx = self.location_context.to_template_context()
+
+ # Both contexts should allow the same template operations
+ # Template would access: {{ owner.name }}, {{ attr_context.owner_id }}, etc.
+
+ # Generic owner access
+ self.assertEqual(entity_template_ctx['owner'].name, "Test Entity")
+ self.assertEqual(location_template_ctx['owner'].name, "Test Location")
+
+ # Context property access
+ self.assertIsInstance(entity_template_ctx['attr_context'].owner_id, int)
+ self.assertIsInstance(location_template_ctx['attr_context'].owner_id, int)
+
+ # URL parameter access
+ self.assertEqual(entity_template_ctx['attr_context'].owner_id_param_name, "entity_id")
+ self.assertEqual(location_template_ctx['attr_context'].owner_id_param_name, "location_id")
+
+ # This demonstrates that a template using these patterns would work identically
+ # with both Entity and Location contexts, achieving true generalization
+
diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.py
index b9608f0e..e59a29b1 100644
--- a/src/hi/apps/entity/tests/test_views.py
+++ b/src/hi/apps/entity/tests/test_views.py
@@ -1,5 +1,5 @@
import logging
-from unittest.mock import Mock, patch
+from unittest.mock import patch
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import transaction
@@ -731,193 +731,6 @@ class TestEntityEditModeView(SyncViewTestCase):
self.assertNotEqual(response.status_code, 200)
-class TestEntityAttributeHistoryView(DualModeViewTestCase):
- """
- Tests for EntityAttributeHistoryView - displays EntityAttribute value history in a modal.
- This view shows historical changes and allows restoring previous values.
- """
-
- def setUp(self):
- super().setUp()
- # Create test entity
- self.entity = Entity.objects.create(
- integration_id='test.entity',
- integration_name='test_integration',
- name='Test Entity',
- entity_type_str=str(EntityType.LIGHT)
- )
- # Create test attribute
- self.attribute = EntityAttribute.objects.create(
- entity=self.entity,
- name='brightness',
- value='100',
- attribute_type_str=str(AttributeValueType.TEXT)
- )
-
- def test_get_history_sync(self):
- """Test getting attribute history with synchronous request."""
- url = reverse('entity_attribute_history', kwargs={'attribute_id': self.attribute.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertHtmlResponse(response)
- self.assertTemplateRendered(response, 'attribute/modals/attribute_history.html')
-
- # Verify context data
- self.assertEqual(response.context['attribute'], self.attribute)
- self.assertIn('history_records', response.context)
-
- def test_get_history_async(self):
- """Test getting attribute history with AJAX request."""
- url = reverse('entity_attribute_history', kwargs={'attribute_id': self.attribute.id})
- response = self.async_get(url)
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
- self.assertTemplateRendered(response, 'attribute/modals/attribute_history.html')
-
- @patch.object(EntityAttribute, '_get_history_model_class')
- def test_history_with_no_history_model(self, mock_get_history_model):
- """Test history view when attribute has no history model."""
- mock_get_history_model.return_value = None
-
- url = reverse('entity_attribute_history', kwargs={'attribute_id': self.attribute.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertHtmlResponse(response)
-
- # Should show empty history
- self.assertEqual(len(response.context['history_records']), 0)
-
- @patch.object(EntityAttribute, '_get_history_model_class')
- def test_history_with_records(self, mock_get_history_model):
- """Test history view with actual history records."""
- # Mock history model and records
- mock_history_model = Mock()
- mock_get_history_model.return_value = mock_history_model
-
- mock_record = Mock()
- mock_record.pk = 1
- mock_record.value = '75'
- mock_record.changed_datetime = Mock()
-
- # Create proper mock chain for queryset slicing
- mock_queryset = Mock()
- mock_queryset.__getitem__ = Mock(return_value=[mock_record])
- mock_history_model.objects.filter.return_value.order_by.return_value = mock_queryset
-
- url = reverse('entity_attribute_history', kwargs={'attribute_id': self.attribute.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertEqual(response.context['attribute'], self.attribute)
- self.assertEqual(list(response.context['history_records']), [mock_record])
-
- def test_nonexistent_attribute_returns_404(self):
- """Test that accessing nonexistent attribute returns 404."""
- url = reverse('entity_attribute_history', kwargs={'attribute_id': 99999})
- response = self.client.get(url)
-
- self.assertEqual(response.status_code, 404)
-
- def test_post_not_allowed(self):
- """Test that POST requests are not allowed."""
- url = reverse('entity_attribute_history', kwargs={'attribute_id': self.attribute.id})
- response = self.client.post(url)
-
- self.assertEqual(response.status_code, 405)
-
-
-class TestEntityAttributeRestoreView(SyncViewTestCase):
- """
- Tests for EntityAttributeRestoreView - restores EntityAttribute values from history.
- This view handles POST requests to restore previous attribute values.
- """
-
- def setUp(self):
- super().setUp()
- # Create test entity
- self.entity = Entity.objects.create(
- integration_id='test.entity',
- integration_name='test_integration',
- name='Test Entity',
- entity_type_str=str(EntityType.LIGHT)
- )
- # Create test attribute
- self.attribute = EntityAttribute.objects.create(
- entity=self.entity,
- name='brightness',
- value='100',
- attribute_type_str=str(AttributeValueType.TEXT)
- )
-
- @patch.object(EntityAttribute, '_get_history_model_class')
- def test_restore_with_valid_history_record(self, mock_get_history_model):
- """Test successful restore with valid history record."""
- # Mock history model and record
- mock_history_model = Mock()
- mock_get_history_model.return_value = mock_history_model
-
- mock_history_record = Mock()
- mock_history_record.value = '75'
- mock_history_model.objects.get.return_value = mock_history_record
-
- url = reverse('entity_attribute_restore', kwargs={'attribute_id': self.attribute.id})
- response = self.client.post(url, {'history_id': '1'})
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
-
- # Verify attribute was updated
- self.attribute.refresh_from_db()
- self.assertEqual(self.attribute.value, '75')
-
- @patch.object(EntityAttribute, '_get_history_model_class')
- def test_restore_with_no_history_model(self, mock_get_history_model):
- """Test restore when attribute has no history model."""
- mock_get_history_model.return_value = None
-
- url = reverse('entity_attribute_restore', kwargs={'attribute_id': self.attribute.id})
- response = self.client.post(url, {'history_id': '1'})
-
- self.assertEqual(response.status_code, 404)
-
- def test_restore_without_history_id(self):
- """Test restore request without history_id parameter."""
- url = reverse('entity_attribute_restore', kwargs={'attribute_id': self.attribute.id})
- response = self.client.post(url, {})
-
- self.assertEqual(response.status_code, 404)
-
- @patch.object(EntityAttribute, '_get_history_model_class')
- def test_restore_with_nonexistent_history_record(self, mock_get_history_model):
- """Test restore with non-existent history record."""
- mock_history_model = Mock()
- mock_get_history_model.return_value = mock_history_model
- mock_history_model.DoesNotExist = Exception
- mock_history_model.objects.get.side_effect = mock_history_model.DoesNotExist()
-
- url = reverse('entity_attribute_restore', kwargs={'attribute_id': self.attribute.id})
- response = self.client.post(url, {'history_id': '999'})
-
- self.assertEqual(response.status_code, 404)
-
- def test_restore_nonexistent_attribute_returns_404(self):
- """Test that restoring nonexistent attribute returns 404."""
- url = reverse('entity_attribute_restore', kwargs={'attribute_id': 99999})
- response = self.client.post(url, {'history_id': '1'})
-
- self.assertEqual(response.status_code, 404)
-
- def test_get_not_allowed(self):
- """Test that GET requests are not allowed."""
- url = reverse('entity_attribute_restore', kwargs={'attribute_id': self.attribute.id})
- response = self.client.get(url)
-
- self.assertEqual(response.status_code, 405)
-
-
class TestEntityEditViewFileUploadIntegration(DualModeViewTestCase):
"""Integration tests for EntityEditView file upload flows.
diff --git a/src/hi/apps/entity/urls.py b/src/hi/apps/entity/urls.py
index bfb84c60..1f0e489d 100644
--- a/src/hi/apps/entity/urls.py
+++ b/src/hi/apps/entity/urls.py
@@ -9,10 +9,6 @@ urlpatterns = [
views.EntityEditView.as_view(),
name='entity_edit'),
- re_path( r'^entity/properties/edit/(?P<entity_id>\d+)$',
- views.EntityPropertiesEditView.as_view(),
- name='entity_properties_edit'),
-
re_path( r'^status/(?P<entity_id>\d+)$',
views.EntityStatusView.as_view(),
name='entity_status' ),
@@ -21,29 +17,17 @@ urlpatterns = [
views.EntityStateHistoryView.as_view(),
name='entity_state_history' ),
- re_path( r'^edit_mode/(?P<entity_id>\d+)$',
- views.EntityEditModeView.as_view(),
- name='entity_edit_mode' ),
-
re_path( r'^attribute/upload/(?P<entity_id>\d+)$',
views.EntityAttributeUploadView.as_view(),
- name='entity_attribute_upload'),
-
- re_path( r'^attribute/history/(?P<attribute_id>\d+)$',
- views.EntityAttributeHistoryView.as_view(),
- name='entity_attribute_history'),
-
- re_path( r'^attribute/restore/(?P<attribute_id>\d+)$',
- views.EntityAttributeRestoreView.as_view(),
- name='entity_attribute_restore'),
+ name='entity_attribute_upload' ),
- re_path( r'^entity/(?P<entity_id>\d+)/attribute/(?P<attribute_id>\d+)/history/inline/$',
+ re_path( r'^attribute/history/(?P<entity_id>\d+)/(?P<attribute_id>\d+)/$',
views.EntityAttributeHistoryInlineView.as_view(),
- name='entity_attribute_history_inline'),
+ name='entity_attribute_history_inline' ),
- re_path( r'^entity/(?P<entity_id>\d+)/attribute/(?P<attribute_id>\d+)/restore/inline/(?P<history_id>\d+)/$',
+ re_path( r'^attribute/restore/(?P<entity_id>\d+)/(?P<attribute_id>\d+)/(?P<history_id>\d+)/$',
views.EntityAttributeRestoreInlineView.as_view(),
- name='entity_attribute_restore_inline'),
+ name='entity_attribute_restore_inline' ),
re_path( r'^edit/', include('hi.apps.entity.edit.urls' )),
diff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.py
index 2f369883..c89b4c01 100644
--- a/src/hi/apps/entity/views.py
+++ b/src/hi/apps/entity/views.py
@@ -1,35 +1,31 @@
import logging
-from typing import Any, Dict, Optional, TYPE_CHECKING
+from typing import Any, Dict
from django.db import transaction
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
-from django.template.loader import get_template, render_to_string
+from django.template.loader import render_to_string
from django.views.generic import View
from hi.apps.attribute.views import BaseAttributeHistoryView, BaseAttributeRestoreView
import hi.apps.common.antinode as antinode
from hi.apps.control.controller_history_manager import ControllerHistoryManager
-from hi.apps.location.location_manager import LocationManager
from hi.apps.monitor.status_display_manager import StatusDisplayManager
from hi.apps.sense.sensor_history_manager import SensorHistoryMixin
from hi.views import page_not_found_response
-from hi.hi_async_view import HiModalView, HiSideView
+from hi.hi_async_view import HiModalView
from hi.constants import DIVID
from .entity_edit_form_handler import EntityEditFormHandler
from .entity_edit_response_renderer import EntityEditResponseRenderer
-from .entity_manager import EntityManager
-from .entity_type_transition_handler import EntityTypeTransitionHandler
from . import forms
from .models import Entity, EntityAttribute
from .transient_models import EntityStateHistoryData
from .view_mixins import EntityViewMixin
+from .entity_attribute_edit_context import EntityAttributeEditContext
-if TYPE_CHECKING:
- from hi.apps.location.models import LocationView
logger = logging.getLogger(__name__)
@@ -107,82 +103,7 @@ class EntityEditView(HiModalView, EntityViewMixin):
def get_success_url_name(self) -> str:
return 'entity_edit'
-
-class EntityEditModeView( HiSideView, EntityViewMixin ):
-
- def get_template_name( self ) -> str:
- return 'entity/edit/panes/entity_edit_mode_panel.html'
-
- def should_push_url( self ) -> bool:
- return True
-
- def get_template_context( self,
- request : HttpRequest,
- *args : Any,
- **kwargs: Any ) -> Dict[str, Any]:
- entity: Entity = self.get_entity( request, *args, **kwargs )
-
- current_location_view: Optional['LocationView'] = None
- if request.view_parameters.view_type.is_location_view:
- current_location_view = LocationManager().get_default_location_view( request = request )
-
- entity_edit_mode_data = EntityManager().get_entity_edit_mode_data(
- entity = entity,
- location_view = current_location_view,
- is_editing = request.view_parameters.is_editing,
- )
- return entity_edit_mode_data.to_template_context()
-
-
-class EntityPropertiesEditView( View, EntityViewMixin ):
- """Handle entity properties editing (name, type) only - used by sidebar.
-
- Business logic is delegated to EntityTypeTransitionHandler following
- the "keep views simple" design philosophy.
- """
-
- def post( self,
- request : HttpRequest,
- *args : Any,
- **kwargs: Any ) -> HttpResponse:
- entity: Entity = self.get_entity( request, *args, **kwargs )
-
- # Store original entity_type_str to detect changes
- original_entity_type_str: str = entity.entity_type_str
-
- entity_form: forms.EntityForm = forms.EntityForm( request.POST, instance = entity )
- form_valid: bool = entity_form.is_valid()
-
- if form_valid:
- # Delegate transition handling to specialized handler
- transition_handler = EntityTypeTransitionHandler()
-
- transition_response: Optional[HttpResponse] = transition_handler.handle_entity_form_save(
- request, entity, entity_form, None, original_entity_type_str
- )
-
- # Now that transaction is committed, handle any transition response
- if transition_response is not None:
- return transition_response
-
- status_code: int = 200
- else:
- status_code: int = 400
- context: Dict[str, Any] = {
- 'entity': entity,
- 'entity_form': entity_form,
- }
- template = get_template( 'entity/edit/panes/entity_properties_edit.html' )
- content: str = template.render( context, request = request )
- return antinode.response(
- insert_map = {
- DIVID['ENTITY_PROPERTIES_PANE']: content,
- },
- status = status_code,
- )
-
-
class EntityStateHistoryView( HiModalView, EntityViewMixin, SensorHistoryMixin ):
ENTITY_STATE_HISTORY_ITEM_MAX = 5
@@ -231,9 +152,13 @@ class EntityAttributeUploadView( View, EntityViewMixin ):
entity_attribute_upload_form.save()
# Render new file card HTML to append to file grid
+ attr_context = EntityAttributeEditContext(entity)
+ context = {'attribute': entity_attribute, 'entity': entity}
+ context.update(attr_context.to_template_context())
+
file_card_html: str = render_to_string(
'attribute/components/file_card.html',
- {'attribute': entity_attribute, 'entity': entity},
+ context,
request=request
)
@@ -260,26 +185,6 @@ class EntityAttributeUploadView( View, EntityViewMixin ):
status=400
)
-
-class EntityAttributeHistoryView(BaseAttributeHistoryView):
- """View for displaying EntityAttribute history in a modal."""
-
- def get_attribute_model_class(self):
- return EntityAttribute
-
- def get_history_url_name(self):
- return 'entity_attribute_history'
-
- def get_restore_url_name(self):
- return 'entity_attribute_restore'
-
-
-class EntityAttributeRestoreView(BaseAttributeRestoreView):
- """View for restoring EntityAttribute values from history."""
-
- def get_attribute_model_class(self):
- return EntityAttribute
-
class EntityAttributeHistoryInlineView(BaseAttributeHistoryView):
"""View for displaying EntityAttribute history inline within the edit modal."""
@@ -319,6 +224,9 @@ class EntityAttributeHistoryInlineView(BaseAttributeHistoryView):
else:
history_records = []
+ # Create the attribute edit context for template generalization
+ attr_context = EntityAttributeEditContext(attribute.entity)
+
context: Dict[str, Any] = {
'entity': attribute.entity,
'attribute': attribute,
@@ -327,6 +235,9 @@ class EntityAttributeHistoryInlineView(BaseAttributeHistoryView):
'restore_url_name': self.get_restore_url_name(),
}
+ # Merge in the context variables from AttributeEditContext
+ context.update(attr_context.to_template_context())
+
# Use Django render shortcut
return render(request, self.get_template_name(), context)
@@ -367,9 +278,10 @@ class EntityAttributeRestoreInlineView(BaseAttributeRestoreView):
# Delegate to EntityEditView logic to return updated modal content
entity: Entity = attribute.entity
- # Use EntityEditView's _render_success_response logic
- entity_edit_view: EntityEditView = EntityEditView()
- return entity_edit_view._render_success_response(
+ # Use EntityEditResponseRenderer to return updated modal content
+ from .entity_edit_response_renderer import EntityEditResponseRenderer
+ renderer: EntityEditResponseRenderer = EntityEditResponseRenderer()
+ return renderer.render_success_response(
request = request,
entity = entity,
)
diff --git a/src/hi/apps/location/edit/forms.py b/src/hi/apps/location/edit/forms.py
index a7008be0..3e25fd81 100644
--- a/src/hi/apps/location/edit/forms.py
+++ b/src/hi/apps/location/edit/forms.py
@@ -4,14 +4,12 @@ import os
from django import forms
from django.conf import settings
-from hi.apps.attribute.forms import AttributeForm, AttributeUploadForm
from hi.apps.common.svg_forms import SvgDecimalFormField, SvgFileForm
from hi.apps.common.svg_models import SvgItemPositionBounds
from hi.apps.location.enums import LocationViewType, SvgStyleName
from hi.apps.location.models import (
Location,
- LocationAttribute,
LocationView,
)
@@ -72,27 +70,6 @@ class LocationEditForm( forms.ModelForm ):
'svg_view_box_str': forms.TextInput( attrs={'class': 'form-control', 'readonly': True } ),
}
-
-class LocationAttributeForm( AttributeForm ):
- class Meta( AttributeForm.Meta ):
- model = LocationAttribute
-
-
-LocationAttributeFormSet = forms.inlineformset_factory(
- Location,
- LocationAttribute,
- form = LocationAttributeForm,
- extra = 1,
- max_num = 100,
- absolute_max = 100,
- can_delete = True,
-)
-
-
-class LocationAttributeUploadForm( AttributeUploadForm ):
- class Meta( AttributeUploadForm.Meta ):
- model = LocationAttribute
-
class LocationViewAddForm(forms.Form):
diff --git a/src/hi/apps/location/edit/tests/test_views.py b/src/hi/apps/location/edit/tests/test_views.py
index b0ce0c27..141d054a 100644
--- a/src/hi/apps/location/edit/tests/test_views.py
+++ b/src/hi/apps/location/edit/tests/test_views.py
@@ -276,241 +276,8 @@ class TestLocationSvgReplaceView(DualModeViewTestCase):
self.assertEqual(response.status_code, 404)
-class TestLocationEditView(SyncViewTestCase):
- """
- Tests for LocationEditView - demonstrates location editing testing.
- This view handles location property updates and attribute management.
- """
-
- def setUp(self):
- super().setUp()
- # Create test location using synthetic data
- self.location = LocationSyntheticData.create_test_location(
- name='Test Location',
- svg_fragment_filename='test.svg',
- svg_view_box_str='0 0 100 100'
- )
-
- def test_get_location_edit(self):
- """Test GET request for location edit."""
- url = reverse('location_edit_location_edit', kwargs={'location_id': self.location.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response) # LocationEditView returns JSON modal
-
- def test_post_valid_edit_with_changes(self):
- """Test POST request with valid edit data that has changes."""
- original_name = self.location.name
-
- url = reverse('location_edit_location_edit', kwargs={'location_id': self.location.id})
- formset_prefix = f'location-{self.location.id}'
- response = self.client.post(url, {
- 'name': 'Updated Location Name',
- 'order_id': '0', # Required field
- 'svg_view_box_str': self.location.svg_view_box_str, # Keep original
- # Add formset management form fields with correct prefix
- f'{formset_prefix}-TOTAL_FORMS': '0',
- f'{formset_prefix}-INITIAL_FORMS': '0',
- f'{formset_prefix}-MIN_NUM_FORMS': '0',
- f'{formset_prefix}-MAX_NUM_FORMS': '1000',
- })
-
- # Expect antinode.js response (200 with JSON)
- self.assertEqual(response.status_code, 200)
-
- # Verify the location was actually updated
- updated_location = Location.objects.get(id=self.location.id)
- self.assertEqual(updated_location.name, 'Updated Location Name')
- self.assertNotEqual(updated_location.name, original_name)
-
- def test_post_valid_edit_without_changes(self):
- """Test POST request with valid edit data that has no changes."""
- # Submit the same data that already exists (no changes)
- url = reverse('location_edit_location_edit', kwargs={'location_id': self.location.id})
- formset_prefix = f'location-{self.location.id}'
- response = self.client.post(url, {
- 'name': self.location.name, # Same name - no change
- 'order_id': '0', # Required field
- 'svg_view_box_str': self.location.svg_view_box_str, # Same viewbox
- # Add formset management form fields with correct prefix
- f'{formset_prefix}-TOTAL_FORMS': '0',
- f'{formset_prefix}-INITIAL_FORMS': '0',
- f'{formset_prefix}-MIN_NUM_FORMS': '0',
- f'{formset_prefix}-MAX_NUM_FORMS': '1000',
- })
-
- # Expect antinode.js response (200 with JSON)
- self.assertEqual(response.status_code, 200)
-
- # Verify location was not changed (same name)
- unchanged_location = Location.objects.get(id=self.location.id)
- self.assertEqual(unchanged_location.name, self.location.name)
-
- def test_post_invalid_edit(self):
- """Test POST request with invalid edit data."""
- url = reverse('location_edit_location_edit', kwargs={'location_id': self.location.id})
- formset_prefix = f'location-{self.location.id}'
- response = self.client.post(url, {
- 'name': '', # Empty name should cause validation error
- 'order_id': '0', # Required field
- 'svg_view_box_str': self.location.svg_view_box_str,
- # Add formset management fields (even though the form has errors)
- f'{formset_prefix}-TOTAL_FORMS': '0',
- f'{formset_prefix}-INITIAL_FORMS': '0',
- f'{formset_prefix}-MIN_NUM_FORMS': '0',
- f'{formset_prefix}-MAX_NUM_FORMS': '1000',
- })
-
- # Should return 200 with form errors displayed
- self.assertEqual(response.status_code, 200)
-
- # Verify location was not changed
- unchanged_location = Location.objects.get(id=self.location.id)
- self.assertEqual(unchanged_location.name, self.location.name) # Should remain unchanged
-
- def test_nonexistent_location_returns_404(self):
- """Test that accessing nonexistent location returns 404."""
- url = reverse('location_edit_location_edit', kwargs={'location_id': 99999})
- response = self.client.get(url)
-
- self.assertEqual(response.status_code, 404)
-
-
-class TestLocationPropertiesEditView(SyncViewTestCase):
- """
- Tests for LocationPropertiesEditView - handles location properties (name, order_id, svg_view_box_str) editing only.
- This view is used by the sidebar in edit mode and only accepts POST requests.
- """
-
- def setUp(self):
- super().setUp()
- # Create test location
- self.location = Location.objects.create(
- name='Test Properties Location',
- svg_fragment_filename='test_props.svg',
- svg_view_box_str='0 0 100 100'
- )
-
- def test_post_valid_properties_edit(self):
- """Test successful location properties edit."""
- url = reverse('location_properties_edit', kwargs={'location_id': self.location.id})
-
- form_data = {
- 'name': 'Updated Properties Name',
- 'order_id': 5,
- 'svg_view_box_str': '0 0 200 200',
- }
-
- response = self.client.post(url, form_data)
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
-
- # Verify location was actually updated
- self.location.refresh_from_db()
- self.assertEqual(self.location.name, 'Updated Properties Name')
- self.assertEqual(self.location.order_id, 5)
- self.assertEqual(self.location.svg_view_box_str, '0 0 200 200')
-
- def test_nonexistent_location_returns_404(self):
- """Test that editing nonexistent location returns 404."""
- url = reverse('location_properties_edit', kwargs={'location_id': 99999})
- response = self.client.post(url, {'name': 'Test', 'order_id': 1})
-
- self.assertEqual(response.status_code, 404)
-
- def test_get_not_allowed(self):
- """Test that GET requests are not allowed (only POST)."""
- url = reverse('location_properties_edit', kwargs={'location_id': self.location.id})
- response = self.client.get(url)
-
- self.assertEqual(response.status_code, 405)
-
-
-class TestLocationAttributeUploadView(SyncViewTestCase):
- """
- Tests for LocationAttributeUploadView - demonstrates location attribute upload testing.
- This view handles uploading location attribute files.
- """
-
- def setUp(self):
- super().setUp()
- # Create test location using synthetic data
- self.location = LocationSyntheticData.create_test_location(
- name='Test Location',
- svg_fragment_filename='test.svg',
- svg_view_box_str='0 0 100 100'
- )
-
- def test_post_valid_upload(self):
- """Test POST request with valid upload data."""
- url = reverse('location_attribute_upload', kwargs={'location_id': self.location.id})
-
- # Create test file
- test_file = SimpleUploadedFile(
- 'test_document.pdf',
- b'fake pdf content for testing',
- content_type='application/pdf'
- )
-
- # Post with file_value field
- response = self.client.post(url, {'file_value': test_file})
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
-
- # Verify the attribute was created with name from filename
- from hi.apps.location.models import LocationAttribute
- uploaded_attr = LocationAttribute.objects.filter(
- location=self.location,
- name='test_document.pdf' # Full filename is used as name
- ).first()
- self.assertIsNotNone(uploaded_attr)
- # File uploads don't have a text value, they have file_value
- self.assertTrue(uploaded_attr.file_value)
-
- def test_post_invalid_upload(self):
- """Test POST request with invalid upload data."""
- url = reverse('location_attribute_upload', kwargs={'location_id': self.location.id})
-
- # Send invalid data - missing required file_value
- test_data = {}
- # No files provided - file_value is required
-
- response = self.client.post(url, data=test_data)
-
- # Form is invalid but view returns 200 with modal containing form errors
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
-
- # Verify response contains modal with form
- data = response.json()
- self.assertIn('modal', data)
- modal_content = data['modal']
- self.assertIn('file_value', modal_content) # Form field should be present
-
- # Verify no attribute was created
- from hi.apps.location.models import LocationAttribute
- uploaded_attrs = LocationAttribute.objects.filter(
- location=self.location,
- name='test_document'
- )
- self.assertEqual(uploaded_attrs.count(), 0)
-
- def test_nonexistent_location_returns_404(self):
- """Test that accessing nonexistent location returns 404."""
- url = reverse('location_attribute_upload', kwargs={'location_id': 99999})
- response = self.client.post(url, {})
-
- self.assertEqual(response.status_code, 404)
-
- def test_get_not_allowed(self):
- """Test that GET requests are not allowed."""
- url = reverse('location_attribute_upload', kwargs={'location_id': self.location.id})
- response = self.client.get(url)
-
- self.assertEqual(response.status_code, 405)
+# TODO: Add tests for LocationEditView V2 modal implementation
+# Tests will be created following the Entity test patterns after V2 implementation is complete
class TestLocationDeleteView(DualModeViewTestCase):
@@ -755,10 +522,10 @@ class TestLocationViewDeleteView(DualModeViewTestCase):
self.assertEqual(response.status_code, 404)
-class TestLocationViewEditView(DualModeViewTestCase):
+class TestLocationViewEditModeView(DualModeViewTestCase):
"""
- Tests for LocationViewEditView - demonstrates location view editing testing.
- This view handles location view property updates.
+ Tests for LocationViewEditModeView - demonstrates location view editing testing.
+ This view handles both displaying the edit interface (GET) and processing form submissions (POST).
"""
def setUp(self):
@@ -778,9 +545,21 @@ class TestLocationViewEditView(DualModeViewTestCase):
svg_view_box_str='0 0 100 100'
)
+ def test_get_edit_mode_panel(self):
+ """Test GET request returns the edit mode panel."""
+ url = reverse('location_view_edit_mode', kwargs={'location_view_id': self.location_view.id})
+ response = self.async_get(url)
+
+ # Should return success
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+ # Should use the edit mode panel template
+ self.assertTemplateRendered(response, 'location/edit/panes/location_view_edit_mode_panel.html')
+
def test_post_valid_edit(self):
"""Test POST request with valid edit data."""
- url = reverse('location_edit_location_view_edit', kwargs={'location_view_id': self.location_view.id})
+ url = reverse('location_view_edit_mode', kwargs={'location_view_id': self.location_view.id})
response = self.async_post(url, {
'name': 'Updated View',
'location_view_type_str': self.location_view.location_view_type_str,
@@ -800,7 +579,7 @@ class TestLocationViewEditView(DualModeViewTestCase):
def test_post_invalid_edit(self):
"""Test POST request with invalid edit data."""
- url = reverse('location_edit_location_view_edit', kwargs={'location_view_id': self.location_view.id})
+ url = reverse('location_view_edit_mode', kwargs={'location_view_id': self.location_view.id})
response = self.async_post(url, {'name': ''}) # Empty name should be invalid
# Should return 400 for invalid form data
@@ -813,19 +592,19 @@ class TestLocationViewEditView(DualModeViewTestCase):
def test_nonexistent_location_view_returns_404(self):
"""Test that accessing nonexistent location view returns 404."""
- url = reverse('location_edit_location_view_edit', kwargs={'location_view_id': 99999})
+ url = reverse('location_view_edit_mode', kwargs={'location_view_id': 99999})
response = self.async_post(url, {'name': 'Test'})
# Should return 404 for nonexistent location view
self.assertEqual(response.status_code, 404)
- def test_get_not_allowed(self):
- """Test that GET requests are not allowed."""
- url = reverse('location_edit_location_view_edit', kwargs={'location_view_id': self.location_view.id})
+ def test_get_nonexistent_location_view_returns_404(self):
+ """Test that GET request for nonexistent location view returns 404."""
+ url = reverse('location_view_edit_mode', kwargs={'location_view_id': 99999})
response = self.async_get(url)
- # View doesn't have GET method - returns 405
- self.assertEqual(response.status_code, 405)
+ # Should return 404 for nonexistent location view
+ self.assertEqual(response.status_code, 404)
class TestLocationViewManageItemsView(SyncViewTestCase):
diff --git a/src/hi/apps/location/edit/urls.py b/src/hi/apps/location/edit/urls.py
index 17f36bec..9480f834 100644
--- a/src/hi/apps/location/edit/urls.py
+++ b/src/hi/apps/location/edit/urls.py
@@ -5,67 +5,67 @@ from . import views
urlpatterns = [
- re_path( r'^location/add/first$',
+ re_path( r'^add/first$',
views.LocationAddFirstView.as_view(),
name='location_edit_location_add_first'),
- re_path( r'^location/add$',
+ re_path( r'^add$',
views.LocationAddView.as_view(),
name='location_edit_location_add'),
- re_path( r'^location/edit/(?P<location_id>\d+)$',
- views.LocationEditView.as_view(),
- name='location_edit_location_edit'),
+ re_path( r'^edit-mode/(?P<location_id>\d+)$',
+ views.LocationEditModeView.as_view(),
+ name='location_edit_mode' ),
+
+ re_path( r'^view/edit-mode/(?P<location_view_id>\d+)$',
+ views.LocationViewEditModeView.as_view(),
+ name='location_view_edit_mode' ),
+
+ re_path( r'^item/edit-mode/(?P<html_id>[\w\-]+)$',
+ views.LocationItemEditModeView.as_view(),
+ name='location_item_edit_mode' ),
re_path( r'^location/properties/edit/(?P<location_id>\d+)$',
views.LocationPropertiesEditView.as_view(),
name='location_properties_edit'),
- re_path( r'^location/attribute/upload/(?P<location_id>\d+)$',
- views.LocationAttributeUploadView.as_view(),
- name='location_attribute_upload'),
-
- re_path( r'^location/svg/replace/(?P<location_id>\d+)$',
+ re_path( r'^svg/replace/(?P<location_id>\d+)$',
views.LocationSvgReplaceView.as_view(),
name='location_edit_svg_replace'),
- re_path( r'^location/delete/(?P<location_id>\d+)$',
+ re_path( r'^delete/(?P<location_id>\d+)$',
views.LocationDeleteView.as_view(),
name='location_edit_location_delete' ),
- re_path( r'^location-view/add$',
+ re_path( r'^view/add$',
views.LocationViewAddView.as_view(),
name='location_edit_location_view_add' ),
- re_path( r'^location-view/edit/(?P<location_view_id>\d+)$',
- views.LocationViewEditView.as_view(),
- name='location_edit_location_view_edit' ),
-
- re_path( r'^location-view/geometry/(?P<location_view_id>\d+)$',
+ re_path( r'^view/geometry/(?P<location_view_id>\d+)$',
views.LocationViewGeometryView.as_view(),
name='location_edit_location_view_geometry' ),
- re_path( r'^location-view/delete/(?P<location_view_id>\d+)$',
+ re_path( r'^view/delete/(?P<location_view_id>\d+)$',
views.LocationViewDeleteView.as_view(),
name='location_edit_location_view_delete' ),
- re_path( r'^location-view/manage-item$',
+ re_path( r'^view/manage-item$',
views.LocationViewManageItemsView.as_view(),
name='location_edit_location_view_manage_items' ),
- re_path( r'^location-view/entity/toggle/(?P<location_view_id>\d+)/(?P<entity_id>\d+)$',
+ re_path( r'^view/entity/toggle/(?P<location_view_id>\d+)/(?P<entity_id>\d+)$',
views.LocationViewEntityToggleView.as_view(),
name='location_edit_location_view_entity_toggle' ),
- re_path( r'^location-view/collection/toggle/(?P<location_view_id>\d+)/(?P<collection_id>\d+)$',
+ re_path( r'^view/collection/toggle/(?P<location_view_id>\d+)/(?P<collection_id>\d+)$',
views.LocationViewCollectionToggleView.as_view(),
name='location_edit_location_view_collection_toggle' ),
- re_path( r'^location-item/position/(?P<html_id>[\w\-]+)$',
+ re_path( r'^item/position/(?P<html_id>[\w\-]+)$',
views.LocationItemPositionView.as_view(),
name='location_edit_location_item_position' ),
- re_path( r'^location-item/path/(?P<html_id>[\w\-]+)$',
+ re_path( r'^item/path/(?P<html_id>[\w\-]+)$',
views.LocationItemPathView.as_view(),
name='location_edit_location_item_path' ),
diff --git a/src/hi/apps/location/edit/view_mixins.py b/src/hi/apps/location/edit/view_mixins.py
index 57d6a607..c1913b0b 100644
--- a/src/hi/apps/location/edit/view_mixins.py
+++ b/src/hi/apps/location/edit/view_mixins.py
@@ -2,30 +2,17 @@ from django.http import HttpRequest
from django.template.loader import get_template
import hi.apps.common.antinode as antinode
-from hi.apps.location.transient_models import LocationEditData, LocationViewEditData
+from hi.apps.location.transient_models import LocationEditModeData, LocationViewEditModeData
from hi.constants import DIVID
class LocationEditViewMixin:
- def location_modal_response(
- self,
- request : HttpRequest,
- location_edit_data : LocationEditData,
- status_code : int = 200 ):
- """Return modal response for full location editing (properties + attributes)"""
- context = location_edit_data.to_template_context()
- return antinode.modal_from_template(
- request = request,
- template_name = 'location/modals/location_edit.html',
- context = context,
- )
-
def location_properties_response(
self,
request : HttpRequest,
- location_edit_data : LocationEditData,
+ location_edit_data : LocationEditModeData,
status_code : int = 200 ):
"""Return sidebar response for location properties editing only (name, order_id, svg_view_box_str)"""
context = location_edit_data.to_template_context()
@@ -38,14 +25,14 @@ class LocationEditViewMixin:
status = status_code,
)
- def location_view_edit_response(
+ def location_view_edit_mode_response(
self,
request : HttpRequest,
- location_view_edit_data : LocationViewEditData,
+ location_view_edit_data : LocationViewEditModeData,
status_code : int = 200 ):
context = location_view_edit_data.to_template_context()
- template = get_template( 'location/edit/panes/location_view_edit.html' )
+ template = get_template( 'location/edit/panes/location_view_properties_edit.html' )
content = template.render( context, request = request )
return antinode.response(
insert_map = {
diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.py
index 684b799d..9e74c57c 100644
--- a/src/hi/apps/location/edit/views.py
+++ b/src/hi/apps/location/edit/views.py
@@ -3,7 +3,7 @@ import logging
from django.core.exceptions import BadRequest
from django.db import transaction
-from django.http import Http404
+from django.http import Http404, HttpResponseNotAllowed, HttpResponseRedirect
from django.template.loader import get_template
from django.urls import reverse
from django.utils.decorators import method_decorator
@@ -17,8 +17,8 @@ from hi.apps.entity.edit.views import EntityPositionEditView
from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.models import Entity
from hi.apps.location.location_manager import LocationManager
-from hi.apps.location.models import Location, LocationAttribute
-from hi.apps.location.transient_models import LocationEditData, LocationViewEditData
+from hi.apps.location.models import Location
+from hi.apps.location.transient_models import LocationEditModeData, LocationViewEditModeData
from hi.apps.location.view_mixins import LocationViewMixin
from hi.constants import DIVID
@@ -32,6 +32,81 @@ from .view_mixins import LocationEditViewMixin
logger = logging.getLogger(__name__)
+class LocationEditModeView( HiSideView, LocationViewMixin ):
+ """Location edit mode panel view - shows location properties editing interface."""
+
+ def get_template_name( self ) -> str:
+ return 'location/edit/panes/location_edit_mode_panel.html'
+
+ def should_push_url( self ):
+ return True
+
+ def get_template_context( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ location_edit_data = LocationEditModeData(
+ location = location,
+ )
+ return location_edit_data.to_template_context()
+
+ def post( self, request, *args, **kwargs ):
+ return HttpResponseNotAllowed(['GET'])
+
+
+class LocationViewEditModeView( HiSideView, LocationViewMixin, LocationEditViewMixin ):
+ """Location view edit mode panel view - shows location view properties editing interface and handles form submission."""
+
+ def get_template_name( self ) -> str:
+ return 'location/edit/panes/location_view_edit_mode_panel.html'
+
+ def should_push_url( self ):
+ return True
+
+ def get_template_context( self, request, *args, **kwargs ):
+ location_view = self.get_location_view( request, *args, **kwargs )
+ location_view_edit_data = LocationViewEditModeData(
+ location_view = location_view,
+ )
+ return location_view_edit_data.to_template_context()
+
+ def post( self, request, *args, **kwargs ):
+ location_view = self.get_location_view( request, *args, **kwargs )
+ location_view_edit_form = forms.LocationViewEditForm( request.POST, instance = location_view )
+
+ if not location_view_edit_form.is_valid():
+ location_view_edit_data = LocationViewEditModeData(
+ location_view = location_view,
+ location_view_edit_form = location_view_edit_form,
+ )
+ return self.location_view_edit_mode_response(
+ request = request,
+ location_view_edit_data = location_view_edit_data,
+ status_code = 400,
+ )
+
+ # Location View name/order can impact many parts of UI. Full refresh is safest in this case.
+ location_view_edit_form.save()
+ return antinode.refresh_response()
+
+
+class LocationItemEditModeView( View ):
+
+ def get(self, request, *args, **kwargs):
+ try:
+ ( item_type, item_id ) = ItemType.parse_from_dict( kwargs )
+ except ValueError:
+ raise BadRequest( 'Bad item id.' )
+
+ if item_type == ItemType.ENTITY:
+ redirect_url = reverse( 'entity_edit_mode', kwargs = { 'entity_id': item_id } )
+ return HttpResponseRedirect( redirect_url )
+
+ if item_type == ItemType.COLLECTION:
+ redirect_url = reverse( 'collection_edit_mode', kwargs = { 'collection_id': item_id } )
+ return HttpResponseRedirect( redirect_url )
+
+ raise BadRequest( f'Unknown item type "{item_type}".' )
+
+
@method_decorator( edit_required, name='dispatch' )
class LocationAddView( HiModalView ):
@@ -128,67 +203,6 @@ class LocationSvgReplaceView( HiModalView, LocationViewMixin ):
return antinode.redirect_response( redirect_url )
-class LocationEditView( View, LocationViewMixin, LocationEditViewMixin ):
-
- def get( self, request, *args, **kwargs ):
- location = self.get_location( request, *args, **kwargs )
- location_edit_data = LocationEditData(
- location = location,
- )
- return self.location_modal_response(
- request = request,
- location_edit_data = location_edit_data,
- status_code = 200,
- )
-
- def post( self, request, *args, **kwargs ):
- location = self.get_location( request, *args, **kwargs )
-
- location_edit_form = forms.LocationEditForm(
- request.POST,
- instance = location,
- )
- location_attribute_formset = forms.LocationAttributeFormSet(
- request.POST,
- request.FILES,
- instance = location,
- prefix = f'location-{location.id}',
- form_kwargs = {
- 'show_as_editable': True,
- },
- )
-
- if ( location_edit_form.is_valid()
- and location_attribute_formset.is_valid() ):
- with transaction.atomic():
- location_edit_form.save()
- location_attribute_formset.save()
-
- # Location name/order can impact many parts of UI. Full refresh is safest in this case.
- if location_edit_form.has_changed():
- return antinode.refresh_response()
-
- # Recreate to preserve "max" to show new form
- location_attribute_formset = forms.LocationAttributeFormSet(
- instance = location,
- prefix = f'location-{location.id}',
- )
- status_code = 200
- else:
- status_code = 400
-
- location_edit_data = LocationEditData(
- location = location,
- location_edit_form = location_edit_form,
- location_attribute_formset = location_attribute_formset,
- )
- return self.location_modal_response(
- request = request,
- location_edit_data = location_edit_data,
- status_code = status_code,
- )
-
-
class LocationPropertiesEditView( View, LocationViewMixin, LocationEditViewMixin ):
"""Handle location properties editing (name, order_id, svg_view_box_str) only - used by sidebar"""
@@ -205,46 +219,16 @@ class LocationPropertiesEditView( View, LocationViewMixin, LocationEditViewMixin
else:
status_code = 400
- # For properties editing, we create LocationEditData without formset
- location_edit_data = LocationEditData(
+ # For properties editing, we create LocationEditModeData without formset
+ location_edit_data = LocationEditModeData(
location = location,
location_edit_form = location_edit_form,
- location_attribute_formset = None,
)
return self.location_properties_response(
request = request,
location_edit_data = location_edit_data,
status_code = status_code,
)
-
-
-class LocationAttributeUploadView( View, LocationViewMixin, LocationEditViewMixin ):
-
- def post( self, request, *args, **kwargs ):
- location = self.get_location( request, *args, **kwargs )
- location_attribute = LocationAttribute( location = location )
- location_attribute_upload_form = forms.LocationAttributeUploadForm(
- request.POST,
- request.FILES,
- instance = location_attribute,
- )
-
- if location_attribute_upload_form.is_valid():
- with transaction.atomic():
- location_attribute_upload_form.save()
- status_code = 200
- else:
- status_code = 400
-
- location_edit_data = LocationEditData(
- location = location,
- location_attribute_upload_form = location_attribute_upload_form,
- )
- return self.location_modal_response(
- request = request,
- location_edit_data = location_edit_data,
- status_code = status_code,
- )
@method_decorator( edit_required, name='dispatch' )
@@ -366,29 +350,6 @@ class LocationViewDeleteView( HiModalView, LocationViewMixin ):
return self.redirect_response( request, redirect_url )
-@method_decorator( edit_required, name='dispatch' )
-class LocationViewEditView( View, LocationViewMixin, LocationEditViewMixin ):
-
- def post( self, request, *args, **kwargs ):
- location_view = self.get_location_view( request, *args, **kwargs )
- location_view_edit_form = forms.LocationViewEditForm( request.POST, instance = location_view )
-
- if not location_view_edit_form.is_valid():
- location_view_edit_data = LocationViewEditData(
- location_view = location_view,
- location_view_edit_form = location_view_edit_form,
- )
- return self.location_view_edit_response(
- request = request,
- location_view_edit_data = location_view_edit_data,
- status_code = 400,
- )
-
- # Location View name/order can impact many parts of UI. Full refresh is safest in this case.
- location_view_edit_form.save()
- return antinode.refresh_response()
-
-
class LocationViewGeometryView( View, LocationViewMixin, LocationEditViewMixin ):
def post(self, request, *args, **kwargs):
@@ -408,10 +369,10 @@ class LocationViewGeometryView( View, LocationViewMixin, LocationEditViewMixin )
logger.warning( 'LocationView geometry form is invalid.' )
status_code = 400
- location_view_edit_data = LocationViewEditData(
+ location_view_edit_data = LocationViewEditModeData(
location_view = location_view,
)
- return self.location_view_edit_response(
+ return self.location_view_edit_mode_response(
request = request,
location_view_edit_data = location_view_edit_data,
status_code = status_code,
@@ -615,4 +576,3 @@ class LocationItemPathView( View ):
return antinode.response(
main_content = 'OK',
)
-
diff --git a/src/hi/apps/location/forms.py b/src/hi/apps/location/forms.py
new file mode 100644
index 00000000..4f73861f
--- /dev/null
+++ b/src/hi/apps/location/forms.py
@@ -0,0 +1,53 @@
+from django import forms
+
+from hi.apps.attribute.forms import AttributeForm, AttributeUploadForm
+from hi.apps.attribute.enums import AttributeValueType
+
+from hi.apps.location.models import Location, LocationAttribute
+
+
+class LocationAttributeForm( AttributeForm ):
+ class Meta( AttributeForm.Meta ):
+ model = LocationAttribute
+
+
+class RegularAttributeBaseFormSet(forms.BaseInlineFormSet):
+ """Base formset that automatically excludes FILE attributes for regular attribute editing"""
+
+ def get_queryset(self):
+ """Override to automatically filter out FILE attributes"""
+ queryset = super().get_queryset()
+ return queryset.exclude(value_type_str=str(AttributeValueType.FILE))
+
+
+LocationAttributeRegularFormSet = forms.inlineformset_factory(
+ Location,
+ LocationAttribute,
+ form = LocationAttributeForm,
+ formset = RegularAttributeBaseFormSet,
+ extra = 1,
+ max_num = 100,
+ absolute_max = 100,
+ can_delete = True,
+)
+
+
+class LocationModalEditForm( forms.ModelForm ):
+ """
+ Location edit form for modal - only includes name field.
+ Geometry fields (svg_view_box_str, order_id) are edited separately.
+ """
+
+ class Meta:
+ model = Location
+ fields = ('name',)
+ widgets = {
+ 'name': forms.TextInput(attrs={'class': 'form-control'})
+ }
+
+
+class LocationAttributeUploadForm( AttributeUploadForm ):
+ class Meta( AttributeUploadForm.Meta ):
+ model = LocationAttribute
+
+
diff --git a/src/hi/apps/location/location_attribute_edit_context.py b/src/hi/apps/location/location_attribute_edit_context.py
new file mode 100644
index 00000000..31382734
--- /dev/null
+++ b/src/hi/apps/location/location_attribute_edit_context.py
@@ -0,0 +1,33 @@
+"""
+LocationAttributeEditContext - Location-specific context for attribute editing templates.
+
+This module contains Location-specific implementations of the AttributeEditContext
+pattern, encapsulating location-specific domain knowledge while maintaining
+the generic template interface.
+"""
+from hi.apps.attribute.edit_context import AttributeEditContext
+from .models import Location
+
+
+class LocationAttributeEditContext(AttributeEditContext):
+ """
+ Location-specific context provider for attribute editing templates.
+
+ This class encapsulates Location-specific knowledge while providing
+ the generic interface expected by attribute editing templates.
+ """
+
+ def __init__(self, location: Location) -> None:
+ """
+ Initialize context for Location attribute editing.
+
+ Args:
+ location: The Location instance that owns the attributes
+ """
+ super().__init__(location, 'location')
+
+ @property
+ def location(self) -> Location:
+ """Get the Location instance (typed accessor)."""
+ return self.owner
+
diff --git a/src/hi/apps/location/location_edit_form_handler.py b/src/hi/apps/location/location_edit_form_handler.py
new file mode 100644
index 00000000..1abc5bd7
--- /dev/null
+++ b/src/hi/apps/location/location_edit_form_handler.py
@@ -0,0 +1,250 @@
+"""
+LocationEditFormHandler - Handles form creation, validation, and file processing for location editing.
+
+This class follows the same pattern as EntityEditFormHandler, encapsulating the complex
+form-handling business logic that was previously embedded in LocationEditView, following
+the "keep views simple" design philosophy.
+"""
+import logging
+import re
+from typing import Any, Dict, List, Optional, Tuple
+from django.db import transaction
+from django.http import HttpRequest
+from django.db.models import QuerySet
+
+from hi.apps.attribute.enums import AttributeValueType
+from .models import Location, LocationAttribute
+from .forms import LocationAttributeRegularFormSet, LocationModalEditForm
+from .location_attribute_edit_context import LocationAttributeEditContext
+
+logger = logging.getLogger(__name__)
+
+
+class LocationEditFormHandler:
+ """
+ Handles form creation, validation, and file processing for location editing.
+
+ This class encapsulates business logic for:
+ - Creating and managing location forms and formsets
+ - Processing file deletions and title updates
+ - Collecting and formatting form validation errors
+ """
+
+ @staticmethod
+ def get_formset_prefix(location: Location) -> str:
+ """
+ Get the formset prefix for regular attributes formset.
+
+ This is the single source of truth for formset prefix logic.
+ Tests and other code should use this method to ensure consistency.
+
+ Args:
+ location: Location instance
+
+ Returns:
+ str: The prefix to use for the regular attributes formset
+ """
+ return f'location-{location.id}'
+
+ def create_location_forms(
+ self,
+ location : Location,
+ form_data : Optional[Dict[str, Any]] = None
+ ) -> Tuple[LocationModalEditForm, QuerySet[LocationAttribute], LocationAttributeRegularFormSet]:
+ """Create location forms used by both initial rendering and fragment updates.
+
+ Args:
+ location: Location instance
+ form_data: POST data for bound forms, None for unbound forms
+
+ Returns:
+ tuple: (location_form, file_attributes, regular_attributes_formset)
+ """
+ # Create location form (only name field for this modal)
+ location_form: LocationModalEditForm = LocationModalEditForm(form_data, instance=location)
+
+ # Get file attributes for display (not a formset, just for template rendering)
+ file_attributes: QuerySet[LocationAttribute] = location.attributes.filter(
+ value_type_str=str(AttributeValueType.FILE)
+ ).order_by('id')
+
+ # Regular attributes formset (automatically excludes FILE attributes)
+ regular_attributes_formset: LocationAttributeRegularFormSet = LocationAttributeRegularFormSet(
+ form_data,
+ instance=location,
+ prefix=self.get_formset_prefix(location),
+ form_kwargs={
+ 'show_as_editable': True,
+ }
+ )
+
+ return location_form, file_attributes, regular_attributes_formset
+
+ def validate_forms( self,
+ location_form : LocationModalEditForm,
+ regular_attributes_formset : LocationAttributeRegularFormSet ) -> bool:
+ """
+ Validate location form and property attributes formset.
+
+ Args:
+ location_form: LocationModalEditForm instance
+ regular_attributes_formset: LocationAttributeRegularFormSet instance
+
+ Returns:
+ bool: True if both forms are valid, False otherwise
+ """
+ return location_form.is_valid() and regular_attributes_formset.is_valid()
+
+ def save_forms( self,
+ location_form : LocationModalEditForm,
+ regular_attributes_formset : LocationAttributeRegularFormSet,
+ request : HttpRequest,
+ location : Location ) -> None:
+ """
+ Save forms and process file operations within a transaction.
+
+ Args:
+ location_form: LocationModalEditForm instance
+ regular_attributes_formset: LocationAttributeRegularFormSet instance
+ request: HTTP request object
+ location: Location instance
+ """
+ with transaction.atomic():
+ location_form.save()
+ regular_attributes_formset.save()
+
+ # Process file deletions
+ self.process_file_deletions(request, location)
+
+ # Process file title updates
+ self.process_file_title_updates(request, location)
+
+ def process_file_deletions( self,
+ request : HttpRequest,
+ location : Location ) -> None:
+ """Process file deletion requests from POST data."""
+ file_deletes: List[str] = request.POST.getlist('delete_file_attribute')
+ if file_deletes:
+ for attr_id in file_deletes:
+ if attr_id: # Skip empty values
+ try:
+ file_attribute: LocationAttribute = LocationAttribute.objects.get(
+ id=attr_id,
+ location=location,
+ value_type_str=str(AttributeValueType.FILE)
+ )
+ # Verify permission to delete
+ if file_attribute.attribute_type.can_delete:
+ file_attribute.delete()
+ except LocationAttribute.DoesNotExist:
+ pass
+
+ def process_file_title_updates( self,
+ request : HttpRequest,
+ location : Location ) -> None:
+ """Process file_title_* fields from POST data to update file attribute values."""
+ # Pattern to match file_title_{location_id}_{attribute_id}
+ file_title_pattern = re.compile(r'^file_title_(\d+)_(\d+)$')
+
+ for field_name, new_title in request.POST.items():
+ match = file_title_pattern.match(field_name)
+ if not match:
+ continue
+
+ location_id_str: str
+ attribute_id_str: str
+ location_id_str, attribute_id_str = match.groups()
+
+ # Validate location_id matches current location
+ if int(location_id_str) != location.id:
+ logger.warning(f'File title field {field_name} has mismatched location ID')
+ continue
+
+ try:
+ attribute_id: int = int(attribute_id_str)
+ attribute: LocationAttribute = LocationAttribute.objects.get(
+ pk=attribute_id,
+ location=location,
+ value_type_str=str(AttributeValueType.FILE)
+ )
+
+ # Clean and validate the new title
+ new_title = new_title.strip()
+ if not new_title:
+ logger.warning(f'Empty title provided for file attribute {attribute_id}')
+ continue
+
+ # Check if title actually changed
+ if attribute.value != new_title:
+ attribute.value = new_title
+ attribute.save() # This will create a history record
+
+ except (ValueError, LocationAttribute.DoesNotExist) as e:
+ logger.warning(f'Invalid file title field {field_name}: {e}')
+
+ def collect_form_errors( self,
+ location_form : LocationModalEditForm,
+ regular_attributes_formset : LocationAttributeRegularFormSet ) -> List[str]:
+ """Collect non-field errors from forms for enhanced error messaging.
+
+ Args:
+ location_form: LocationModalEditForm instance
+ regular_attributes_formset: LocationAttributeRegularFormSet instance
+
+ Returns:
+ list: Formatted error messages with context prefixes
+ """
+ non_field_errors: List[str] = []
+
+ # Location form non-field errors
+ if ( location_form
+ and hasattr(location_form, 'non_field_errors')
+ and location_form.non_field_errors() ):
+ non_field_errors.extend([f"Location: {error}"
+ for error in location_form.non_field_errors()])
+
+ # Property formset non-field errors
+ if ( regular_attributes_formset
+ and hasattr(regular_attributes_formset, 'non_field_errors')
+ and regular_attributes_formset.non_field_errors() ):
+ non_field_errors.extend( [f"Properties: {error}"
+ for error in regular_attributes_formset.non_field_errors()])
+
+ # Individual property form non-field errors
+ if regular_attributes_formset:
+ for i, form in enumerate(regular_attributes_formset.forms):
+ if hasattr(form, 'non_field_errors') and form.non_field_errors():
+ property_name: str = form.instance.name if form.instance.pk else f"New Property #{i+1}"
+ non_field_errors.extend([f"{property_name}: {error}"
+ for error in form.non_field_errors()])
+
+ return non_field_errors
+
+ def create_initial_context( self,
+ location : Location ) -> Dict[str, Any]:
+ """Create initial template context for location editing form.
+
+ Args:
+ location: Location instance
+
+ Returns:
+ dict: Template context for initial form display
+ """
+ location_form, file_attributes, regular_attributes_formset = self.create_location_forms(location)
+
+ # Create the attribute edit context for template generalization
+ attr_context = LocationAttributeEditContext(location)
+
+ # Build context with both old and new patterns for compatibility
+ context = {
+ 'location': location,
+ 'location_form': location_form,
+ 'owner_form': location_form, # Generic alias for templates
+ 'file_attributes': file_attributes,
+ 'regular_attributes_formset': regular_attributes_formset,
+ }
+
+ # Merge in the context variables from AttributeEditContext
+ context.update(attr_context.to_template_context())
+
+ return context
diff --git a/src/hi/apps/location/location_edit_response_renderer.py b/src/hi/apps/location/location_edit_response_renderer.py
new file mode 100644
index 00000000..f3ef2dbd
--- /dev/null
+++ b/src/hi/apps/location/location_edit_response_renderer.py
@@ -0,0 +1,215 @@
+"""
+LocationEditResponseRenderer - Handles template rendering and response generation for location editing.
+
+This class follows the same pattern as EntityEditResponseRenderer, encapsulating the complex
+rendering and response logic that was previously embedded in LocationEditView, following
+the "keep views simple" design philosophy.
+"""
+from typing import Any, Dict, Optional, Tuple
+from django.db.models import QuerySet
+from django.http import HttpRequest
+from django.template.loader import render_to_string
+from django.urls import reverse
+
+import hi.apps.common.antinode as antinode
+from hi.constants import DIVID
+from .location_edit_form_handler import LocationEditFormHandler
+from .models import Location, LocationAttribute
+from .forms import LocationAttributeRegularFormSet, LocationModalEditForm
+from .location_attribute_edit_context import LocationAttributeEditContext
+
+
+class LocationEditResponseRenderer:
+ """
+ Handles template rendering and response generation for location editing.
+
+ This class encapsulates business logic for:
+ - Building template contexts
+ - Rendering template fragments for HTMX updates
+ - Constructing antinode responses for success/error cases
+ """
+
+ def __init__(self) -> None:
+ self.form_handler: LocationEditFormHandler = LocationEditFormHandler()
+
+ def build_template_context( self,
+ location : Location,
+ location_form : LocationModalEditForm,
+ file_attributes : QuerySet[LocationAttribute],
+ regular_attributes_formset : LocationAttributeRegularFormSet,
+ success_message : Optional[str] = None,
+ error_message : Optional[str] = None,
+ has_errors : bool = False ) -> Dict[str, Any]:
+ """Build context dictionary for template rendering.
+
+ Args:
+ location: Location instance
+ location_form: LocationModalEditForm instance
+ file_attributes: QuerySet of file attributes
+ regular_attributes_formset: LocationAttributeRegularFormSet instance
+ success_message: Optional success message for display
+ error_message: Optional error message for display
+ has_errors: Boolean indicating if forms have errors
+
+ Returns:
+ dict: Template context with all required variables
+ """
+ non_field_errors = self.form_handler.collect_form_errors(location_form, regular_attributes_formset)
+
+ # Create the attribute edit context for template generalization
+ attr_context = LocationAttributeEditContext(location)
+
+ # Build context with both old and new patterns for compatibility
+ context = {
+ 'location': location,
+ 'location_form': location_form,
+ 'owner_form': location_form, # Generic alias for templates
+ 'file_attributes': file_attributes,
+ 'regular_attributes_formset': regular_attributes_formset,
+ 'success_message': success_message,
+ 'error_message': error_message,
+ 'has_errors': has_errors,
+ 'non_field_errors': non_field_errors,
+ }
+
+ # Merge in the context variables from AttributeEditContext
+ context.update(attr_context.to_template_context())
+
+ return context
+
+ def render_update_fragments( self,
+ request : HttpRequest,
+ location : Location,
+ location_form : Optional[LocationModalEditForm] = None,
+ regular_attributes_formset : Optional[LocationAttributeRegularFormSet] = None,
+ success_message : Optional[str] = None,
+ error_message : Optional[str] = None,
+ has_errors : bool = False ) -> Tuple[str, str]:
+ """Render both content body and upload form fragments for antinode updates.
+
+ This is the main method for generating fragment updates after form submissions.
+
+ Args:
+ request: HTTP request object
+ location: Location instance
+ location_form: Optional location form (creates fresh if None)
+ regular_attributes_formset: Optional formset (creates fresh if None)
+ success_message: Success message for display
+ error_message: Error message for display
+ has_errors: Boolean indicating if forms have errors
+
+ Returns:
+ tuple: (content_body_html, upload_form_html)
+ """
+ # If forms not provided, create fresh ones (for success case)
+ if location_form is None or regular_attributes_formset is None:
+ fresh_location_form, file_attributes, fresh_property_formset = self.form_handler.create_location_forms(location)
+ if location_form is None:
+ location_form = fresh_location_form
+ if regular_attributes_formset is None:
+ regular_attributes_formset = fresh_property_formset
+ else:
+ # Forms provided, we still need file_attributes
+ _, file_attributes, _ = self.form_handler.create_location_forms(location)
+
+ # Build template context
+ context: Dict[str, Any] = self.build_template_context(
+ location, location_form, file_attributes, regular_attributes_formset,
+ success_message, error_message, has_errors
+ )
+
+ # Render and return fragments
+ return self.render_content_fragments(
+ request=request,
+ context=context,
+ location=location,
+ )
+
+ def render_content_fragments( self,
+ request : HttpRequest,
+ context : Dict[str, Any],
+ location : Location ) -> Tuple[str, str]:
+ """Render both content body and upload form fragments.
+
+ Args:
+ request: HTTP request object
+ context: Template context dictionary
+ location: Location instance
+
+ Returns:
+ tuple: (content_body_html, upload_form_html)
+ """
+ # Render both fragments
+ content_body: str = render_to_string('location/panes/location_edit_content_body.html', context, request=request)
+
+ # Upload form needs to be specific to location
+ file_upload_url: str = reverse('location_attribute_upload',
+ kwargs={'location_id': location.id})
+ upload_form: str = render_to_string(
+ 'attribute/components/upload_form.html',
+ {'file_upload_url': file_upload_url},
+ request=request, # Needed for context processors (CSRF, DIVID, etc.)
+ )
+
+ return content_body, upload_form
+
+ def render_success_response( self,
+ request : HttpRequest,
+ location : Location ) -> 'antinode.Response':
+ """Render success response using antinode helpers - multiple target replacement.
+
+ Args:
+ request: HTTP request object
+ location: Location instance
+
+ Returns:
+ antinode.Response: Success response for HTMX update
+ """
+ # Re-render both content body and upload form with fresh forms
+ content_body, upload_form = self.render_update_fragments(
+ request=request,
+ location=location,
+ success_message="Changes saved successfully"
+ )
+
+ return antinode.response(
+ insert_map={
+ DIVID['ATTR_V2_CONTENT']: content_body,
+ DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']: upload_form
+ }
+ )
+
+ def render_error_response(
+ self,
+ request : HttpRequest,
+ location : Location,
+ location_form : LocationModalEditForm,
+ regular_attributes_formset : LocationAttributeRegularFormSet ) -> 'antinode.Response':
+ """Render error response using antinode helpers - multiple target replacement.
+
+ Args:
+ request: HTTP request object
+ location: Location instance
+ location_form: LocationModalEditForm instance with validation errors
+ regular_attributes_formset: FormSet instance with validation errors
+
+ Returns:
+ antinode.Response: Error response for HTMX update with 400 status
+ """
+ # Re-render both content body and upload form with form errors
+ content_body, upload_form = self.render_update_fragments(
+ request=request,
+ location=location,
+ location_form=location_form,
+ regular_attributes_formset=regular_attributes_formset,
+ error_message="Please correct the errors below",
+ has_errors=True,
+ )
+
+ return antinode.response(
+ insert_map={
+ DIVID['ATTR_V2_CONTENT']: content_body,
+ DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']: upload_form
+ },
+ status=400
+ )
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_edit.html b/src/hi/apps/location/templates/location/edit/panes/location_edit.html
deleted file mode 100644
index 35b4634e..00000000
--- a/src/hi/apps/location/templates/location/edit/panes/location_edit.html
+++ /dev/null
@@ -1,48 +0,0 @@
-{% load icons %}
-<form action="{% url 'location_edit_location_edit' location_id=location.id %}"
- method="post" enctype="multipart/form-data"
- class="form" data-async="true">
- {% csrf_token %}
- <div>
- {% include "location/edit/panes/location_edit_form.html" %}
- </div>
- <div>
- {% include "attribute/panes/attribute_form.html" with attribute_formset=location_attribute_formset %}
- </div>
-
- <div class="text-center" >
- <button id="hi-add-location-button" type="submit" class="btn btn-primary"
- name="action" value="update">
- {% icon "save" size="sm" css_class="hi-icon-left" %}UPDATE
- </button>
- </div>
-</form>
-
-<div class="text-center my-3" >
- <form action="{% url 'location_attribute_upload' location_id=location.id %}"
- method="post"
- class="form" data-async="true">
- {% csrf_token %}
- <div>
- {% include "attribute/panes/attribute_upload_form.html" with attribute_upload_form=location_attribute_upload_form %}
- </div>
- </form>
-</div>
-
-{% if request.view_parameters.is_editing %}
-<div class="text-center my-3" >
- <a href="{% url 'location_edit_svg_replace' location_id=location.id %}"
- id="hi-svg-replace-link" class="btn btn-primary btn-control" role="button"
- data-async="true">
- {% icon "upload" size="sm" css_class="hi-icon-left" %}REPLACE BACKGROUND SVG IMAGE
- </a>
-</div>
-
-<div class="my-3">
- <a href="{% url 'location_edit_location_delete' location_id=location.id %}"
- id="hi-delete-location-link" class="btn btn-danger btn-control" role="button"
- data-async="true">
- {% icon "delete" size="sm" css_class="hi-icon-left" %}DELETE LOCATION AND ALL VIEWS
- </a>
-</div>
-{% endif %}
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_edit_header.html b/src/hi/apps/location/templates/location/edit/panes/location_edit_mode_header.html
similarity index 73%
rename from src/hi/apps/location/templates/location/edit/panes/location_edit_header.html
rename to src/hi/apps/location/templates/location/edit/panes/location_edit_mode_header.html
index a7899944..80a906ed 100644
--- a/src/hi/apps/location/templates/location/edit/panes/location_edit_header.html
+++ b/src/hi/apps/location/templates/location/edit/panes/location_edit_mode_header.html
@@ -1,7 +1,7 @@
<div class="d-flex justify-content-between">
<div class="h5"><small>Location:</small> {{ request.view_parameters.location.name }}</div>
<div>
- <a href="{% url 'location_details' location_id=request.view_parameters.location.id %}"
+ <a href="{% url 'location_edit_mode' location_id=request.view_parameters.location.id %}"
class="btn btn-sm btn-tertiary" role="button" data-async="true">
EDIT
</a>
diff --git a/src/hi/apps/location/templates/location/panes/location_edit_mode_panel.html b/src/hi/apps/location/templates/location/edit/panes/location_edit_mode_panel.html
similarity index 100%
rename from src/hi/apps/location/templates/location/panes/location_edit_mode_panel.html
rename to src/hi/apps/location/templates/location/edit/panes/location_edit_mode_panel.html
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_edit_form.html b/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_form.html
similarity index 100%
rename from src/hi/apps/location/templates/location/edit/panes/location_view_edit_form.html
rename to src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_form.html
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_edit_header.html b/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_header.html
similarity index 70%
rename from src/hi/apps/location/templates/location/edit/panes/location_view_edit_header.html
rename to src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_header.html
index 6415aa66..f5996c87 100644
--- a/src/hi/apps/location/templates/location/edit/panes/location_view_edit_header.html
+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_header.html
@@ -1,7 +1,7 @@
<div class="d-flex justify-content-between">
<div class="h5"><small>View:</small> {{ request.view_parameters.location_view.name }}</div>
<div>
- <a href="{% url 'location_view_details' location_view_id=request.view_parameters.location_view.id %}"
+ <a href="{% url 'location_view_edit_mode' location_view_id=request.view_parameters.location_view.id %}"
class="btn btn-sm btn-tertiary" role="button" data-async="true">
EDIT
</a>
diff --git a/src/hi/apps/location/templates/location/panes/location_view_details.html b/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_panel.html
similarity index 82%
rename from src/hi/apps/location/templates/location/panes/location_view_details.html
rename to src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_panel.html
index d53f8783..5127985b 100644
--- a/src/hi/apps/location/templates/location/panes/location_view_details.html
+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_panel.html
@@ -8,5 +8,5 @@
</div>
</div>
<div id="{{ DIVID.LOCATION_VIEW_EDIT_PANE }}">
- {% include "location/edit/panes/location_view_edit.html" %}
+ {% include "location/edit/panes/location_view_properties_edit.html" %}
</div>
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_edit.html b/src/hi/apps/location/templates/location/edit/panes/location_view_properties_edit.html
similarity index 80%
rename from src/hi/apps/location/templates/location/edit/panes/location_view_edit.html
rename to src/hi/apps/location/templates/location/edit/panes/location_view_properties_edit.html
index cb1973ac..43a3a148 100644
--- a/src/hi/apps/location/templates/location/edit/panes/location_view_edit.html
+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_properties_edit.html
@@ -1,11 +1,11 @@
{% load icons %}
-<form action="{% url 'location_edit_location_view_edit' location_view_id=location_view.id %}"
+<form action="{% url 'location_view_edit_mode' location_view_id=location_view.id %}"
method="post"
class="form" data-async="true">
{% csrf_token %}
<div>
- {% include "location/edit/panes/location_view_edit_form.html" %}
+ {% include "location/edit/panes/location_view_edit_mode_form.html" %}
</div>
<div class="text-center" >
<button id="hi-add-location-view-button" type="submit" class="btn btn-primary"
diff --git a/src/hi/apps/location/templates/location/modals/location_edit.html b/src/hi/apps/location/templates/location/modals/location_edit.html
index d924febf..1ed36555 100644
--- a/src/hi/apps/location/templates/location/modals/location_edit.html
+++ b/src/hi/apps/location/templates/location/modals/location_edit.html
@@ -1,11 +1,49 @@
-{% extends "modals/action_done.html" %}
+{% extends "modals/base.html" %}
+{% load icons %}
-{% block title_text %}
-{{ location.name }}
-{% endblock %}
+{% block modal_dialog_class %}hi-modal-dialog-700{% endblock %}
+{% block title_text %}{{ location.name }}{% endblock %}
{% block body %}
-<div>
- {% include "location/edit/panes/location_edit.html" %}
+<form id="{{ DIVID.ATTR_V2_FORM }}"
+ action="{% url 'location_edit_location_edit' location_id=location.id %}"
+ method="post"
+ class="form {{ DIVID.ATTR_V2_MODAL_CLASS }}"
+ data-async="true"
+ data-stay-in-modal="true"
+ enctype="multipart/form-data">
+ {% csrf_token %}
+
+<!-- Main content wrapper for antinode updates -->
+<div id="{{ DIVID.ATTR_V2_CONTENT }}">
+ {% include "location/panes/location_edit_content_body.html" %}
+</div>
+</form>
+
+<!-- File Upload Form Container (separate from main form to avoid nesting) -->
+<div id="{{ DIVID.ATTR_V2_UPLOAD_FORM_CONTAINER }}">
+ {% url 'location_attribute_upload' location_id=location.id as file_upload_url %}
+ {% include "attribute/components/upload_form.html" with file_upload_url=file_upload_url %}
</div>
+
+<!-- Success/Error Messages -->
+{% if messages %}
+ <div class="{{ DIVID.ATTR_V2_MESSAGES }}" id="{{ DIVID.ATTR_V2_MESSAGES }}">
+ {% for message in messages %}
+ <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
+ {{ message }}
+ <button type="button" class="close" data-dismiss="alert" aria-label="Close">
+ <span aria-hidden="true">&times;</span>
+ </button>
+ </div>
+ {% endfor %}
+ </div>
+{% endif %}
+
+<!-- JavaScript for V2 functionality loaded via Django Pipeline js_before_content bundle -->
+
+{% endblock %}
+
+{% block footer %}
+<!-- No footer - sticky panel contains all actions -->
{% endblock %}
diff --git a/src/hi/apps/location/templates/location/panes/location_edit_content_body.html b/src/hi/apps/location/templates/location/panes/location_edit_content_body.html
new file mode 100644
index 00000000..ff7b5550
--- /dev/null
+++ b/src/hi/apps/location/templates/location/panes/location_edit_content_body.html
@@ -0,0 +1,27 @@
+{% extends "attribute/components/edit_content_body.html" %}
+{% comment %}
+Location V2 Content Body Fragment
+Extends the generic attribute edit content body with location-specific field layout.
+{% endcomment %}
+
+{% block owner_fields %}
+<!-- Location-specific fields: Only name field for modal editing -->
+<div class="row">
+ <div class="col-md-12">
+ <div class="form-group mb-0">
+ <small class="text-muted">Name</small>
+ <input type="text"
+ id="{{ owner_form.name.id_for_label }}"
+ name="{{ owner_form.name.html_name }}"
+ value="{{ owner_form.name.value|default:'' }}"
+ class="form-control form-control-sm"
+ {% if owner_form.name.field.required %}required{% endif %}>
+ {% if owner_form.name.errors %}
+ <div class="invalid-feedback d-block">
+ {{ owner_form.name.errors }}
+ </div>
+ {% endif %}
+ </div>
+ </div>
+</div>
+{% endblock %}
\ No newline at end of file
diff --git a/src/hi/apps/location/tests/test_location_attribute_edit_context.py b/src/hi/apps/location/tests/test_location_attribute_edit_context.py
new file mode 100644
index 00000000..fd75004d
--- /dev/null
+++ b/src/hi/apps/location/tests/test_location_attribute_edit_context.py
@@ -0,0 +1,190 @@
+"""
+Tests for LocationAttributeEditContext.
+
+Focuses on Location-specific context generation, URL patterns, and integration
+with LocationAttribute model relationships.
+"""
+import logging
+from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
+from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestLocationAttributeEditContext(BaseTestCase):
+ """Test LocationAttributeEditContext location-specific functionality."""
+
+ def setUp(self):
+ super().setUp()
+ self.location = LocationSyntheticData.create_test_location(
+ name="Test Location",
+ svg_fragment_filename="test-location.svg"
+ )
+ self.context = LocationAttributeEditContext(self.location)
+
+ def test_location_context_initialization(self):
+ """Test LocationAttributeEditContext initializes with correct owner type."""
+ self.assertEqual(self.context.owner_type, "location")
+ self.assertEqual(self.context.owner, self.location)
+ self.assertEqual(self.context.owner_id, self.location.id)
+ self.assertEqual(self.context.owner_name, self.location.name)
+
+ def test_location_property_accessor(self):
+ """Test typed location property accessor - provides type safety."""
+ self.assertIs(self.context.location, self.location)
+ self.assertEqual(self.context.location.name, "Test Location")
+ self.assertEqual(self.context.location.svg_fragment_filename, "test-location.svg")
+
+ def test_location_specific_url_patterns(self):
+ """Test location-specific URL name generation - routing integration."""
+ self.assertEqual(self.context.history_url_name, "location_attribute_history_inline")
+ self.assertEqual(self.context.restore_url_name, "location_attribute_restore_inline")
+ self.assertEqual(self.context.owner_id_param_name, "location_id")
+
+ def test_location_specific_dom_ids(self):
+ """Test location-specific DOM ID generation - JavaScript integration."""
+ attribute_id = 123
+
+ history_id = self.context.history_target_id(attribute_id)
+ self.assertEqual(history_id, f"hi-location-attr-history-{self.location.id}-123")
+
+ toggle_id = self.context.history_toggle_id(attribute_id)
+ self.assertEqual(toggle_id, f"history-extra-{self.location.id}-123")
+
+ def test_location_template_context_assembly(self):
+ """Test location-specific template context generation - template integration."""
+ template_context = self.context.to_template_context()
+
+ # Should include generic keys
+ self.assertIn('attr_context', template_context)
+ self.assertIn('owner', template_context)
+
+ # Should include location-specific key
+ self.assertIn('location', template_context)
+ self.assertIs(template_context['location'], self.location)
+
+ # Should NOT include entity key
+ self.assertNotIn('entity', template_context)
+
+ def test_location_context_with_different_locations(self):
+ """Test context works correctly with different location instances."""
+ location2 = LocationSyntheticData.create_test_location(
+ name="Another Location",
+ svg_fragment_filename="another-location.svg"
+ )
+ context2 = LocationAttributeEditContext(location2)
+
+ # Should have different IDs and names
+ self.assertNotEqual(self.context.owner_id, context2.owner_id)
+ self.assertNotEqual(self.context.owner_name, context2.owner_name)
+
+ # But same URL patterns
+ self.assertEqual(self.context.history_url_name, context2.history_url_name)
+ self.assertEqual(self.context.owner_id_param_name, context2.owner_id_param_name)
+
+ # DOM IDs should differ by location ID
+ attribute_id = 456
+ history1 = self.context.history_target_id(attribute_id)
+ history2 = context2.history_target_id(attribute_id)
+ self.assertNotEqual(history1, history2)
+ self.assertIn(str(self.location.id), history1)
+ self.assertIn(str(location2.id), history2)
+
+ def test_location_context_form_field_naming(self):
+ """Test location-specific form field name generation."""
+ attribute_id = 789
+ field_name = self.context.file_title_field_name(attribute_id)
+ expected = f"file_title_{self.location.id}_{attribute_id}"
+ self.assertEqual(field_name, expected)
+
+ def test_location_context_consistency_across_operations(self):
+ """Test context maintains consistency across different operations - state management."""
+ attribute_id = 999
+
+ # All operations should use the same location ID
+ history_id = self.context.history_target_id(attribute_id)
+ toggle_id = self.context.history_toggle_id(attribute_id)
+ field_name = self.context.file_title_field_name(attribute_id)
+
+ location_id_str = str(self.location.id)
+ self.assertIn(location_id_str, history_id)
+ self.assertIn(location_id_str, toggle_id)
+ self.assertIn(location_id_str, field_name)
+
+ def test_location_context_inheritance_behavior(self):
+ """Test LocationAttributeEditContext properly inherits base functionality."""
+ # Should inherit all base class methods
+ self.assertTrue(hasattr(self.context, 'owner_id'))
+ self.assertTrue(hasattr(self.context, 'owner_name'))
+ self.assertTrue(hasattr(self.context, 'owner_id_param_name'))
+ self.assertTrue(hasattr(self.context, 'history_url_name'))
+ self.assertTrue(hasattr(self.context, 'restore_url_name'))
+ self.assertTrue(hasattr(self.context, 'history_target_id'))
+ self.assertTrue(hasattr(self.context, 'history_toggle_id'))
+ self.assertTrue(hasattr(self.context, 'file_title_field_name'))
+ self.assertTrue(hasattr(self.context, 'to_template_context'))
+
+ def test_location_context_edge_cases(self):
+ """Test location context handles edge cases gracefully."""
+ # Test with location having special characters in name
+ special_location = LocationSyntheticData.create_test_location(
+ name="Location with & special chars!",
+ svg_fragment_filename="special-location.svg"
+ )
+ special_context = LocationAttributeEditContext(special_location)
+
+ self.assertEqual(special_context.owner_name, "Location with & special chars!")
+
+ # DOM IDs should still be generated properly
+ history_id = special_context.history_target_id(123)
+ self.assertIn("hi-location-attr-history", history_id)
+ self.assertIn(str(special_location.id), history_id)
+
+ def test_location_context_with_location_attributes(self):
+ """Test context integration with actual LocationAttribute relationships."""
+ # Create location with attributes using synthetic data
+ location_with_attrs = LocationSyntheticData.create_test_location(
+ name="Location with Attributes"
+ )
+
+ context = LocationAttributeEditContext(location_with_attrs)
+
+ # Context should work with the location regardless of attribute count
+ self.assertEqual(context.location, location_with_attrs)
+ self.assertEqual(context.owner_type, "location")
+
+ # Template context should be consistent
+ template_ctx = context.to_template_context()
+ self.assertIs(template_ctx['location'], location_with_attrs)
+
+ def test_location_context_multiple_instances_isolation(self):
+ """Test multiple LocationAttributeEditContext instances don't interfere - instance isolation."""
+ location1 = LocationSyntheticData.create_test_location(name="Location 1")
+ location2 = LocationSyntheticData.create_test_location(name="Location 2")
+
+ context1 = LocationAttributeEditContext(location1)
+ context2 = LocationAttributeEditContext(location2)
+
+ # Contexts should be independent
+ self.assertNotEqual(context1.owner_id, context2.owner_id)
+ self.assertNotEqual(context1.owner_name, context2.owner_name)
+
+ # Modifying one location shouldn't affect the other context
+ location1.name = "Modified Location 1"
+ self.assertEqual(context1.owner_name, "Modified Location 1")
+ self.assertEqual(context2.owner_name, "Location 2") # Should be unchanged
+
+ def test_location_context_type_consistency(self):
+ """Test LocationAttributeEditContext maintains type consistency - type safety."""
+ # owner_type should always be 'location'
+ self.assertEqual(self.context.owner_type, "location")
+
+ # location property should return the same instance as owner
+ self.assertIs(self.context.location, self.context.owner)
+
+ # Template context should have location key pointing to same instance
+ template_ctx = self.context.to_template_context()
+ self.assertIs(template_ctx['location'], self.context.owner)
+ self.assertIs(template_ctx['owner'], self.context.owner)
+
diff --git a/src/hi/apps/location/tests/test_location_edit_form_handler.py b/src/hi/apps/location/tests/test_location_edit_form_handler.py
new file mode 100644
index 00000000..904f5122
--- /dev/null
+++ b/src/hi/apps/location/tests/test_location_edit_form_handler.py
@@ -0,0 +1,372 @@
+"""
+Tests for LocationEditFormHandler business logic.
+
+Focuses on high-value form processing logic: formset creation, file operations,
+validation orchestration, and error collection patterns.
+"""
+import logging
+import re
+from django.test import RequestFactory
+
+from hi.apps.location.location_edit_form_handler import LocationEditFormHandler
+from hi.apps.location.models import LocationAttribute
+from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestLocationEditFormHandler(BaseTestCase):
+ """Test LocationEditFormHandler business logic - form processing and file operations."""
+
+ def setUp(self):
+ super().setUp()
+ self.location = LocationSyntheticData.create_test_location(
+ name="Test Location Handler"
+ )
+ self.handler = LocationEditFormHandler()
+ self.request_factory = RequestFactory()
+
+ def test_formset_prefix_generation_consistency(self):
+ """Test formset prefix follows expected pattern - critical for form processing."""
+ prefix = LocationEditFormHandler.get_formset_prefix(self.location)
+ expected = f"location-{self.location.id}"
+ self.assertEqual(prefix, expected)
+
+ # Test with different location
+ location2 = LocationSyntheticData.create_test_location(name="Another Location")
+ prefix2 = LocationEditFormHandler.get_formset_prefix(location2)
+ expected2 = f"location-{location2.id}"
+ self.assertEqual(prefix2, expected2)
+ self.assertNotEqual(prefix, prefix2)
+
+ def test_create_location_forms_unbound(self):
+ """Test creating unbound forms for initial display - form initialization logic."""
+ location_form, file_attributes, regular_formset = self.handler.create_location_forms(self.location)
+
+ # Location form should be unbound
+ self.assertFalse(location_form.is_bound)
+ self.assertEqual(location_form.instance, self.location)
+
+ # File attributes should be queryset of FILE type attributes
+ self.assertEqual(list(file_attributes), list(self.location.attributes.filter(
+ value_type_str=str(AttributeValueType.FILE)
+ ).order_by('id')))
+
+ # Regular formset should be unbound and exclude FILE attributes
+ self.assertFalse(regular_formset.is_bound)
+ self.assertEqual(regular_formset.instance, self.location)
+
+ def test_create_location_forms_bound_with_data(self):
+ """Test creating bound forms with POST data - form binding logic."""
+ form_data = {
+ 'name': 'Updated Location Name',
+ # Add formset management form data
+ f'location-{self.location.id}-TOTAL_FORMS': '1',
+ f'location-{self.location.id}-INITIAL_FORMS': '0',
+ f'location-{self.location.id}-MIN_NUM_FORMS': '0',
+ f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
+ }
+
+ location_form, file_attributes, regular_formset = self.handler.create_location_forms(
+ self.location, form_data
+ )
+
+ # Forms should be bound with data
+ self.assertTrue(location_form.is_bound)
+ self.assertTrue(regular_formset.is_bound)
+
+ # Formset should use correct prefix
+ expected_prefix = LocationEditFormHandler.get_formset_prefix(self.location)
+ self.assertEqual(regular_formset.prefix, expected_prefix)
+
+ def test_validate_forms_both_valid(self):
+ """Test form validation when both forms are valid - success path."""
+ # Create valid form data
+ form_data = {
+ 'name': 'Valid Location Name',
+ f'location-{self.location.id}-TOTAL_FORMS': '0',
+ f'location-{self.location.id}-INITIAL_FORMS': '0',
+ f'location-{self.location.id}-MIN_NUM_FORMS': '0',
+ f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
+ }
+
+ location_form, _, regular_formset = self.handler.create_location_forms(
+ self.location, form_data
+ )
+
+ is_valid = self.handler.validate_forms(location_form, regular_formset)
+ self.assertTrue(is_valid)
+
+ def test_validate_forms_location_invalid(self):
+ """Test form validation when location form is invalid - error handling."""
+ # Create invalid form data (empty name)
+ form_data = {
+ 'name': '', # Invalid empty name
+ f'location-{self.location.id}-TOTAL_FORMS': '0',
+ f'location-{self.location.id}-INITIAL_FORMS': '0',
+ f'location-{self.location.id}-MIN_NUM_FORMS': '0',
+ f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
+ }
+
+ location_form, _, regular_formset = self.handler.create_location_forms(
+ self.location, form_data
+ )
+
+ is_valid = self.handler.validate_forms(location_form, regular_formset)
+ self.assertFalse(is_valid)
+
+ def test_validate_forms_formset_invalid(self):
+ """Test form validation when formset is invalid - error handling."""
+ # Create form data with invalid formset (will depend on actual form validation rules)
+ form_data = {
+ 'name': 'Valid Location Name',
+ f'location-{self.location.id}-TOTAL_FORMS': '1',
+ f'location-{self.location.id}-INITIAL_FORMS': '0',
+ f'location-{self.location.id}-MIN_NUM_FORMS': '0',
+ f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
+ # Add invalid attribute data
+ f'location-{self.location.id}-0-name': '', # Empty name might be invalid
+ f'location-{self.location.id}-0-value': 'some value',
+ }
+
+ location_form, _, regular_formset = self.handler.create_location_forms(
+ self.location, form_data
+ )
+
+ is_valid = self.handler.validate_forms(location_form, regular_formset)
+ # Result depends on actual validation rules, but testing the validation orchestration
+ self.assertIsInstance(is_valid, bool)
+
+ def test_process_file_deletions_valid_file_attributes(self):
+ """Test file deletion processing with valid file attributes - file management logic."""
+ # Create file attribute
+ file_attr = LocationAttribute.objects.create(
+ location=self.location,
+ name='test_file',
+ value='Test File',
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM), # Can be deleted
+ )
+
+ # Create request with file deletion
+ post_data = {
+ 'delete_file_attribute': [str(file_attr.id)]
+ }
+ request = self.request_factory.post('/', post_data)
+
+ # Should delete the file attribute
+ self.handler.process_file_deletions(request, self.location)
+
+ # Attribute should be deleted
+ self.assertFalse(LocationAttribute.objects.filter(id=file_attr.id).exists())
+
+ def test_process_file_deletions_non_deletable_attribute(self):
+ """Test file deletion processing skips non-deletable attributes - permission logic."""
+ # Create non-deletable file attribute
+ file_attr = LocationAttribute.objects.create(
+ location=self.location,
+ name='predefined_file',
+ value='Predefined File',
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.PREDEFINED), # Cannot be deleted
+ )
+
+ post_data = {
+ 'delete_file_attribute': [str(file_attr.id)]
+ }
+ request = self.request_factory.post('/', post_data)
+
+ # Should not delete the file attribute
+ self.handler.process_file_deletions(request, self.location)
+
+ # Attribute should still exist
+ self.assertTrue(LocationAttribute.objects.filter(id=file_attr.id).exists())
+
+ def test_process_file_deletions_invalid_attribute_id(self):
+ """Test file deletion processing handles invalid attribute IDs gracefully - error handling."""
+ post_data = {
+ 'delete_file_attribute': ['999999', ''] # Non-existent, empty
+ }
+ request = self.request_factory.post('/', post_data)
+
+ # Should not raise exception
+ self.handler.process_file_deletions(request, self.location)
+ # No assertions needed - just ensure no exceptions are raised
+
+ def test_process_file_title_updates_valid_updates(self):
+ """Test file title update processing - file metadata management logic."""
+ # Create file attribute
+ file_attr = LocationAttribute.objects.create(
+ location=self.location,
+ name='test_file',
+ value='Original Title',
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+
+ # Create request with file title update
+ field_name = f'file_title_{self.location.id}_{file_attr.id}'
+ post_data = {
+ field_name: 'Updated Title'
+ }
+ request = self.request_factory.post('/', post_data)
+
+ self.handler.process_file_title_updates(request, self.location)
+
+ # Attribute value should be updated
+ file_attr.refresh_from_db()
+ self.assertEqual(file_attr.value, 'Updated Title')
+
+ def test_process_file_title_updates_pattern_matching(self):
+ """Test file title field name pattern matching - field parsing logic."""
+ # Create file attribute
+ file_attr = LocationAttribute.objects.create(
+ location=self.location,
+ name='test_file',
+ value='Original Title',
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+
+ # Test various field name patterns
+ test_cases = [
+ (f'file_title_{self.location.id}_{file_attr.id}', 'Valid Pattern', True),
+ ('file_title_wrong_format', 'Invalid Pattern', False),
+ (f'file_title_{self.location.id + 1}_{file_attr.id}', 'Wrong Location', False),
+ (f'file_title_{self.location.id}_999999', 'Non-existent Attr', False),
+ ]
+
+ for field_name, new_title, should_update in test_cases:
+ with self.subTest(field_name=field_name):
+ original_title = file_attr.value
+
+ post_data = {field_name: new_title}
+ request = self.request_factory.post('/', post_data)
+
+ self.handler.process_file_title_updates(request, self.location)
+
+ file_attr.refresh_from_db()
+ if should_update:
+ self.assertEqual(file_attr.value, new_title)
+ else:
+ self.assertEqual(file_attr.value, original_title)
+
+ # Reset for next test
+ file_attr.value = 'Original Title'
+ file_attr.save()
+
+ def test_process_file_title_updates_empty_title_handling(self):
+ """Test file title update processing handles empty titles - data validation."""
+ file_attr = LocationAttribute.objects.create(
+ location=self.location,
+ name='test_file',
+ value='Original Title',
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+
+ # Test empty and whitespace-only titles
+ test_cases = ['', ' ', '\t\n']
+
+ for empty_title in test_cases:
+ with self.subTest(empty_title=repr(empty_title)):
+ original_title = file_attr.value
+
+ field_name = f'file_title_{self.location.id}_{file_attr.id}'
+ post_data = {field_name: empty_title}
+ request = self.request_factory.post('/', post_data)
+
+ self.handler.process_file_title_updates(request, self.location)
+
+ file_attr.refresh_from_db()
+ # Title should remain unchanged for empty values
+ self.assertEqual(file_attr.value, original_title)
+
+ def test_collect_form_errors_multiple_sources(self):
+ """Test error collection from multiple form sources - comprehensive error handling."""
+ # Create forms with errors
+ form_data = {
+ 'name': '', # Will cause location form error
+ f'location-{self.location.id}-TOTAL_FORMS': '1',
+ f'location-{self.location.id}-INITIAL_FORMS': '0',
+ f'location-{self.location.id}-MIN_NUM_FORMS': '0',
+ f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
+ # Invalid attribute data might cause formset errors
+ f'location-{self.location.id}-0-name': '',
+ f'location-{self.location.id}-0-value': '',
+ }
+
+ location_form, _, regular_formset = self.handler.create_location_forms(
+ self.location, form_data
+ )
+
+ # Trigger validation to generate errors
+ location_form.is_valid()
+ regular_formset.is_valid()
+
+ errors = self.handler.collect_form_errors(location_form, regular_formset)
+
+ # Should return a list of error strings
+ self.assertIsInstance(errors, list)
+ # Specific error content depends on form validation rules
+
+ def test_create_initial_context_structure(self):
+ """Test initial context creation includes all required components - template integration."""
+ context = self.handler.create_initial_context(self.location)
+
+ # Should include all expected keys
+ required_keys = [
+ 'location', 'location_form', 'owner_form', 'file_attributes',
+ 'regular_attributes_formset', 'attr_context', 'owner'
+ ]
+
+ for key in required_keys:
+ with self.subTest(key=key):
+ self.assertIn(key, context)
+
+ # Generic aliases should point to same objects
+ self.assertIs(context['owner_form'], context['location_form'])
+ self.assertIs(context['owner'], context['location'])
+ self.assertIs(context['location'], self.location)
+
+ def test_create_initial_context_attribute_context_integration(self):
+ """Test initial context includes AttributeEditContext integration - template generalization."""
+ context = self.handler.create_initial_context(self.location)
+
+ # Should have attr_context
+ self.assertIn('attr_context', context)
+ attr_context = context['attr_context']
+
+ # attr_context should be LocationAttributeEditContext
+ from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
+ self.assertIsInstance(attr_context, LocationAttributeEditContext)
+
+ # Should reference the same location
+ self.assertEqual(attr_context.location, self.location)
+
+ def test_file_title_pattern_regex_accuracy(self):
+ """Test the file title pattern regex matches expected formats - pattern validation."""
+ # Access the pattern used in the handler (it's defined in the method)
+ pattern = re.compile(r'^file_title_(\d+)_(\d+)$')
+
+ test_cases = [
+ ('file_title_123_456', True, ('123', '456')),
+ ('file_title_0_0', True, ('0', '0')),
+ ('file_title_abc_123', False, None),
+ ('file_title_123_abc', False, None),
+ ('file_title_123', False, None),
+ ('prefix_file_title_123_456', False, None),
+ ('file_title_123_456_suffix', False, None),
+ ]
+
+ for field_name, should_match, expected_groups in test_cases:
+ with self.subTest(field_name=field_name):
+ match = pattern.match(field_name)
+ if should_match:
+ self.assertIsNotNone(match)
+ self.assertEqual(match.groups(), expected_groups)
+ else:
+ self.assertIsNone(match)
+
diff --git a/src/hi/apps/location/tests/test_location_edit_response_renderer.py b/src/hi/apps/location/tests/test_location_edit_response_renderer.py
new file mode 100644
index 00000000..e9de82fa
--- /dev/null
+++ b/src/hi/apps/location/tests/test_location_edit_response_renderer.py
@@ -0,0 +1,379 @@
+"""
+Tests for LocationEditResponseRenderer integration logic.
+
+Focuses on high-value template rendering, context assembly, and antinode response
+generation patterns.
+"""
+import logging
+from unittest.mock import Mock, patch
+from django.test import RequestFactory
+
+from hi.apps.location.location_edit_response_renderer import LocationEditResponseRenderer
+from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+from hi.apps.location.models import LocationAttribute
+from hi.apps.attribute.enums import AttributeValueType, AttributeType
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestLocationEditResponseRenderer(BaseTestCase):
+ """Test LocationEditResponseRenderer template rendering and response logic."""
+
+ def setUp(self):
+ super().setUp()
+ self.location = LocationSyntheticData.create_test_location(
+ name="Test Location Renderer"
+ )
+ self.renderer = LocationEditResponseRenderer()
+ self.request_factory = RequestFactory()
+ self.request = self.request_factory.get('/')
+
+ def test_renderer_initialization(self):
+ """Test renderer initializes with form handler - dependency injection."""
+ self.assertIsNotNone(self.renderer.form_handler)
+ from hi.apps.location.location_edit_form_handler import LocationEditFormHandler
+ self.assertIsInstance(self.renderer.form_handler, LocationEditFormHandler)
+
+ def test_build_template_context_basic_structure(self):
+ """Test template context building includes all required components - context assembly."""
+ # Create forms using form handler
+ location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(
+ self.location
+ )
+
+ context = self.renderer.build_template_context(
+ location=self.location,
+ location_form=location_form,
+ file_attributes=file_attributes,
+ regular_attributes_formset=regular_formset,
+ success_message="Test success",
+ error_message="Test error",
+ has_errors=True
+ )
+
+ # Check all required context keys
+ required_keys = [
+ 'location', 'location_form', 'owner_form', 'file_attributes',
+ 'regular_attributes_formset', 'success_message', 'error_message',
+ 'has_errors', 'non_field_errors', 'attr_context', 'owner'
+ ]
+
+ for key in required_keys:
+ with self.subTest(key=key):
+ self.assertIn(key, context)
+
+ # Check generic aliases
+ self.assertIs(context['owner_form'], context['location_form'])
+ self.assertIs(context['owner'], context['location'])
+
+ def test_build_template_context_attribute_context_integration(self):
+ """Test template context includes AttributeEditContext - template generalization."""
+ location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(
+ self.location
+ )
+
+ context = self.renderer.build_template_context(
+ location=self.location,
+ location_form=location_form,
+ file_attributes=file_attributes,
+ regular_attributes_formset=regular_formset
+ )
+
+ # Should have attr_context from LocationAttributeEditContext
+ self.assertIn('attr_context', context)
+ attr_context = context['attr_context']
+
+ from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
+ self.assertIsInstance(attr_context, LocationAttributeEditContext)
+ self.assertEqual(attr_context.location, self.location)
+
+ def test_build_template_context_error_collection(self):
+ """Test template context collects form errors - error messaging logic."""
+ # Create forms with validation errors
+ form_data = {
+ 'name': '', # Invalid empty name
+ f'location-{self.location.id}-TOTAL_FORMS': '0',
+ f'location-{self.location.id}-INITIAL_FORMS': '0',
+ f'location-{self.location.id}-MIN_NUM_FORMS': '0',
+ f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
+ }
+
+ location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(
+ self.location, form_data
+ )
+
+ # Trigger validation
+ location_form.is_valid()
+ regular_formset.is_valid()
+
+ context = self.renderer.build_template_context(
+ location=self.location,
+ location_form=location_form,
+ file_attributes=file_attributes,
+ regular_attributes_formset=regular_formset,
+ has_errors=True
+ )
+
+ # Should include non_field_errors
+ self.assertIn('non_field_errors', context)
+ self.assertIsInstance(context['non_field_errors'], list)
+
+ @patch('hi.apps.location.location_edit_response_renderer.render_to_string')
+ @patch('hi.apps.location.location_edit_response_renderer.reverse')
+ def test_render_content_fragments_template_rendering(self, mock_reverse, mock_render):
+ """Test content fragment rendering uses correct templates - template integration."""
+ mock_reverse.return_value = '/location/123/attribute/upload/'
+ mock_render.side_effect = ['<content_body>', '<upload_form>']
+
+ context = {'location': self.location, 'test': 'data'}
+
+ content_body, upload_form = self.renderer.render_content_fragments(
+ request=self.request,
+ context=context,
+ location=self.location
+ )
+
+ # Should call render_to_string twice with correct templates
+ self.assertEqual(mock_render.call_count, 2)
+
+ # First call: content body template
+ first_call = mock_render.call_args_list[0]
+ self.assertEqual(first_call[0][0], 'location/panes/location_edit_content_body.html')
+ self.assertEqual(first_call[0][1], context)
+ self.assertEqual(first_call[1]['request'], self.request)
+
+ # Second call: upload form template
+ second_call = mock_render.call_args_list[1]
+ self.assertEqual(second_call[0][0], 'attribute/components/upload_form.html')
+ self.assertIn('file_upload_url', second_call[0][1])
+
+ # Should generate upload URL for this location
+ mock_reverse.assert_called_once_with(
+ 'location_attribute_upload',
+ kwargs={'location_id': self.location.id}
+ )
+
+ self.assertEqual(content_body, '<content_body>')
+ self.assertEqual(upload_form, '<upload_form>')
+
+ def test_render_update_fragments_with_fresh_forms(self):
+ """Test update fragments rendering creates fresh forms when none provided - success case logic."""
+ with patch.object(self.renderer, 'render_content_fragments') as mock_render_fragments:
+ mock_render_fragments.return_value = ('<content>', '<upload>')
+
+ content_body, upload_form = self.renderer.render_update_fragments(
+ request=self.request,
+ location=self.location,
+ success_message="Success!"
+ )
+
+ # Should call render_content_fragments
+ mock_render_fragments.assert_called_once()
+ call_args = mock_render_fragments.call_args
+
+ # Should have created fresh forms (not None)
+ context = call_args[1]['context']
+ self.assertIsNotNone(context['location_form'])
+ self.assertIsNotNone(context['regular_attributes_formset'])
+ self.assertEqual(context['success_message'], "Success!")
+
+ def test_render_update_fragments_with_existing_forms(self):
+ """Test update fragments rendering uses provided forms - error case logic."""
+ # Create forms with errors
+ form_data = {
+ 'name': '',
+ f'location-{self.location.id}-TOTAL_FORMS': '0',
+ f'location-{self.location.id}-INITIAL_FORMS': '0',
+ f'location-{self.location.id}-MIN_NUM_FORMS': '0',
+ f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
+ }
+
+ location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(
+ self.location, form_data
+ )
+
+ with patch.object(self.renderer, 'render_content_fragments') as mock_render_fragments:
+ mock_render_fragments.return_value = ('<error_content>', '<upload>')
+
+ self.renderer.render_update_fragments(
+ request=self.request,
+ location=self.location,
+ location_form=location_form,
+ regular_attributes_formset=regular_formset,
+ error_message="Error!",
+ has_errors=True
+ )
+
+ # Should use provided forms
+ mock_render_fragments.assert_called_once()
+ call_args = mock_render_fragments.call_args
+ context = call_args[1]['context']
+
+ self.assertIs(context['location_form'], location_form)
+ self.assertIs(context['regular_attributes_formset'], regular_formset)
+ self.assertEqual(context['error_message'], "Error!")
+ self.assertTrue(context['has_errors'])
+
+ @patch('hi.apps.location.location_edit_response_renderer.antinode')
+ def test_render_success_response_antinode_integration(self, mock_antinode):
+ """Test success response uses antinode with correct parameters - response generation."""
+ mock_response = Mock()
+ mock_antinode.response.return_value = mock_response
+
+ with patch.object(self.renderer, 'render_update_fragments') as mock_render:
+ mock_render.return_value = ('<success_content>', '<success_upload>')
+
+ response = self.renderer.render_success_response(self.request, self.location)
+
+ # Should call render_update_fragments with success message
+ mock_render.assert_called_once()
+ call_args = mock_render.call_args
+ self.assertEqual(call_args[1]['success_message'], "Changes saved successfully")
+
+ # Should create antinode response with insert_map
+ mock_antinode.response.assert_called_once()
+ response_args = mock_antinode.response.call_args
+
+ self.assertIn('insert_map', response_args[1])
+ insert_map = response_args[1]['insert_map']
+
+ # Should have both content and upload form updates
+ from hi.constants import DIVID
+ self.assertIn(DIVID['ATTR_V2_CONTENT'], insert_map)
+ self.assertIn(DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER'], insert_map)
+ self.assertEqual(insert_map[DIVID['ATTR_V2_CONTENT']], '<success_content>')
+ self.assertEqual(insert_map[DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']], '<success_upload>')
+
+ self.assertEqual(response, mock_response)
+
+ @patch('hi.apps.location.location_edit_response_renderer.antinode')
+ def test_render_error_response_antinode_integration(self, mock_antinode):
+ """Test error response uses antinode with 400 status - error response generation."""
+ mock_response = Mock()
+ mock_antinode.response.return_value = mock_response
+
+ # Create forms with errors
+ location_form, _, regular_formset = self.renderer.form_handler.create_location_forms(self.location)
+
+ with patch.object(self.renderer, 'render_update_fragments') as mock_render:
+ mock_render.return_value = ('<error_content>', '<error_upload>')
+
+ response = self.renderer.render_error_response(
+ self.request, self.location, location_form, regular_formset
+ )
+
+ # Should call render_update_fragments with error parameters
+ mock_render.assert_called_once()
+ self.assertEqual(response, mock_response)
+ call_args = mock_render.call_args
+ self.assertEqual(call_args[1]['error_message'], "Please correct the errors below")
+ self.assertTrue(call_args[1]['has_errors'])
+ self.assertIs(call_args[1]['location_form'], location_form)
+ self.assertIs(call_args[1]['regular_attributes_formset'], regular_formset)
+
+ # Should create antinode response with 400 status
+ mock_antinode.response.assert_called_once()
+ response_args = mock_antinode.response.call_args
+
+ self.assertEqual(response_args[1]['status'], 400)
+ self.assertIn('insert_map', response_args[1])
+
+ def test_renderer_with_location_having_file_attributes(self):
+ """Test renderer handles locations with file attributes - file attribute integration."""
+ # Create location with file attribute
+ file_attr = LocationAttribute.objects.create(
+ location=self.location,
+ name='test_document',
+ value='Test Document',
+ value_type_str=str(AttributeValueType.FILE),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+
+ # Create forms and context
+ location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(
+ self.location
+ )
+
+ context = self.renderer.build_template_context(
+ location=self.location,
+ location_form=location_form,
+ file_attributes=file_attributes,
+ regular_attributes_formset=regular_formset
+ )
+
+ # File attributes should be included in context
+ self.assertIn(file_attr, context['file_attributes'])
+
+ def test_renderer_context_consistency_across_operations(self):
+ """Test renderer maintains context consistency across different operations - state management."""
+ # Test that different operations produce consistent context structure
+
+ # Test success case context
+ location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(self.location)
+ success_context = self.renderer.build_template_context(
+ location=self.location,
+ location_form=location_form,
+ file_attributes=file_attributes,
+ regular_attributes_formset=regular_formset,
+ success_message="Success!"
+ )
+
+ # Test error case context
+ error_context = self.renderer.build_template_context(
+ location=self.location,
+ location_form=location_form,
+ file_attributes=file_attributes,
+ regular_attributes_formset=regular_formset,
+ error_message="Error!",
+ has_errors=True
+ )
+
+ # Test initial case context
+ initial_context = self.renderer.form_handler.create_initial_context(self.location)
+
+ # All contexts should reference the same location and have attr_context
+ for context_name, context in [('success', success_context), ('error', error_context), ('initial', initial_context)]:
+ with self.subTest(context=context_name):
+ self.assertEqual(context['location'], self.location)
+ self.assertIn('attr_context', context)
+ # attr_context should be the same type across all operations
+ from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
+ self.assertIsInstance(context['attr_context'], LocationAttributeEditContext)
+
+ def test_renderer_template_path_consistency(self):
+ """Test renderer uses consistent template paths - template organization."""
+ with patch('hi.apps.location.location_edit_response_renderer.render_to_string') as mock_render:
+ mock_render.return_value = '<rendered>'
+
+ context = {'test': 'data'}
+ self.renderer.render_content_fragments(self.request, context, self.location)
+
+ # Should use location-specific content template
+ content_call = mock_render.call_args_list[0]
+ self.assertEqual(content_call[0][0], 'location/panes/location_edit_content_body.html')
+
+ # Should use generic upload form template
+ upload_call = mock_render.call_args_list[1]
+ self.assertEqual(upload_call[0][0], 'attribute/components/upload_form.html')
+
+ def test_renderer_error_handling_robustness(self):
+ """Test renderer handles various error conditions gracefully - error resilience."""
+ # Test with None values
+ with patch.object(self.renderer.form_handler, 'collect_form_errors') as mock_collect:
+ mock_collect.return_value = []
+
+ context = self.renderer.build_template_context(
+ location=self.location,
+ location_form=None, # Should handle None gracefully
+ file_attributes=LocationAttribute.objects.none(),
+ regular_attributes_formset=None,
+ success_message=None,
+ error_message=None,
+ has_errors=False
+ )
+
+ # Should not crash and should include basic required keys
+ self.assertEqual(context['location'], self.location)
+ self.assertIn('attr_context', context)
+
diff --git a/src/hi/apps/location/tests/test_transient_models.py b/src/hi/apps/location/tests/test_transient_models.py
index 53e3f92f..5c41eb1c 100644
--- a/src/hi/apps/location/tests/test_transient_models.py
+++ b/src/hi/apps/location/tests/test_transient_models.py
@@ -1,34 +1,30 @@
import logging
-from hi.apps.location.transient_models import LocationEditData, LocationViewEditData
-from hi.apps.location.models import Location, LocationView, LocationAttribute
+from hi.apps.location.transient_models import LocationEditModeData, LocationViewEditModeData
+from hi.apps.location.models import Location, LocationView
from hi.apps.location.edit.forms import LocationEditForm, LocationViewEditForm
-from hi.apps.attribute.enums import AttributeValueType
from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
-class TestLocationEditData(BaseTestCase):
+class TestLocationEditModeData(BaseTestCase):
def test_location_edit_data_form_initialization(self):
- """Test LocationEditData form auto-initialization - critical for edit UI."""
+ """Test LocationEditModeData form auto-initialization - critical for edit UI."""
location = Location.objects.create(
name='Test Location',
svg_fragment_filename='test.svg',
svg_view_box_str='0 0 100 100'
)
- edit_data = LocationEditData(location=location)
+ edit_data = LocationEditModeData(location=location)
# Forms should be automatically initialized
self.assertIsNotNone(edit_data.location_edit_form)
- self.assertIsNotNone(edit_data.location_attribute_formset)
- self.assertIsNotNone(edit_data.location_attribute_upload_form)
# Form should be bound to location instance
self.assertEqual(edit_data.location_edit_form.instance, location)
- self.assertEqual(edit_data.location_attribute_formset.instance, location)
return
def test_location_edit_data_template_context_generation(self):
@@ -39,77 +35,20 @@ class TestLocationEditData(BaseTestCase):
svg_view_box_str='0 0 100 100'
)
- edit_data = LocationEditData(location=location)
+ edit_data = LocationEditModeData(location=location)
context = edit_data.to_template_context()
# Should contain all required template variables
expected_keys = {
'location',
'location_edit_form',
- 'location_attribute_formset',
- 'location_attribute_upload_form',
- 'history_url_name',
- 'restore_url_name'
}
self.assertEqual(set(context.keys()), expected_keys)
self.assertEqual(context['location'], location)
return
-
- def test_location_edit_data_formset_prefix_generation(self):
- """Test formset prefix generation - critical for form handling."""
- location = Location.objects.create(
- name='Test Location',
- svg_fragment_filename='test.svg',
- svg_view_box_str='0 0 100 100'
- )
-
- edit_data = LocationEditData(location=location)
-
- # Prefix should include location ID
- expected_prefix = f'location-{location.id}'
- self.assertEqual(edit_data.location_attribute_formset.prefix, expected_prefix)
- return
-
- def test_location_edit_data_with_existing_attributes(self):
- """Test LocationEditData handles existing attributes correctly."""
- location = Location.objects.create(
- name='Test Location with Attributes',
- svg_fragment_filename='test.svg',
- svg_view_box_str='0 0 150 150'
- )
-
- # Create existing attributes
- LocationAttribute.objects.create(
- location=location,
- name='documentation',
- value_type=AttributeValueType.TEXT,
- value='Existing manual'
- )
- LocationAttribute.objects.create(
- location=location,
- name='config_file',
- value_type=AttributeValueType.FILE,
- value='config.json'
- )
-
- edit_data = LocationEditData(location=location)
-
- # Formset should include existing attributes (may include extra empty forms)
- formset = edit_data.location_attribute_formset
- self.assertGreaterEqual(len(formset.forms), 2) # At least 2 existing attributes
-
- # Verify formset is bound to location with existing data
- self.assertEqual(formset.instance, location)
- self.assertEqual(formset.queryset.count(), 2)
-
- # Test template context includes all necessary data
- context = edit_data.to_template_context()
- self.assertIn('location_attribute_formset', context)
- self.assertEqual(context['location'], location)
- return
def test_location_edit_data_form_validation_behavior(self):
- """Test LocationEditData form validation and error handling."""
+ """Test LocationEditModeData form validation and error handling."""
location = Location.objects.create(
name='Valid Location',
svg_fragment_filename='valid.svg',
@@ -122,7 +61,7 @@ class TestLocationEditData(BaseTestCase):
'svg_view_box_str': 'invalid viewbox', # Invalid format
}
- edit_data = LocationEditData(
+ edit_data = LocationEditModeData(
location=location,
location_edit_form=LocationEditForm(data=invalid_data, instance=location)
)
@@ -147,7 +86,7 @@ class TestLocationEditData(BaseTestCase):
'svg_view_box_str': '10 10 250 250',
}
- edit_data_valid = LocationEditData(
+ edit_data_valid = LocationEditModeData(
location=location,
location_edit_form=LocationEditForm(data=valid_data, instance=location)
)
@@ -163,10 +102,10 @@ class TestLocationEditData(BaseTestCase):
return
-class TestLocationViewEditData(BaseTestCase):
+class TestLocationViewEditModeData(BaseTestCase):
def test_location_view_edit_data_form_initialization(self):
- """Test LocationViewEditData form auto-initialization - critical for edit UI."""
+ """Test LocationViewEditModeData form auto-initialization - critical for edit UI."""
location = Location.objects.create(
name='Test Location',
svg_fragment_filename='test.svg',
@@ -182,7 +121,7 @@ class TestLocationViewEditData(BaseTestCase):
svg_style_name_str='COLOR'
)
- edit_data = LocationViewEditData(location_view=location_view)
+ edit_data = LocationViewEditModeData(location_view=location_view)
# Form should be automatically initialized
self.assertIsNotNone(edit_data.location_view_edit_form)
@@ -208,7 +147,7 @@ class TestLocationViewEditData(BaseTestCase):
svg_style_name_str='COLOR'
)
- edit_data = LocationViewEditData(location_view=location_view)
+ edit_data = LocationViewEditModeData(location_view=location_view)
context = edit_data.to_template_context()
# Should contain all required template variables
@@ -218,7 +157,7 @@ class TestLocationViewEditData(BaseTestCase):
return
def test_location_view_edit_data_form_enum_handling(self):
- """Test LocationViewEditData handles enum conversions correctly."""
+ """Test LocationViewEditModeData handles enum conversions correctly."""
location = Location.objects.create(
name='Enum Test Location',
svg_fragment_filename='enum.svg',
@@ -234,7 +173,7 @@ class TestLocationViewEditData(BaseTestCase):
svg_style_name_str='GREYSCALE'
)
- edit_data = LocationViewEditData(location_view=location_view)
+ edit_data = LocationViewEditModeData(location_view=location_view)
# Form should be bound to the view with enum values
form = edit_data.location_view_edit_form
@@ -249,7 +188,7 @@ class TestLocationViewEditData(BaseTestCase):
'svg_style_name_str': 'COLOR'
}
- edit_data_updated = LocationViewEditData(
+ edit_data_updated = LocationViewEditModeData(
location_view=location_view,
location_view_edit_form=LocationViewEditForm(data=update_data, instance=location_view)
)
@@ -265,59 +204,3 @@ class TestLocationViewEditData(BaseTestCase):
context = edit_data_updated.to_template_context()
self.assertEqual(context['location_view'], location_view)
return
-
- def test_location_edit_data_multiple_locations_isolation(self):
- """Test that LocationEditData instances for different locations are isolated."""
- # Create two different locations
- location1 = Location.objects.create(
- name='Location One',
- svg_fragment_filename='one.svg',
- svg_view_box_str='0 0 100 100'
- )
- location2 = Location.objects.create(
- name='Location Two',
- svg_fragment_filename='two.svg',
- svg_view_box_str='0 0 200 200'
- )
-
- # Create attributes for each location
- LocationAttribute.objects.create(
- location=location1,
- name='location1_attr',
- value_type=AttributeValueType.TEXT,
- value='Location 1 data'
- )
- LocationAttribute.objects.create(
- location=location2,
- name='location2_attr',
- value_type=AttributeValueType.TEXT,
- value='Location 2 data'
- )
-
- # Create edit data for both locations
- edit_data1 = LocationEditData(location=location1)
- edit_data2 = LocationEditData(location=location2)
-
- # Verify formsets are isolated to their respective locations
- formset1 = edit_data1.location_attribute_formset
- formset2 = edit_data2.location_attribute_formset
-
- self.assertEqual(formset1.instance, location1)
- self.assertEqual(formset2.instance, location2)
- self.assertNotEqual(formset1.instance, formset2.instance)
-
- # Verify prefixes are unique
- self.assertNotEqual(formset1.prefix, formset2.prefix)
- self.assertEqual(formset1.prefix, f'location-{location1.id}')
- self.assertEqual(formset2.prefix, f'location-{location2.id}')
-
- # Verify each formset only contains its location's attributes
- self.assertEqual(formset1.queryset.count(), 1)
- self.assertEqual(formset2.queryset.count(), 1)
-
- attr1 = formset1.queryset.first()
- attr2 = formset2.queryset.first()
-
- self.assertEqual(attr1.name, 'location1_attr')
- self.assertEqual(attr2.name, 'location2_attr')
- return
diff --git a/src/hi/apps/location/tests/test_views.py b/src/hi/apps/location/tests/test_views.py
index 3ffc8b33..8b683949 100644
--- a/src/hi/apps/location/tests/test_views.py
+++ b/src/hi/apps/location/tests/test_views.py
@@ -297,9 +297,9 @@ class TestLocationSwitchView(SyncViewTestCase):
self.assertEqual(response.status_code, 405)
-class TestLocationDetailsView(AsyncViewTestCase):
+class TestLocationEditModeView(AsyncViewTestCase):
"""
- Tests for LocationDetailsView - demonstrates HiSideView testing.
+ Tests for LocationEditModeView - demonstrates HiSideView testing.
This view displays location details in a side panel.
"""
@@ -314,16 +314,16 @@ class TestLocationDetailsView(AsyncViewTestCase):
def test_get_location_details(self):
"""Test getting location details."""
- url = reverse('location_details', kwargs={'location_id': self.location.id})
+ url = reverse('location_edit_mode', kwargs={'location_id': self.location.id})
response = self.async_get(url)
self.assertSuccessResponse(response)
self.assertJsonResponse(response)
- self.assertTemplateRendered(response, 'location/panes/location_edit_mode_panel.html')
+ self.assertTemplateRendered(response, 'location/edit/panes/location_edit_mode_panel.html')
def test_location_details_should_push_url(self):
- """Test that LocationDetailsView should push URL."""
- url = reverse('location_details', kwargs={'location_id': self.location.id})
+ """Test that LocationEditModeView should push URL."""
+ url = reverse('location_edit_mode', kwargs={'location_id': self.location.id})
response = self.async_get(url)
self.assertSuccessResponse(response)
@@ -331,31 +331,31 @@ class TestLocationDetailsView(AsyncViewTestCase):
def test_location_edit_data_in_context(self):
"""Test that location edit data is passed to template context."""
- url = reverse('location_details', kwargs={'location_id': self.location.id})
+ url = reverse('location_edit_mode', kwargs={'location_id': self.location.id})
response = self.async_get(url)
self.assertSuccessResponse(response)
# Context should contain location edit data
- # The actual structure depends on LocationEditData.to_template_context()
+ # The actual structure depends on LocationEditModeData.to_template_context()
def test_nonexistent_location_returns_404(self):
"""Test that accessing nonexistent location returns 404."""
- url = reverse('location_details', kwargs={'location_id': 99999})
+ url = reverse('location_edit_mode', kwargs={'location_id': 99999})
response = self.async_get(url)
self.assertEqual(response.status_code, 404)
def test_post_not_allowed(self):
"""Test that POST requests are not allowed."""
- url = reverse('location_details', kwargs={'location_id': self.location.id})
+ url = reverse('location_edit_mode', kwargs={'location_id': self.location.id})
response = self.async_post(url)
self.assertEqual(response.status_code, 405)
-class TestLocationViewDetailsView(AsyncViewTestCase):
+class TestLocationViewEditModeViewGet(AsyncViewTestCase):
"""
- Tests for LocationViewDetailsView - demonstrates location view details testing.
+ Tests for LocationViewEditModeView.get() - demonstrates location view details testing.
This view displays location view details in a side panel.
"""
@@ -377,16 +377,16 @@ class TestLocationViewDetailsView(AsyncViewTestCase):
def test_get_location_view_details(self):
"""Test getting location view details."""
- url = reverse('location_view_details', kwargs={'location_view_id': self.location_view.id})
+ url = reverse('location_view_edit_mode', kwargs={'location_view_id': self.location_view.id})
response = self.async_get(url)
self.assertSuccessResponse(response)
self.assertJsonResponse(response)
- self.assertTemplateRendered(response, 'location/panes/location_view_details.html')
+ self.assertTemplateRendered(response, 'location/edit/panes/location_view_edit_mode_panel.html')
def test_location_view_details_should_push_url(self):
- """Test that LocationViewDetailsView should push URL."""
- url = reverse('location_view_details', kwargs={'location_view_id': self.location_view.id})
+ """Test that LocationViewEditModeView should push URL."""
+ url = reverse('location_view_edit_mode', kwargs={'location_view_id': self.location_view.id})
response = self.async_get(url)
self.assertSuccessResponse(response)
@@ -394,29 +394,22 @@ class TestLocationViewDetailsView(AsyncViewTestCase):
def test_location_view_edit_data_in_context(self):
"""Test that location view edit data is passed to template context."""
- url = reverse('location_view_details', kwargs={'location_view_id': self.location_view.id})
+ url = reverse('location_view_edit_mode', kwargs={'location_view_id': self.location_view.id})
response = self.async_get(url)
self.assertSuccessResponse(response)
# Context should contain location view edit data
- # The actual structure depends on LocationViewEditData.to_template_context()
+ # The actual structure depends on LocationViewEditModeData.to_template_context()
def test_nonexistent_location_view_returns_404(self):
"""Test that accessing nonexistent location view returns 404."""
- url = reverse('location_view_details', kwargs={'location_view_id': 99999})
+ url = reverse('location_view_edit_mode', kwargs={'location_view_id': 99999})
response = self.async_get(url)
self.assertEqual(response.status_code, 404)
- def test_post_not_allowed(self):
- """Test that POST requests are not allowed."""
- url = reverse('location_view_details', kwargs={'location_view_id': self.location_view.id})
- response = self.async_post(url)
-
- self.assertEqual(response.status_code, 405)
-
-class TestLocationItemInfoView(SyncViewTestCase):
+class TestLocationItemStatusView(SyncViewTestCase):
"""
Tests for LocationItemInfoView - demonstrates item type delegation testing.
This view redirects to appropriate info views based on item type.
@@ -439,7 +432,7 @@ class TestLocationItemInfoView(SyncViewTestCase):
"""Test redirecting to entity status for entity items."""
from hi.enums import ItemType
html_id = ItemType.ENTITY.html_id(self.entity.id)
- url = reverse('location_item_info', kwargs={'html_id': html_id})
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
@@ -450,7 +443,7 @@ class TestLocationItemInfoView(SyncViewTestCase):
"""Test redirecting to collection view for collection items."""
from hi.enums import ItemType
html_id = ItemType.COLLECTION.html_id(self.collection.id)
- url = reverse('location_item_info', kwargs={'html_id': html_id})
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
@@ -460,7 +453,7 @@ class TestLocationItemInfoView(SyncViewTestCase):
def test_unknown_item_type_returns_400(self):
"""Test that unknown item types return BadRequest."""
# Use an invalid html_id format to trigger BadRequest
- url = reverse('location_item_info', kwargs={'html_id': 'hi-unknown-1'})
+ url = reverse('location_item_status', kwargs={'html_id': 'hi-unknown-1'})
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
@@ -468,7 +461,7 @@ class TestLocationItemInfoView(SyncViewTestCase):
def test_invalid_item_id_returns_400(self):
"""Test that invalid item IDs return BadRequest."""
# Use an invalid html_id format to trigger BadRequest
- url = reverse('location_item_info', kwargs={'html_id': 'invalid-format'})
+ url = reverse('location_item_status', kwargs={'html_id': 'invalid-format'})
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
@@ -477,13 +470,13 @@ class TestLocationItemInfoView(SyncViewTestCase):
"""Test that POST requests are not allowed."""
from hi.enums import ItemType
html_id = ItemType.ENTITY.html_id(self.entity.id)
- url = reverse('location_item_info', kwargs={'html_id': html_id})
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
response = self.client.post(url)
self.assertEqual(response.status_code, 405)
-class TestLocationItemDetailsView(SyncViewTestCase):
+class TestLocationItemEditModeView(SyncViewTestCase):
"""
Tests for LocationItemDetailsView - demonstrates item details delegation testing.
This view redirects to appropriate details views based on item type.
@@ -506,28 +499,28 @@ class TestLocationItemDetailsView(SyncViewTestCase):
"""Test redirecting to entity edit mode for entity items."""
from hi.enums import ItemType
html_id = ItemType.ENTITY.html_id(self.entity.id)
- url = reverse('location_item_details', kwargs={'html_id': html_id})
+ url = reverse('location_item_edit_mode', kwargs={'html_id': html_id})
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
expected_url = reverse('entity_edit_mode', kwargs={'entity_id': self.entity.id})
self.assertEqual(response.url, expected_url)
- def test_collection_details_redirect(self):
- """Test redirecting to collection details for collection items."""
+ def test_collection_edit_mode_redirect(self):
+ """Test redirecting to collection edit mode for collection items."""
from hi.enums import ItemType
html_id = ItemType.COLLECTION.html_id(self.collection.id)
- url = reverse('location_item_details', kwargs={'html_id': html_id})
+ url = reverse('location_item_edit_mode', kwargs={'html_id': html_id})
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
- expected_url = reverse('collection_details', kwargs={'collection_id': self.collection.id})
+ expected_url = reverse('collection_edit_mode', kwargs={'collection_id': self.collection.id})
self.assertEqual(response.url, expected_url)
def test_unknown_item_type_returns_400(self):
"""Test that unknown item types return BadRequest."""
# Use an invalid html_id format to trigger BadRequest
- url = reverse('location_item_details', kwargs={'html_id': 'hi-unknown-1'})
+ url = reverse('location_item_edit_mode', kwargs={'html_id': 'hi-unknown-1'})
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
@@ -535,7 +528,7 @@ class TestLocationItemDetailsView(SyncViewTestCase):
def test_invalid_item_id_returns_400(self):
"""Test that invalid item IDs return BadRequest."""
# Use an invalid html_id format to trigger BadRequest
- url = reverse('location_item_details', kwargs={'html_id': 'invalid-format'})
+ url = reverse('location_item_edit_mode', kwargs={'html_id': 'invalid-format'})
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
@@ -544,7 +537,7 @@ class TestLocationItemDetailsView(SyncViewTestCase):
"""Test that POST requests are not allowed."""
from hi.enums import ItemType
html_id = ItemType.ENTITY.html_id(self.entity.id)
- url = reverse('location_item_details', kwargs={'html_id': html_id})
+ url = reverse('location_item_edit_mode', kwargs={'html_id': html_id})
response = self.client.post(url)
self.assertEqual(response.status_code, 405)
diff --git a/src/hi/apps/location/transient_models.py b/src/hi/apps/location/transient_models.py
index 34892196..12dfd916 100644
--- a/src/hi/apps/location/transient_models.py
+++ b/src/hi/apps/location/transient_models.py
@@ -1,8 +1,6 @@
from dataclasses import dataclass
from hi.apps.location.edit.forms import (
- LocationAttributeFormSet,
- LocationAttributeUploadForm,
LocationEditForm,
LocationViewEditForm,
)
@@ -11,12 +9,10 @@ from .models import Location, LocationView
@dataclass
-class LocationEditData:
+class LocationEditModeData:
""" All the data needed to render the Location edit pane. """
location : Location
location_edit_form : LocationEditForm = None
- location_attribute_formset : LocationAttributeFormSet = None
- location_attribute_upload_form : LocationAttributeUploadForm = None
def __post_init__(self):
@@ -24,32 +20,17 @@ class LocationEditData:
self.location_edit_form = LocationEditForm(
instance = self.location,
)
- if not self.location_attribute_formset:
- self.location_attribute_formset = LocationAttributeFormSet(
- instance = self.location,
- prefix = f'location-{self.location.id}',
- form_kwargs = {
- 'show_as_editable': True,
- },
- )
- if not self.location_attribute_upload_form:
- self.location_attribute_upload_form = LocationAttributeUploadForm()
-
return
def to_template_context(self):
return {
'location': self.location,
'location_edit_form': self.location_edit_form,
- 'location_attribute_formset': self.location_attribute_formset,
- 'location_attribute_upload_form': self.location_attribute_upload_form,
- 'history_url_name': 'location_attribute_history',
- 'restore_url_name': 'location_attribute_restore',
}
@dataclass
-class LocationViewEditData:
+class LocationViewEditModeData:
""" All the data needed to render the LocationView edit pane. """
location_view : LocationView
diff --git a/src/hi/apps/location/urls.py b/src/hi/apps/location/urls.py
index 257a6cd7..a530582f 100644
--- a/src/hi/apps/location/urls.py
+++ b/src/hi/apps/location/urls.py
@@ -9,14 +9,10 @@ urlpatterns = [
views.LocationSwitchView.as_view(),
name='location_switch'),
- re_path( r'^details/(?P<location_id>\d+)$',
- views.LocationDetailsView.as_view(),
- name='location_details' ),
-
- re_path( r'^view/details/(?P<location_view_id>\d+)$',
- views.LocationViewDetailsView.as_view(),
- name='location_view_details' ),
-
+ re_path( r'^edit/(?P<location_id>\d+)$',
+ views.LocationEditView.as_view(),
+ name='location_edit_location_edit'),
+
re_path( r'^view/(?P<location_view_id>\d+)$',
views.LocationViewView.as_view(),
name='location_view'),
@@ -25,21 +21,21 @@ urlpatterns = [
views.LocationViewDefaultView.as_view(),
name='location_view_default'),
- re_path( r'^item/info/(?P<html_id>[\w\-]+)$',
- views.LocationItemInfoView.as_view(),
- name='location_item_info' ),
-
- re_path( r'^item/details/(?P<html_id>[\w\-]+)$',
- views.LocationItemDetailsView.as_view(),
- name='location_item_details' ),
+ re_path( r'^item/status/(?P<html_id>[\w\-]+)$',
+ views.LocationItemStatusView.as_view(),
+ name='location_item_status' ),
+
+ re_path( r'^attribute/upload/(?P<location_id>\d+)$',
+ views.LocationAttributeUploadView.as_view(),
+ name='location_attribute_upload'),
- re_path( r'^attribute/history/(?P<attribute_id>\d+)$',
- views.LocationAttributeHistoryView.as_view(),
- name='location_attribute_history'),
+ re_path( r'^attribute/history/(?P<location_id>\d+)/(?P<attribute_id>\d+)$',
+ views.LocationAttributeHistoryInlineView.as_view(),
+ name='location_attribute_history_inline'),
- re_path( r'^attribute/restore/(?P<attribute_id>\d+)$',
- views.LocationAttributeRestoreView.as_view(),
- name='location_attribute_restore'),
+ re_path( r'^attribute/restore/(?P<location_id>\d+)/(?P<attribute_id>\d+)/(?P<history_id>\d+)$',
+ views.LocationAttributeRestoreInlineView.as_view(),
+ name='location_attribute_restore_inline'),
re_path( r'^edit/', include('hi.apps.location.edit.urls' )),
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index 72fb5343..7f75f3f6 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -1,22 +1,31 @@
import logging
+from typing import Any, Dict
+from django.db import transaction
from django.core.exceptions import BadRequest
-from django.http import HttpResponseRedirect, HttpResponseNotAllowed
-from django.urls import reverse
+from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
+from django.shortcuts import render, reverse
+from django.template.loader import render_to_string
from django.views.generic import View
+import hi.apps.common.antinode as antinode
from hi.apps.common.utils import is_ajax
+from hi.constants import DIVID
from hi.enums import ItemType, ViewType
from hi.exceptions import ForceSynchronousException
-from hi.hi_async_view import HiSideView
+from hi.hi_async_view import HiModalView
from hi.hi_grid_view import HiGridView
from hi.apps.attribute.views import BaseAttributeHistoryView, BaseAttributeRestoreView
+from hi.views import page_not_found_response
+from .forms import LocationAttributeUploadForm
from .location_manager import LocationManager
-from .models import LocationView, LocationAttribute
-from .transient_models import LocationEditData, LocationViewEditData
+from .models import Location, LocationView, LocationAttribute
from .view_mixins import LocationViewMixin
+from .location_attribute_edit_context import LocationAttributeEditContext
+from .location_edit_form_handler import LocationEditFormHandler
+from .location_edit_response_renderer import LocationEditResponseRenderer
logger = logging.getLogger(__name__)
@@ -89,45 +98,7 @@ class LocationSwitchView( View, LocationViewMixin ):
return HttpResponseRedirect( redirect_url )
-class LocationDetailsView( HiSideView, LocationViewMixin ):
-
- def get_template_name( self ) -> str:
- return 'location/panes/location_edit_mode_panel.html'
-
- def should_push_url( self ):
- return True
-
- def get_template_context( self, request, *args, **kwargs ):
- location = self.get_location( request, *args, **kwargs )
- location_edit_data = LocationEditData(
- location = location,
- )
- return location_edit_data.to_template_context()
-
- def post( self, request, *args, **kwargs ):
- return HttpResponseNotAllowed(['GET'])
-
-
-class LocationViewDetailsView( HiSideView, LocationViewMixin ):
-
- def get_template_name( self ) -> str:
- return 'location/panes/location_view_details.html'
-
- def should_push_url( self ):
- return True
-
- def get_template_context( self, request, *args, **kwargs ):
- location_view = self.get_location_view( request, *args, **kwargs )
- location_view_edit_data = LocationViewEditData(
- location_view = location_view,
- )
- return location_view_edit_data.to_template_context()
-
- def post( self, request, *args, **kwargs ):
- return HttpResponseNotAllowed(['GET'])
-
-
-class LocationItemInfoView( View ):
+class LocationItemStatusView( View ):
def get(self, request, *args, **kwargs):
try:
@@ -146,40 +117,223 @@ class LocationItemInfoView( View ):
raise BadRequest( f'Unknown item type "{item_type}".' )
-class LocationItemDetailsView( View ):
-
- def get(self, request, *args, **kwargs):
- try:
- ( item_type, item_id ) = ItemType.parse_from_dict( kwargs )
- except ValueError:
- raise BadRequest( 'Bad item id.' )
+class LocationEditView(HiModalView, LocationViewMixin):
+ """Location attribute editing modal with redesigned interface.
+
+ This view uses a dual response pattern:
+ - get(): Returns full modal using standard modal_response()
+ - post(): Returns antinode fragments for async DOM updates
+
+ Business logic is delegated to specialized handler classes following
+ the "keep views simple" design philosophy.
+ """
+
+ def get_template_name(self) -> str:
+ return 'location/modals/location_edit.html'
+
+ def get( self,
+ request : HttpRequest,
+ *args : Any,
+ **kwargs: Any ) -> HttpResponse:
+ location: Location = self.get_location(request, *args, **kwargs)
- if item_type == ItemType.ENTITY:
- redirect_url = reverse( 'entity_edit_mode', kwargs = { 'entity_id': item_id } )
- return HttpResponseRedirect( redirect_url )
+ # Delegate form creation and context building to handler
+ form_handler = LocationEditFormHandler()
+ context: Dict[str, Any] = form_handler.create_initial_context(location)
+
+ return self.modal_response(request, context)
- if item_type == ItemType.COLLECTION:
- redirect_url = reverse( 'collection_details', kwargs = { 'collection_id': item_id } )
- return HttpResponseRedirect( redirect_url )
+ def post( self,
+ request : HttpRequest,
+ *args : Any,
+ **kwargs: Any ) -> HttpResponse:
+ location: Location = self.get_location(request, *args, **kwargs)
+
+ # Delegate form handling to specialized handlers
+ form_handler = LocationEditFormHandler()
+ renderer = LocationEditResponseRenderer()
+
+ # Create forms with POST data
+ (
+ location_form,
+ file_attributes,
+ regular_attributes_formset,
+ ) = form_handler.create_location_forms(
+ location, request.POST
+ )
+
+ if form_handler.validate_forms(location_form, regular_attributes_formset):
+ # Save forms and process files
+ form_handler.save_forms(location_form, regular_attributes_formset, request, location)
+
+ # Return success response
+ return renderer.render_success_response(request, location)
+ else:
+ # Return error response
+ return renderer.render_error_response(
+ request, location, location_form, regular_attributes_formset
+ )
+
+ def get_success_url_name(self) -> str:
+ return 'location_edit'
- raise BadRequest( f'Unknown item type "{item_type}".' )
+
+class LocationAttributeUploadView( View, LocationViewMixin ):
+
+ def post( self,
+ request : HttpRequest,
+ *args : Any,
+ **kwargs: Any ) -> HttpResponse:
+ location = self.get_location( request, *args, **kwargs )
+ location_attribute = LocationAttribute( location = location )
+ location_attribute_upload_form = LocationAttributeUploadForm(
+ request.POST,
+ request.FILES,
+ instance = location_attribute,
+ )
+
+ if location_attribute_upload_form.is_valid():
+ with transaction.atomic():
+ location_attribute_upload_form.save()
+
+ # Render new file card HTML to append to file grid
+ from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
+ attr_context = LocationAttributeEditContext(location)
+ context = {'attribute': location_attribute, 'location': location}
+ context.update(attr_context.to_template_context())
+
+ file_card_html: str = render_to_string(
+ 'attribute/components/file_card.html',
+ context,
+ request=request
+ )
+
+ return antinode.response(
+ append_map={
+ DIVID['ATTR_V2_FILE_GRID']: file_card_html
+ },
+ scroll_to=DIVID['ATTR_V2_FILE_GRID']
+ )
+ else:
+ # Render error message to status area
+ error_html: str = render_to_string(
+ 'attribute/components/status_message.html',
+ {
+ 'error_message': 'File upload failed. Please check the file and try again.',
+ 'form_errors': location_attribute_upload_form.errors
+ }
+ )
+
+ return antinode.response(
+ insert_map={
+ DIVID['ATTR_V2_STATUS_MSG']: error_html
+ },
+ status=400
+ )
-class LocationAttributeHistoryView(BaseAttributeHistoryView):
- """View for displaying LocationAttribute history in a modal."""
+class LocationAttributeHistoryInlineView(BaseAttributeHistoryView):
+ """View for displaying LocationAttribute history inline within the edit modal."""
+
+ ATTRIBUTE_HISTORY_VIEW_LIMIT = 50
+
+ def get_template_name(self):
+ return 'attribute/components/attribute_history_inline.html'
def get_attribute_model_class(self):
return LocationAttribute
def get_history_url_name(self):
- return 'location_attribute_history'
+ return 'location_attribute_history_inline'
def get_restore_url_name(self):
- return 'location_attribute_restore'
+ return 'location_attribute_restore_inline'
+
+ def get( self,
+ request : HttpRequest,
+ location_id : int,
+ attribute_id : int,
+ *args : Any,
+ **kwargs : Any ) -> HttpResponse:
+ # Validate that the attribute belongs to this location for security
+ try:
+ attribute: LocationAttribute = LocationAttribute.objects.get(
+ pk=attribute_id, location_id=location_id
+ )
+ except LocationAttribute.DoesNotExist:
+ return page_not_found_response(request, "Attribute not found.")
+
+ # Get history records for this attribute
+ history_model_class = attribute._get_history_model_class()
+ if history_model_class:
+ history_records = history_model_class.objects.filter(
+ attribute=attribute
+ ).order_by('-changed_datetime')[:self.ATTRIBUTE_HISTORY_VIEW_LIMIT] # Limit for inline display
+ else:
+ history_records = []
+
+ # Create the attribute edit context for template generalization
+ attr_context = LocationAttributeEditContext(attribute.location)
+
+ context: Dict[str, Any] = {
+ 'location': attribute.location,
+ 'attribute': attribute,
+ 'history_records': history_records,
+ 'history_url_name': self.get_history_url_name(),
+ 'restore_url_name': self.get_restore_url_name(),
+ }
+
+ # Merge in the context variables from AttributeEditContext
+ context.update(attr_context.to_template_context())
+
+ # Use Django render shortcut
+ return render(request, self.get_template_name(), context)
-class LocationAttributeRestoreView(BaseAttributeRestoreView):
- """View for restoring LocationAttribute values from history."""
+class LocationAttributeRestoreInlineView(BaseAttributeRestoreView):
+ """View for restoring LocationAttribute values from history within the edit modal."""
def get_attribute_model_class(self):
return LocationAttribute
+
+ def get( self,
+ request : HttpRequest,
+ location_id : int,
+ attribute_id : int,
+ history_id : int,
+ *args : Any,
+ **kwargs : Any ) -> HttpResponse:
+ # Validate that the attribute belongs to this location for security
+ try:
+ attribute: LocationAttribute = LocationAttribute.objects.get(
+ pk=attribute_id, location_id=location_id
+ )
+ except LocationAttribute.DoesNotExist:
+ return page_not_found_response(request, "Attribute not found.")
+
+ # Get the history record to restore from
+ history_model_class = attribute._get_history_model_class()
+ if not history_model_class:
+ return page_not_found_response(request, "No history available for this attribute type.")
+
+ try:
+ history_record = history_model_class.objects.get(
+ pk=history_id, attribute=attribute
+ )
+ except history_model_class.DoesNotExist:
+ return page_not_found_response(request, "History record not found.")
+
+ # Restore the value from the history record
+ attribute.value = history_record.value
+ attribute.save() # This will create a new history record
+
+ # Delegate to LocationEditView logic to return updated modal content
+ location: Location = attribute.location
+
+ # Use LocationEditView's render_success_response logic
+ from .location_edit_response_renderer import LocationEditResponseRenderer
+ renderer: LocationEditResponseRenderer = LocationEditResponseRenderer()
+ return renderer.render_success_response(
+ request = request,
+ location = location,
+ )
diff --git a/src/hi/decorators.py b/src/hi/decorators.py
index dbbbb8e8..24b32963 100644
--- a/src/hi/decorators.py
+++ b/src/hi/decorators.py
@@ -8,7 +8,7 @@ logger = logging.getLogger( __name__ )
def edit_required(func):
"""
- Decorator used for views that require an autheticated user with an email.
+ Decorator used for views that require being in editing mode.
"""
@wraps(func)
def wrapper( request, *args, **kwargs):
diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.js
index 0e315583..8801555a 100644
--- a/src/hi/static/js/main.js
+++ b/src/hi/static/js/main.js
@@ -23,8 +23,8 @@
DATA_TYPE_ICON_VALUE: 'svg-icon',
DATA_TYPE_PATH_VALUE: 'svg-path',
- API_LOCATION_ITEM_DETAILS_URL: '/location/item/details',
- API_LOCATION_ITEM_INFO_URL: '/location/item/info',
+ API_LOCATION_ITEM_EDIT_MODE_URL: '/location/edit/item/edit-mode',
+ API_LOCATION_ITEM_STATUS_URL: '/location/item/status',
ENTITY_STATE_VALUE_CHOICES_URL_PREFIX: '/edit/entity/state/values',
generateUniqueId: function() {
diff --git a/src/hi/static/js/svg-icon.js b/src/hi/static/js/svg-icon.js
index 851d3083..fb9a8158 100644
--- a/src/hi/static/js/svg-icon.js
+++ b/src/hi/static/js/svg-icon.js
@@ -10,44 +10,44 @@
const HiEditSvgIcon = {
init: function() {
Hi.edit.eventBus.subscribe( Hi.edit.SELECTION_MADE_EVENT_NAME,
- this.clearSelection.bind(this) );
+ this.clearSelection.bind(this) );
+ },
+ handleSinglePointerEventStart: function( singlePointerEvent ) {
+ return _handleSinglePointerEventStart( singlePointerEvent );
+ },
+ handleSinglePointerEventMove: function( singlePointerEvent ) {
+ return _handleSinglePointerEventMove( singlePointerEvent );
+ },
+ handleSinglePointerEventEnd: function( singlePointerEvent ) {
+ return _handleSinglePointerEventEnd( singlePointerEvent );
+ },
+ handleDoublePointerEventStart: function( doublePointerEvent ) {
+ return _handleDoublePointerEventStart( doublePointerEvent );
+ },
+ handleDoublePointerEventMove: function( doublePointerEvent ) {
+ return _handleDoublePointerEventMove( doublePointerEvent );
+ },
+ handleDoublePointerEventEnd: function( doublePointerEvent ) {
+ return _handleDoublePointerEventEnd( doublePointerEvent );
+ },
+ handleLastPointerLocation: function( x, y ) {
+ _handleLastPointerLocation( x, y );
+ },
+ handleMouseWheel: function( event ) {
+ return _handleMouseWheel( event );
+ },
+ handleClick: function( event ) {
+ return _handleClick( event );
+ },
+ handleKeyDown: function( event ) {
+ return _handleKeyDown( event );
},
- handleSinglePointerEventStart: function( singlePointerEvent ) {
- return _handleSinglePointerEventStart( singlePointerEvent );
- },
- handleSinglePointerEventMove: function( singlePointerEvent ) {
- return _handleSinglePointerEventMove( singlePointerEvent );
- },
- handleSinglePointerEventEnd: function( singlePointerEvent ) {
- return _handleSinglePointerEventEnd( singlePointerEvent );
- },
- handleDoublePointerEventStart: function( doublePointerEvent ) {
- return _handleDoublePointerEventStart( doublePointerEvent );
- },
- handleDoublePointerEventMove: function( doublePointerEvent ) {
- return _handleDoublePointerEventMove( doublePointerEvent );
- },
- handleDoublePointerEventEnd: function( doublePointerEvent ) {
- return _handleDoublePointerEventEnd( doublePointerEvent );
- },
- handleLastPointerLocation: function( x, y ) {
- _handleLastPointerLocation( x, y );
- },
- handleMouseWheel: function( event ) {
- return _handleMouseWheel( event );
- },
- handleClick: function( event ) {
- return _handleClick( event );
- },
- handleKeyDown: function( event ) {
- return _handleKeyDown( event );
- },
clearSelection: function( data ) {
- gCurrentSelectionModule = data.moduleName;
- if ( data.moduleName != MODULE_NAME ) {
- clearSelectedIconSvgGroup();
+ gCurrentSelectionModule = data.moduleName;
+ if ( data.moduleName != MODULE_NAME ) {
+ clearSelectedIconSvgGroup();
}
- }
+ }
};
window.Hi.edit.icon = HiEditSvgIcon;
@@ -78,12 +78,12 @@
const KEYPRESS_ROTATE_DEGREES = 10.0;
const POSITION_API_CALL_DEBOUNCE_MS = 400;
- const API_EDIT_LOCATION_ITEM_POSITION_URL = '/location/edit/location-item/position';
+ const API_EDIT_LOCATION_ITEM_POSITION_URL = '/location/edit/item/position';
const SvgActionStateType = {
- MOVE: 'move',
- SCALE: 'scale',
- ROTATE: 'rotate'
+ MOVE: 'move',
+ SCALE: 'scale',
+ ROTATE: 'rotate'
};
let gSvgIconActionState = SvgActionStateType.MOVE;
@@ -98,552 +98,552 @@
let lastPositionApiCallTime = 0;
function _handleSinglePointerEventStart( singlePointerEvent ) {
- if ( ! Hi.isEditMode ) { return false; }
-
- if ( gSvgIconActionEditData ) {
- if ( Hi.DEBUG ) { console.log( `Pointer down [${MODULE_NAME}]`, singlePointerEvent ); }
- if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
- gSvgIconActionEditData.isScaling = true;
- } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
- gSvgIconActionEditData.isRotating = true;
- }
- return true;
- } else {
- const enclosingSvgGroup = $(singlePointerEvent.start.event.target).closest('g');
- if ( enclosingSvgGroup.length > 0 ) {
- const svgDataType = $(enclosingSvgGroup).attr( Hi.DATA_TYPE_ATTR );
- if ( svgDataType == Hi.DATA_TYPE_ICON_VALUE ) {
-
- if ( $(enclosingSvgGroup).attr('id') != $(gSelectedIconSvgGroup).attr('id')) {
- clearSelectedIconSvgGroup();
- gSelectedIconSvgGroup = enclosingSvgGroup[0];
- }
-
- if ( Hi.DEBUG ) { console.log( `Pointer down [${MODULE_NAME}]`, singlePointerEvent ); }
- startDrag( singlePointerEvent, enclosingSvgGroup );
- return true;
- }
- }
- }
- if ( Hi.DEBUG ) { console.log( `Pointer down skipped [${MODULE_NAME}]` ); }
- return false;
+ if ( ! Hi.isEditMode ) { return false; }
+
+ if ( gSvgIconActionEditData ) {
+ if ( Hi.DEBUG ) { console.log( `Pointer down [${MODULE_NAME}]`, singlePointerEvent ); }
+ if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
+ gSvgIconActionEditData.isScaling = true;
+ } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
+ gSvgIconActionEditData.isRotating = true;
+ }
+ return true;
+ } else {
+ const enclosingSvgGroup = $(singlePointerEvent.start.event.target).closest('g');
+ if ( enclosingSvgGroup.length > 0 ) {
+ const svgDataType = $(enclosingSvgGroup).attr( Hi.DATA_TYPE_ATTR );
+ if ( svgDataType == Hi.DATA_TYPE_ICON_VALUE ) {
+
+ if ( $(enclosingSvgGroup).attr('id') != $(gSelectedIconSvgGroup).attr('id')) {
+ clearSelectedIconSvgGroup();
+ gSelectedIconSvgGroup = enclosingSvgGroup[0];
+ }
+
+ if ( Hi.DEBUG ) { console.log( `Pointer down [${MODULE_NAME}]`, singlePointerEvent ); }
+ startDrag( singlePointerEvent, enclosingSvgGroup );
+ return true;
+ }
+ }
+ }
+ if ( Hi.DEBUG ) { console.log( `Pointer down skipped [${MODULE_NAME}]` ); }
+ return false;
}
function _handleSinglePointerEventMove( singlePointerEvent ) {
- if ( ! Hi.isEditMode ) { return false; }
-
- const currentPointPosition = {
- x: singlePointerEvent.last.x,
- y: singlePointerEvent.last.y
- };
-
- let handled = false;
-
- if ( gSvgIconActionEditData ) {
- if ( gSvgIconActionEditData.isScaling ) {
- updateScaleFromPointerMove( singlePointerEvent );
- handled = true;
- } else if ( gSvgIconActionEditData.isRotating ) {
- updateRotateFromPointerMove( singlePointerEvent );
- handled = true;
- }
- }
-
- if ( gSvgIconDragData ) {
- const distanceX = Math.abs( currentPointPosition.x - singlePointerEvent.start.x );
- const distanceY = Math.abs( currentPointPosition.y - singlePointerEvent.start.y );
- gSvgIconDragData.isDragging = true;
- $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, SvgActionStateType.MOVE);
- updateDrag( singlePointerEvent );
- handled = true;
- }
- return handled;
+ if ( ! Hi.isEditMode ) { return false; }
+
+ const currentPointPosition = {
+ x: singlePointerEvent.last.x,
+ y: singlePointerEvent.last.y
+ };
+
+ let handled = false;
+
+ if ( gSvgIconActionEditData ) {
+ if ( gSvgIconActionEditData.isScaling ) {
+ updateScaleFromPointerMove( singlePointerEvent );
+ handled = true;
+ } else if ( gSvgIconActionEditData.isRotating ) {
+ updateRotateFromPointerMove( singlePointerEvent );
+ handled = true;
+ }
+ }
+
+ if ( gSvgIconDragData ) {
+ const distanceX = Math.abs( currentPointPosition.x - singlePointerEvent.start.x );
+ const distanceY = Math.abs( currentPointPosition.y - singlePointerEvent.start.y );
+ gSvgIconDragData.isDragging = true;
+ $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, SvgActionStateType.MOVE);
+ updateDrag( singlePointerEvent );
+ handled = true;
+ }
+ return handled;
}
function _handleSinglePointerEventEnd( singlePointerEvent ) {
- if ( ! Hi.isEditMode ) { return false; }
+ if ( ! Hi.isEditMode ) { return false; }
- let handled = endSinglePointerEvent();
- if ( handled ) {
- if ( Hi.DEBUG ) { console.log( `Pointer end [${MODULE_NAME}]`, singlePointerEvent ); }
- } else {
- if ( Hi.DEBUG ) { console.log( `Pointer end skipped [${MODULE_NAME}]` ); }
- }
- return handled;
+ let handled = endSinglePointerEvent();
+ if ( handled ) {
+ if ( Hi.DEBUG ) { console.log( `Pointer end [${MODULE_NAME}]`, singlePointerEvent ); }
+ } else {
+ if ( Hi.DEBUG ) { console.log( `Pointer end skipped [${MODULE_NAME}]` ); }
+ }
+ return handled;
}
function endSinglePointerEvent() {
- if ( gSvgIconActionEditData ) {
- if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
- gSvgIconActionEditData.isScaling = false;
- endScale();
- } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
- gSvgIconActionEditData.isRotating = false;
- endRotate();
- }
- gSvgIconActionState = SvgActionStateType.MOVE;
- $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '');
- gSvgIconActionEditData = null;
- gIgnoreCLick = true;
- return true;
- }
-
- if ( gSvgIconDragData ) {
- if ( gSvgIconDragData.isDragging ) {
- endDrag();
- gIgnoreCLick = true;
- $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '');
- }
- $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '' );
- gSvgIconDragData = null;
- return true;
- }
- return false;
+ if ( gSvgIconActionEditData ) {
+ if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
+ gSvgIconActionEditData.isScaling = false;
+ endScale();
+ } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
+ gSvgIconActionEditData.isRotating = false;
+ endRotate();
+ }
+ gSvgIconActionState = SvgActionStateType.MOVE;
+ $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '');
+ gSvgIconActionEditData = null;
+ gIgnoreCLick = true;
+ return true;
+ }
+
+ if ( gSvgIconDragData ) {
+ if ( gSvgIconDragData.isDragging ) {
+ endDrag();
+ gIgnoreCLick = true;
+ $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '');
+ }
+ $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '' );
+ gSvgIconDragData = null;
+ return true;
+ }
+ return false;
}
function _handleDoublePointerEventStart( doublePointerEvent ) {
- if ( ! Hi.isEditMode ) { return false; }
- if ( ! gSelectedIconSvgGroup ) { return false; }
- endSinglePointerEvent();
- return true;
+ if ( ! Hi.isEditMode ) { return false; }
+ if ( ! gSelectedIconSvgGroup ) { return false; }
+ endSinglePointerEvent();
+ return true;
}
function _handleDoublePointerEventMove( doublePointerEvent ) {
- if ( ! Hi.isEditMode ) { return false; }
- if ( ! gSelectedIconSvgGroup ) { return false; }
-
- let scaleMultiplier = ( 1.0 + ( doublePointerEvent.deltaDistancePrevious
- / POINTER_EVENTS_SCALE_FACTOR ));
- let deltaAngle = doublePointerEvent.deltaAngleStart * POINTER_EVENTS_ROTATE_FACTOR;
+ if ( ! Hi.isEditMode ) { return false; }
+ if ( ! gSelectedIconSvgGroup ) { return false; }
+
+ let scaleMultiplier = ( 1.0 + ( doublePointerEvent.deltaDistancePrevious
+ / POINTER_EVENTS_SCALE_FACTOR ));
+ let deltaAngle = doublePointerEvent.deltaAngleStart * POINTER_EVENTS_ROTATE_FACTOR;
- updateScale( gSelectedIconSvgGroup, scaleMultiplier );
- updateRotate( gSelectedIconSvgGroup, deltaAngle );
- return true;
+ updateScale( gSelectedIconSvgGroup, scaleMultiplier );
+ updateRotate( gSelectedIconSvgGroup, deltaAngle );
+ return true;
}
function _handleDoublePointerEventEnd( doublePointerEvent ) {
- let handled = endDoublePointerEvent();
- if ( handled ) {
- if ( Hi.DEBUG ) { console.log( `Touch-2 end: [${MODULE_NAME}]`, event ); }
- } else {
- if ( Hi.DEBUG ) { console.log( `Touch-2 end skipped: [${MODULE_NAME}]`, event ); }
- }
- return handled;
+ let handled = endDoublePointerEvent();
+ if ( handled ) {
+ if ( Hi.DEBUG ) { console.log( `Touch-2 end: [${MODULE_NAME}]`, event ); }
+ } else {
+ if ( Hi.DEBUG ) { console.log( `Touch-2 end skipped: [${MODULE_NAME}]`, event ); }
+ }
+ return handled;
}
function endDoublePointerEvent() {
- if ( ! Hi.isEditMode ) { return false; }
- if ( ! gSelectedIconSvgGroup ) { return false; }
- saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
- return true;
+ if ( ! Hi.isEditMode ) { return false; }
+ if ( ! gSelectedIconSvgGroup ) { return false; }
+ saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
+ return true;
}
function _handleLastPointerLocation( x, y ) {
- gLastPointerPosition.x = x;
- gLastPointerPosition.y = y;
+ gLastPointerPosition.x = x;
+ gLastPointerPosition.y = y;
}
function _handleMouseWheel( event ) {
- if ( ! Hi.isEditMode ) { return false; }
-
- if ( gSvgIconDragData ) {
- return false;
- }
-
- if ( gSvgIconActionEditData ) {
- if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
- updateScaleFromMouseWheel( event );
- event.preventDefault();
- event.stopImmediatePropagation();
- return true;
- } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
- updateRotateFromMouseWheel( event );
- event.preventDefault();
- event.stopImmediatePropagation();
- return true;
- }
- }
- return false;
+ if ( ! Hi.isEditMode ) { return false; }
+
+ if ( gSvgIconDragData ) {
+ return false;
+ }
+
+ if ( gSvgIconActionEditData ) {
+ if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
+ updateScaleFromMouseWheel( event );
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+ } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
+ updateRotateFromMouseWheel( event );
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+ }
+ }
+ return false;
}
function _handleClick( event ) {
- if ( gIgnoreCLick ) {
- if ( Hi.DEBUG ) { console.log( `Ignoring click [${MODULE_NAME}]`, event ); }
- gIgnoreCLick = false;
- return true;
- }
- gIgnoreCLick = false;
-
- const enclosingSvgGroup = $(event.target).closest('g');
- if ( enclosingSvgGroup.length > 0 ) {
- let svgDataType = $(enclosingSvgGroup).attr( Hi.DATA_TYPE_ATTR );
- const isSvgIcon = ( svgDataType == Hi.DATA_TYPE_ICON_VALUE );
- const svgItemId = enclosingSvgGroup.attr('id');
- if ( isSvgIcon && svgItemId ) {
- console.log( `Click [${MODULE_NAME}]`, event );
- if ( Hi.DEBUG ) { console.log( 'SVG Target Element', enclosingSvgGroup ); }
- handleSvgIconClick( event, enclosingSvgGroup );
- return true;
- }
- }
- if ( Hi.DEBUG ) { console.log( `Click skipped [${MODULE_NAME}]` ); }
- return false;
+ if ( gIgnoreCLick ) {
+ if ( Hi.DEBUG ) { console.log( `Ignoring click [${MODULE_NAME}]`, event ); }
+ gIgnoreCLick = false;
+ return true;
+ }
+ gIgnoreCLick = false;
+
+ const enclosingSvgGroup = $(event.target).closest('g');
+ if ( enclosingSvgGroup.length > 0 ) {
+ let svgDataType = $(enclosingSvgGroup).attr( Hi.DATA_TYPE_ATTR );
+ const isSvgIcon = ( svgDataType == Hi.DATA_TYPE_ICON_VALUE );
+ const svgItemId = enclosingSvgGroup.attr('id');
+ if ( isSvgIcon && svgItemId ) {
+ console.log( `Click [${MODULE_NAME}]`, event );
+ if ( Hi.DEBUG ) { console.log( 'SVG Target Element', enclosingSvgGroup ); }
+ handleSvgIconClick( event, enclosingSvgGroup );
+ return true;
+ }
+ }
+ if ( Hi.DEBUG ) { console.log( `Click skipped [${MODULE_NAME}]` ); }
+ return false;
}
function _handleKeyDown( event ) {
- if ( ! Hi.isEditMode ) { return false; }
-
- if ( $(event.target).is('input, textarea') ) {
+ if ( ! Hi.isEditMode ) { return false; }
+
+ if ( $(event.target).is('input, textarea') ) {
return false;
- }
- if ($(event.target).closest('.modal').length > 0) {
+ }
+ if ($(event.target).closest('.modal').length > 0) {
return false;
- }
- if ( gSelectedIconSvgGroup ) {
- const targetArea = $(Hi.LOCATION_VIEW_AREA_SELECTOR);
+ }
+ if ( gSelectedIconSvgGroup ) {
+ const targetArea = $(Hi.LOCATION_VIEW_AREA_SELECTOR);
const targetOffset = targetArea.offset();
const targetWidth = targetArea.outerWidth();
const targetHeight = targetArea.outerHeight();
-
+
if (( gLastPointerPosition.x >= targetOffset.left )
- && ( gLastPointerPosition.x <= ( targetOffset.left + targetWidth ))
- && ( gLastPointerPosition.y >= targetOffset.top )
- && ( gLastPointerPosition.y <= ( targetOffset.top + targetHeight ))) {
-
- if ( Hi.DEBUG ) { console.log( `Key Down [${MODULE_NAME}]`, event ); }
-
- if ( event.key == ICON_ACTION_SCALE_KEY ) {
- rotateAbort();
- startScale();
-
- } else if ( event.key == ICON_ACTION_ROTATE_KEY ) {
- scaleAbort();
- startRotate();
-
- } else if ( event.key == ICON_ACTION_ZOOM_IN_KEY ) {
- if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
- scaleUpFromKeypress();
- } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
- rotateRightFromKeypress();
- }
-
- } else if ( event.key == ICON_ACTION_ZOOM_OUT_KEY ) {
- if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
- scaleDownFromKeypress();
- } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
- rotateLeftFromKeypress();
- }
-
- } else if ( event.key == 'Escape' ) {
- scaleAbort();
- rotateAbort();
- gSvgIconActionState = SvgActionStateType.MOVE;
- $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '');
- clearSelectedIconSvgGroup();
- }
- event.preventDefault();
- event.stopImmediatePropagation();
- return true;
- }
- }
- if ( Hi.DEBUG ) { console.log( `Key down skipped [${MODULE_NAME}]` ); }
- return false;
+ && ( gLastPointerPosition.x <= ( targetOffset.left + targetWidth ))
+ && ( gLastPointerPosition.y >= targetOffset.top )
+ && ( gLastPointerPosition.y <= ( targetOffset.top + targetHeight ))) {
+
+ if ( Hi.DEBUG ) { console.log( `Key Down [${MODULE_NAME}]`, event ); }
+
+ if ( event.key == ICON_ACTION_SCALE_KEY ) {
+ rotateAbort();
+ startScale();
+
+ } else if ( event.key == ICON_ACTION_ROTATE_KEY ) {
+ scaleAbort();
+ startRotate();
+
+ } else if ( event.key == ICON_ACTION_ZOOM_IN_KEY ) {
+ if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
+ scaleUpFromKeypress();
+ } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
+ rotateRightFromKeypress();
+ }
+
+ } else if ( event.key == ICON_ACTION_ZOOM_OUT_KEY ) {
+ if ( gSvgIconActionState == SvgActionStateType.SCALE ) {
+ scaleDownFromKeypress();
+ } else if ( gSvgIconActionState == SvgActionStateType.ROTATE ) {
+ rotateLeftFromKeypress();
+ }
+
+ } else if ( event.key == 'Escape' ) {
+ scaleAbort();
+ rotateAbort();
+ gSvgIconActionState = SvgActionStateType.MOVE;
+ $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '');
+ clearSelectedIconSvgGroup();
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+ }
+ }
+ if ( Hi.DEBUG ) { console.log( `Key down skipped [${MODULE_NAME}]` ); }
+ return false;
}
function handleSvgIconClick( event, enclosingSvgGroup ) {
- const svgItemId = $(enclosingSvgGroup).attr('id');
+ const svgItemId = $(enclosingSvgGroup).attr('id');
- if ( Hi.isEditMode ) {
- clearSelectedIconSvgGroup();
- gSelectedIconSvgGroup = $(enclosingSvgGroup)[0];
+ if ( Hi.isEditMode ) {
+ clearSelectedIconSvgGroup();
+ gSelectedIconSvgGroup = $(enclosingSvgGroup)[0];
$(enclosingSvgGroup).addClass( Hi.HIGHLIGHTED_CLASS );
- gSvgIconActionState = SvgActionStateType.MOVE;
- let data = {
- moduleName: MODULE_NAME,
- };
- Hi.edit.eventBus.emit( Hi.edit.SELECTION_MADE_EVENT_NAME, data );
- AN.get( `${Hi.API_LOCATION_ITEM_DETAILS_URL}/${svgItemId}` );
+ gSvgIconActionState = SvgActionStateType.MOVE;
+ let data = {
+ moduleName: MODULE_NAME,
+ };
+ Hi.edit.eventBus.emit( Hi.edit.SELECTION_MADE_EVENT_NAME, data );
+ AN.get( `${Hi.API_LOCATION_ITEM_EDIT_MODE_URL}/${svgItemId}` );
- } else {
- AN.get( `${Hi.API_LOCATION_ITEM_INFO_URL}/${svgItemId}` );
- }
+ } else {
+ AN.get( `${Hi.API_LOCATION_ITEM_STATUS_URL}/${svgItemId}` );
+ }
}
function clearSelectedIconSvgGroup() {
- if ( gSelectedIconSvgGroup ) {
+ if ( gSelectedIconSvgGroup ) {
if ( Hi.DEBUG ) { console.log('Clearing svg icon selection'); }
- $( SELECTABLE_SELECTOR ).removeClass( Hi.HIGHLIGHTED_CLASS );
- gSelectedIconSvgGroup = null;
- }
+ $( SELECTABLE_SELECTOR ).removeClass( Hi.HIGHLIGHTED_CLASS );
+ gSelectedIconSvgGroup = null;
+ }
}
- function startDrag( singlePointerEvent, enclosingSvgGroup ) {
+ function startDrag( singlePointerEvent, enclosingSvgGroup ) {
- const dragElement = enclosingSvgGroup;
+ const dragElement = enclosingSvgGroup;
Hi.displayElementInfo( 'Drag Element', dragElement );
-
- const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
- Hi.displayElementInfo( 'Base SVG', baseSvgElement );
+
+ const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
+ Hi.displayElementInfo( 'Base SVG', baseSvgElement );
let transform = $(dragElement).attr('transform') || '';
let { scale, translate, rotate } = Hi.svgUtils.getSvgTransformValues( transform );
let cursorSvgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement,
- singlePointerEvent.last.x,
- singlePointerEvent.last.y );
-
- const cursorSvgOffset = {
- x : (cursorSvgPoint.x / scale.x) - translate.x,
- y : (cursorSvgPoint.y / scale.y) - translate.y
- };
-
- gSvgIconDragData = {
- element: dragElement,
- baseSvgElement: baseSvgElement,
- cursorSvgOffset: cursorSvgOffset,
- originalSvgScale: scale,
- originalSvgRotate: rotate,
- isDragging: false
- };
-
- if ( Hi.DEBUG ) {
- console.log( `Drag Start:
+ singlePointerEvent.last.x,
+ singlePointerEvent.last.y );
+
+ const cursorSvgOffset = {
+ x : (cursorSvgPoint.x / scale.x) - translate.x,
+ y : (cursorSvgPoint.y / scale.y) - translate.y
+ };
+
+ gSvgIconDragData = {
+ element: dragElement,
+ baseSvgElement: baseSvgElement,
+ cursorSvgOffset: cursorSvgOffset,
+ originalSvgScale: scale,
+ originalSvgRotate: rotate,
+ isDragging: false
+ };
+
+ if ( Hi.DEBUG ) {
+ console.log( `Drag Start:
SVG Cursor Point: ( ${cursorSvgPoint.x}, ${cursorSvgPoint.y} ),
SVG Cursor Offset: ( ${gSvgIconDragData.cursorSvgOffset.x}, ${gSvgIconDragData.cursorSvgOffset.y} )`);
- }
-
+ }
+
}
function updateDrag( singlePointerEvent ) {
if ( gSvgIconDragData == null ) {
- return;
- }
+ return;
+ }
Hi.displayEventInfo( 'Update Drag', singlePointerEvent );
Hi.displayElementInfo( 'Drag Element', gSvgIconDragData.element );
let cursorSvgPoint = Hi.svgUtils.toSvgPoint( gSvgIconDragData.baseSvgElement,
- singlePointerEvent.last.x,
- singlePointerEvent.last.y );
+ singlePointerEvent.last.x,
+ singlePointerEvent.last.y );
- let scale = gSvgIconDragData.originalSvgScale;
- let rotate = gSvgIconDragData.originalSvgRotate;
- let translate = {
- x: (cursorSvgPoint.x / scale.x) - gSvgIconDragData.cursorSvgOffset.x,
- y: (cursorSvgPoint.y / scale.y) - gSvgIconDragData.cursorSvgOffset.y
- };
+ let scale = gSvgIconDragData.originalSvgScale;
+ let rotate = gSvgIconDragData.originalSvgRotate;
+ let translate = {
+ x: (cursorSvgPoint.x / scale.x) - gSvgIconDragData.cursorSvgOffset.x,
+ y: (cursorSvgPoint.y / scale.y) - gSvgIconDragData.cursorSvgOffset.y
+ };
- setSvgTransformAttr( gSvgIconDragData.element, scale, translate, rotate );
+ setSvgTransformAttr( gSvgIconDragData.element, scale, translate, rotate );
}
function endDrag() {
if ( gSvgIconDragData == null ) {
- return;
- }
-
+ return;
+ }
+
Hi.displayElementInfo( 'End Drag Element', gSvgIconDragData.element );
- saveIconSvgPositionDebouncer( gSvgIconDragData.element );
- gSvgIconDragData = null;
+ saveIconSvgPositionDebouncer( gSvgIconDragData.element );
+ gSvgIconDragData = null;
}
function startIconAction( actionState ) {
- if ( gSelectedIconSvgGroup ) {
+ if ( gSelectedIconSvgGroup ) {
let transform = $(gSelectedIconSvgGroup).attr('transform');
let { scale, translate, rotate } = Hi.svgUtils.getSvgTransformValues( transform );
- gSvgIconActionEditData = {
- element: gSelectedIconSvgGroup,
- scaleStart: scale,
- translateStart: translate,
- rotateStart: rotate,
- isScaling: false,
- isRotating: false
- };
+ gSvgIconActionEditData = {
+ element: gSelectedIconSvgGroup,
+ scaleStart: scale,
+ translateStart: translate,
+ rotateStart: rotate,
+ isScaling: false,
+ isRotating: false
+ };
- gSvgIconActionState = actionState;
- $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, actionState );
- }
+ gSvgIconActionState = actionState;
+ $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, actionState );
+ }
}
function endIconAction( element ) {
- if ( gSvgIconActionEditData ) {
- gSvgIconActionEditData = null;
- }
+ if ( gSvgIconActionEditData ) {
+ gSvgIconActionEditData = null;
+ }
}
function startScale() {
- startIconAction( SvgActionStateType.SCALE );
+ startIconAction( SvgActionStateType.SCALE );
}
function updateScaleFromMouseWheel( event ) {
- const e = event.originalEvent;
- let scaleMultiplier = 1.0 + ( MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
- if ( e.deltaY > 0 ) {
- scaleMultiplier = 1.0 - ( MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
- }
- console.log( `Scale multiplier = ${scaleMultiplier} [${gSvgIconActionEditData.isScaling}]` );
- updateScale( gSvgIconActionEditData.element, scaleMultiplier );
- saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
+ const e = event.originalEvent;
+ let scaleMultiplier = 1.0 + ( MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
+ if ( e.deltaY > 0 ) {
+ scaleMultiplier = 1.0 - ( MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
+ }
+ console.log( `Scale multiplier = ${scaleMultiplier} [${gSvgIconActionEditData.isScaling}]` );
+ updateScale( gSvgIconActionEditData.element, scaleMultiplier );
+ saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
}
function scaleUpFromKeypress() {
- if ( gSelectedIconSvgGroup ) {
- let scaleMultiplier = 1.0 + ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
- updateScale( gSelectedIconSvgGroup, scaleMultiplier );
- saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
- }
+ if ( gSelectedIconSvgGroup ) {
+ let scaleMultiplier = 1.0 + ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
+ updateScale( gSelectedIconSvgGroup, scaleMultiplier );
+ saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
+ }
}
function scaleDownFromKeypress() {
- if ( gSelectedIconSvgGroup ) {
- let scaleMultiplier = 1.0 - ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
- updateScale( gSelectedIconSvgGroup, scaleMultiplier );
- saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
- }
+ if ( gSelectedIconSvgGroup ) {
+ let scaleMultiplier = 1.0 - ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
+ updateScale( gSelectedIconSvgGroup, scaleMultiplier );
+ saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
+ }
}
function updateScaleFromPointerMove( singlePointerEvent ) {
- if ( Hi.DEBUG ) { console.log( `updateScale [${MODULE_NAME}]` ); }
-
- let center = Hi.getScreenCenterPoint( gSvgIconActionEditData.element );
- const startX = singlePointerEvent.previous.x;
- const startY = singlePointerEvent.previous.y;
- const endX = singlePointerEvent.last.x;
- const endY = singlePointerEvent.last.y;
- const startDistance = Math.sqrt( Math.pow(startX - center.x, 2) + Math.pow(startY - center.y, 2) );
- const endDistance = Math.sqrt( Math.pow(endX - center.x, 2) + Math.pow(endY - center.y, 2) );
- const moveDistance = Math.abs( endDistance - startDistance );
-
- let scaleMultiplier = 1.0;
- if ( endDistance > startDistance ) {
- scaleMultiplier = 2 ** ( moveDistance / POINTER_MOVE_ZOOM_SCALE_FACTOR );
- } else {
- scaleMultiplier = 2 ** ( -1.0 * moveDistance / POINTER_MOVE_ZOOM_SCALE_FACTOR );
- }
-
- if ( Hi.DEBUG ) {
- console.log( `Scale: moveDistance=${moveDistance}, multiplier=${scaleMultiplier}` );
- }
- updateScale( gSvgIconActionEditData.element, scaleMultiplier );
- return;
+ if ( Hi.DEBUG ) { console.log( `updateScale [${MODULE_NAME}]` ); }
+
+ let center = Hi.getScreenCenterPoint( gSvgIconActionEditData.element );
+ const startX = singlePointerEvent.previous.x;
+ const startY = singlePointerEvent.previous.y;
+ const endX = singlePointerEvent.last.x;
+ const endY = singlePointerEvent.last.y;
+ const startDistance = Math.sqrt( Math.pow(startX - center.x, 2) + Math.pow(startY - center.y, 2) );
+ const endDistance = Math.sqrt( Math.pow(endX - center.x, 2) + Math.pow(endY - center.y, 2) );
+ const moveDistance = Math.abs( endDistance - startDistance );
+
+ let scaleMultiplier = 1.0;
+ if ( endDistance > startDistance ) {
+ scaleMultiplier = 2 ** ( moveDistance / POINTER_MOVE_ZOOM_SCALE_FACTOR );
+ } else {
+ scaleMultiplier = 2 ** ( -1.0 * moveDistance / POINTER_MOVE_ZOOM_SCALE_FACTOR );
+ }
+
+ if ( Hi.DEBUG ) {
+ console.log( `Scale: moveDistance=${moveDistance}, multiplier=${scaleMultiplier}` );
+ }
+ updateScale( gSvgIconActionEditData.element, scaleMultiplier );
+ return;
}
function updateScale( svgIconElement, scaleMultiplier ) {
let transformStr = $(svgIconElement).attr('transform');
- const oldTransform = Hi.svgUtils.getSvgTransformValues( transformStr );
- const newScale = {
- x: oldTransform.scale.x * scaleMultiplier,
- y: oldTransform.scale.y * scaleMultiplier
- };
- const newTranslate = {
- x: oldTransform.translate.x * oldTransform.scale.x / newScale.x,
- y: oldTransform.translate.y * oldTransform.scale.y / newScale.y
- };
-
- if ( Hi.DEBUG ) {
- console.log( `Scale Update:
+ const oldTransform = Hi.svgUtils.getSvgTransformValues( transformStr );
+ const newScale = {
+ x: oldTransform.scale.x * scaleMultiplier,
+ y: oldTransform.scale.y * scaleMultiplier
+ };
+ const newTranslate = {
+ x: oldTransform.translate.x * oldTransform.scale.x / newScale.x,
+ y: oldTransform.translate.y * oldTransform.scale.y / newScale.y
+ };
+
+ if ( Hi.DEBUG ) {
+ console.log( `Scale Update:
Original (str): ${transformStr}
Old (parsed): ${JSON.stringify(oldTransform)}
Multiplier: ${scaleMultiplier}
New: S = ${JSON.stringify(newScale)}, T = ${JSON.stringify(newTranslate)}, R = ${JSON.stringify(oldTransform.rotate)}` );
- }
+ }
- setSvgTransformAttr( svgIconElement, newScale, newTranslate, oldTransform.rotate );
+ setSvgTransformAttr( svgIconElement, newScale, newTranslate, oldTransform.rotate );
}
function endScale() {
- if ( Hi.DEBUG ) { console.log( 'Scale End' ); }
- saveIconSvgPosition( gSvgIconActionEditData.element );
+ if ( Hi.DEBUG ) { console.log( 'Scale End' ); }
+ saveIconSvgPosition( gSvgIconActionEditData.element );
}
function scaleAbort() {
- if ( gSvgIconActionState != SvgActionStateType.SCALE ) {
- return;
- }
- endIconAction();
+ if ( gSvgIconActionState != SvgActionStateType.SCALE ) {
+ return;
+ }
+ endIconAction();
}
function startRotate() {
- startIconAction( SvgActionStateType.ROTATE );
+ startIconAction( SvgActionStateType.ROTATE );
}
function updateRotateFromPointerMove( singlePointerEvent ) {
- if ( Hi.DEBUG ) { console.log( `updateRotation [${MODULE_NAME}]` ); }
+ if ( Hi.DEBUG ) { console.log( `updateRotation [${MODULE_NAME}]` ); }
- let center = Hi.getScreenCenterPoint( gSvgIconActionEditData.element );
+ let center = Hi.getScreenCenterPoint( gSvgIconActionEditData.element );
- let deltaAngle = Hi.getRotationAngle( center.x, center.y,
- singlePointerEvent.previous.x, singlePointerEvent.previous.y,
- singlePointerEvent.last.x, singlePointerEvent.last.y );
-
+ let deltaAngle = Hi.getRotationAngle( center.x, center.y,
+ singlePointerEvent.previous.x, singlePointerEvent.previous.y,
+ singlePointerEvent.last.x, singlePointerEvent.last.y );
+
let transformStr = $(gSvgIconActionEditData.element).attr('transform');
- const oldTransform = Hi.svgUtils.getSvgTransformValues( transformStr );
+ const oldTransform = Hi.svgUtils.getSvgTransformValues( transformStr );
- const newRotate = { ...oldTransform.rotate }; // Create a copy of old values
- newRotate.angle += deltaAngle;
- newRotate.angle = Hi.normalizeAngle( newRotate.angle );
+ const newRotate = { ...oldTransform.rotate }; // Create a copy of old values
+ newRotate.angle += deltaAngle;
+ newRotate.angle = Hi.normalizeAngle( newRotate.angle );
- setSvgTransformAttr( gSvgIconActionEditData.element,
- oldTransform.scale, oldTransform.translate, newRotate );
+ setSvgTransformAttr( gSvgIconActionEditData.element,
+ oldTransform.scale, oldTransform.translate, newRotate );
}
function updateRotateFromMouseWheel( event ) {
- const e = event.originalEvent;
- let deltaAngle = MOUSE_WHEEL_ROTATE_DEGREES;
- if ( e.deltaY > 0 ) {
- deltaAngle = -1.0 * MOUSE_WHEEL_ROTATE_DEGREES;
- }
- updateRotate( gSvgIconActionEditData.element, deltaAngle );
- saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
+ const e = event.originalEvent;
+ let deltaAngle = MOUSE_WHEEL_ROTATE_DEGREES;
+ if ( e.deltaY > 0 ) {
+ deltaAngle = -1.0 * MOUSE_WHEEL_ROTATE_DEGREES;
+ }
+ updateRotate( gSvgIconActionEditData.element, deltaAngle );
+ saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
}
function rotateRightFromKeypress() {
- let deltaAngle = KEYPRESS_ROTATE_DEGREES;
- updateRotate( gSelectedIconSvgGroup, deltaAngle );
- saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
+ let deltaAngle = KEYPRESS_ROTATE_DEGREES;
+ updateRotate( gSelectedIconSvgGroup, deltaAngle );
+ saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
}
function rotateLeftFromKeypress() {
- let deltaAngle = -1.0 * KEYPRESS_ROTATE_DEGREES;
- updateRotate( gSelectedIconSvgGroup, deltaAngle );
- saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
+ let deltaAngle = -1.0 * KEYPRESS_ROTATE_DEGREES;
+ updateRotate( gSelectedIconSvgGroup, deltaAngle );
+ saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
}
function updateRotate( svgIconElement, deltaAngle ) {
let transformStr = $(svgIconElement).attr('transform');
- const oldTransform = Hi.svgUtils.getSvgTransformValues( transformStr );
-
- const newRotate = { ...oldTransform.rotate }; // Create a copy of old values
- newRotate.angle += deltaAngle;
- newRotate.angle = Hi.normalizeAngle( newRotate.angle );
-
- if ( Hi.DEBUG ) {
- console.log( `Rotate Update:
+ const oldTransform = Hi.svgUtils.getSvgTransformValues( transformStr );
+
+ const newRotate = { ...oldTransform.rotate }; // Create a copy of old values
+ newRotate.angle += deltaAngle;
+ newRotate.angle = Hi.normalizeAngle( newRotate.angle );
+
+ if ( Hi.DEBUG ) {
+ console.log( `Rotate Update:
Original (str): ${transformStr}
Old (parsed): ${JSON.stringify(oldTransform)}
Angle Delta: ${deltaAngle}
New: S = ${JSON.stringify(oldTransform.scale)}, T = ${JSON.stringify(oldTransform.translate)}, R = ${JSON.stringify(newRotate)}` );
- }
-
- setSvgTransformAttr( svgIconElement,
- oldTransform.scale, oldTransform.translate, newRotate );
+ }
+
+ setSvgTransformAttr( svgIconElement,
+ oldTransform.scale, oldTransform.translate, newRotate );
}
function endRotate() {
- saveIconSvgPosition( gSvgIconActionEditData.element );
+ saveIconSvgPosition( gSvgIconActionEditData.element );
}
function rotateAbort() {
- if ( gSvgIconActionState != SvgActionStateType.ROTATE ) {
- return;
- }
- endIconAction();
+ if ( gSvgIconActionState != SvgActionStateType.ROTATE ) {
+ return;
+ }
+ endIconAction();
}
function setSvgTransformAttr( element, scale, translate, rotate ) {
let newTransform = `scale(${scale.x} ${scale.y}) translate(${translate.x}, ${translate.y}) rotate(${rotate.angle}, ${rotate.cx}, ${rotate.cy})`;
- $(element).attr('transform', newTransform);
+ $(element).attr('transform', newTransform);
}
function saveIconSvgPositionDebouncer( element ) {
@@ -652,7 +652,7 @@ Original (str): ${transformStr}
clearTimeout( positionApiCallDebounceTimer );
positionApiCallDebounceTimer = setTimeout(() => {
- saveIconSvgPosition( element );
+ saveIconSvgPosition( element );
lastPositionApiCallTime = Date.now();
}, POSITION_API_CALL_DEBOUNCE_MS );
}
@@ -662,17 +662,17 @@ Original (str): ${transformStr}
let transform = $(element).attr('transform');
let { scale, translate, rotate } = Hi.svgUtils.getSvgTransformValues( transform );
- const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
- const center = Hi.svgUtils.getSvgCenterPoint( element, baseSvgElement );
-
- let svgItemId = $(element).attr('id');
- let data = {
- svg_x: center.x,
- svg_y: center.y,
- svg_scale: scale.x,
- svg_rotate: rotate.angle,
- };
- AN.post( `${API_EDIT_LOCATION_ITEM_POSITION_URL}/${svgItemId}`, data );
+ const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
+ const center = Hi.svgUtils.getSvgCenterPoint( element, baseSvgElement );
+
+ let svgItemId = $(element).attr('id');
+ let data = {
+ svg_x: center.x,
+ svg_y: center.y,
+ svg_scale: scale.x,
+ svg_rotate: rotate.angle,
+ };
+ AN.post( `${API_EDIT_LOCATION_ITEM_POSITION_URL}/${svgItemId}`, data );
}
diff --git a/src/hi/static/js/svg-location.js b/src/hi/static/js/svg-location.js
index fda4bb88..7bf9258a 100644
--- a/src/hi/static/js/svg-location.js
+++ b/src/hi/static/js/svg-location.js
@@ -10,44 +10,44 @@
const HiSvgLocation = {
init: function() {
Hi.edit.eventBus.subscribe( Hi.edit.SELECTION_MADE_EVENT_NAME,
- this.clearSelection.bind(this) );
+ this.clearSelection.bind(this) );
+ },
+ handleSinglePointerEventStart: function( singlePointerEvent ) {
+ return _handleSinglePointerEventStart( singlePointerEvent );
+ },
+ handleSinglePointerEventMove: function( singlePointerEvent ) {
+ return _handleSinglePointerEventMove( singlePointerEvent );
+ },
+ handleSinglePointerEventEnd: function( singlePointerEvent ) {
+ return _handleSinglePointerEventEnd( singlePointerEvent );
+ },
+ handleDoublePointerEventStart: function( doublePointerEvent ) {
+ return _handleDoublePointerEventStart( doublePointerEvent );
+ },
+ handleDoublePointerEventMove: function( doublePointerEvent ) {
+ return _handleDoublePointerEventMove( doublePointerEvent );
+ },
+ handleDoublePointerEventEnd: function( doublePointerEvent ) {
+ return _handleDoublePointerEventEnd( doublePointerEvent );
+ },
+ handleLastPointerLocation: function( x, y ) {
+ _handleLastPointerLocation( x, y );
+ },
+ handleMouseWheel: function( event ) {
+ return _handleMouseWheel( event );
+ },
+ handleClick: function( event ) {
+ return _handleClick( event );
+ },
+ handleKeyDown: function( event ) {
+ return _handleKeyDown( event );
},
- handleSinglePointerEventStart: function( singlePointerEvent ) {
- return _handleSinglePointerEventStart( singlePointerEvent );
- },
- handleSinglePointerEventMove: function( singlePointerEvent ) {
- return _handleSinglePointerEventMove( singlePointerEvent );
- },
- handleSinglePointerEventEnd: function( singlePointerEvent ) {
- return _handleSinglePointerEventEnd( singlePointerEvent );
- },
- handleDoublePointerEventStart: function( doublePointerEvent ) {
- return _handleDoublePointerEventStart( doublePointerEvent );
- },
- handleDoublePointerEventMove: function( doublePointerEvent ) {
- return _handleDoublePointerEventMove( doublePointerEvent );
- },
- handleDoublePointerEventEnd: function( doublePointerEvent ) {
- return _handleDoublePointerEventEnd( doublePointerEvent );
- },
- handleLastPointerLocation: function( x, y ) {
- _handleLastPointerLocation( x, y );
- },
- handleMouseWheel: function( event ) {
- return _handleMouseWheel( event );
- },
- handleClick: function( event ) {
- return _handleClick( event );
- },
- handleKeyDown: function( event ) {
- return _handleKeyDown( event );
- },
clearSelection: function( data ) {
- gCurrentSelectionModule = data.moduleName;
- if ( data.moduleName != MODULE_NAME ) {
- clearSelectedLocationViewSvg();
+ gCurrentSelectionModule = data.moduleName;
+ if ( data.moduleName != MODULE_NAME ) {
+ clearSelectedLocationViewSvg();
}
- }
+ }
};
window.Hi.location = HiSvgLocation;
@@ -75,12 +75,12 @@
const ZOOM_API_CALL_DEBOUNCE_MS = 400;
const LOCATION_VIEW_EDIT_PANE_SELECTOR = '#hi-location-view-edit';
- const API_EDIT_LOCATION_VIEW_GEOMETRY_URL = '/location/edit/location-view/geometry';
+ const API_EDIT_LOCATION_VIEW_GEOMETRY_URL = '/location/edit/view/geometry';
const SvgTransformType = {
- MOVE: 'move',
- SCALE: 'scale',
- ROTATE: 'rotate'
+ MOVE: 'move',
+ SCALE: 'scale',
+ ROTATE: 'rotate'
};
let gSvgTransformType = SvgTransformType.MOVE;
@@ -93,604 +93,604 @@
let lastZoomApiCallTime = 0;
function _handleSinglePointerEventStart( singlePointerEvent ) {
- const event = singlePointerEvent.start.event;
-
- if ( gSelectedLocationViewSvg ) {
- if ( Hi.DEBUG ) { console.log( `Pointer down event [${MODULE_NAME}]`, event ); }
- createTransformData( event, gSelectedLocationViewSvg );
- return true;
-
- } else if ( gCurrentSelectionModule != 'svg-path' ) {
- const closest = $(event.target).closest( Hi.LOCATION_VIEW_SVG_SELECTOR );
- if ( closest.length > 0 ) {
- if ( Hi.DEBUG ) { console.log( `Pointer down event [${MODULE_NAME}]`, event ); }
- gSelectedLocationViewSvg = closest[0];
- createTransformData( event, gSelectedLocationViewSvg );
- return true;
- }
- }
-
- if ( Hi.DEBUG ) { console.log( `Pointer down skipped: [${MODULE_NAME}]` ); }
- return false;
+ const event = singlePointerEvent.start.event;
+
+ if ( gSelectedLocationViewSvg ) {
+ if ( Hi.DEBUG ) { console.log( `Pointer down event [${MODULE_NAME}]`, event ); }
+ createTransformData( event, gSelectedLocationViewSvg );
+ return true;
+
+ } else if ( gCurrentSelectionModule != 'svg-path' ) {
+ const closest = $(event.target).closest( Hi.LOCATION_VIEW_SVG_SELECTOR );
+ if ( closest.length > 0 ) {
+ if ( Hi.DEBUG ) { console.log( `Pointer down event [${MODULE_NAME}]`, event ); }
+ gSelectedLocationViewSvg = closest[0];
+ createTransformData( event, gSelectedLocationViewSvg );
+ return true;
+ }
+ }
+
+ if ( Hi.DEBUG ) { console.log( `Pointer down skipped: [${MODULE_NAME}]` ); }
+ return false;
}
function _handleSinglePointerEventMove( singlePointerEvent ) {
- const event = singlePointerEvent.last.event;
-
- const currentPointPosition = {
- x: event.clientX,
- y: event.clientY
- };
- if ( gSvgTransformData ) {
-
- gSvgTransformData.isDragging = true;
- if ( gSvgTransformType == SvgTransformType.SCALE ) {
- updateScaleFromPointerMove( event );
- } else if( gSvgTransformType == SvgTransformType.ROTATE ) {
- updateRotationFromPointerMove( singlePointerEvent );
- } else {
- updateDragFromPointerMove( singlePointerEvent );
- }
- gSvgTransformData.last = currentPointPosition;
- return true;
- }
- return false;
+ const event = singlePointerEvent.last.event;
+
+ const currentPointPosition = {
+ x: event.clientX,
+ y: event.clientY
+ };
+ if ( gSvgTransformData ) {
+
+ gSvgTransformData.isDragging = true;
+ if ( gSvgTransformType == SvgTransformType.SCALE ) {
+ updateScaleFromPointerMove( event );
+ } else if( gSvgTransformType == SvgTransformType.ROTATE ) {
+ updateRotationFromPointerMove( singlePointerEvent );
+ } else {
+ updateDragFromPointerMove( singlePointerEvent );
+ }
+ gSvgTransformData.last = currentPointPosition;
+ return true;
+ }
+ return false;
}
function _handleSinglePointerEventEnd( singlePointerEvent ) {
- const event = singlePointerEvent.last.event;
+ const event = singlePointerEvent.last.event;
- let eventWasHandled = false;
- if ( gSvgTransformData ) {
- if ( gSvgTransformType == SvgTransformType.SCALE ) {
- endScale();
- eventWasHandled = true;
+ let eventWasHandled = false;
+ if ( gSvgTransformData ) {
+ if ( gSvgTransformType == SvgTransformType.SCALE ) {
+ endScale();
+ eventWasHandled = true;
- } else if( gSvgTransformType == SvgTransformType.ROTATE ) {
- endRotation();
- eventWasHandled = true;
+ } else if( gSvgTransformType == SvgTransformType.ROTATE ) {
+ endRotation();
+ eventWasHandled = true;
- } else if (( gSvgTransformType == SvgTransformType.MOVE ) && gSvgTransformData.isDragging ) {
- endDrag( event );
- eventWasHandled = true;
- }
- }
-
- if ( eventWasHandled ) {
- if ( Hi.DEBUG ) { console.log( `Pointer end: [${MODULE_NAME}]`, event ); }
- clearTransformData();
- gIgnoreCLick = true;
-
- } else {
- if ( Hi.DEBUG ) { console.log( `Pointer env skipped: [${MODULE_NAME}]` ); }
- }
- return eventWasHandled;
+ } else if (( gSvgTransformType == SvgTransformType.MOVE ) && gSvgTransformData.isDragging ) {
+ endDrag( event );
+ eventWasHandled = true;
+ }
+ }
+
+ if ( eventWasHandled ) {
+ if ( Hi.DEBUG ) { console.log( `Pointer end: [${MODULE_NAME}]`, event ); }
+ clearTransformData();
+ gIgnoreCLick = true;
+
+ } else {
+ if ( Hi.DEBUG ) { console.log( `Pointer env skipped: [${MODULE_NAME}]` ); }
+ }
+ return eventWasHandled;
}
function _handleDoublePointerEventStart( doublePointerEvent ) {
- const event = doublePointerEvent.start.event;
- const closest = $(event.target).closest( Hi.LOCATION_VIEW_SVG_SELECTOR );
- if ( closest.length > 0 ) {
- gSelectedLocationViewSvg = closest[0];
- createTransformData( event, gSelectedLocationViewSvg );
- return true;
- }
- return false;
+ const event = doublePointerEvent.start.event;
+ const closest = $(event.target).closest( Hi.LOCATION_VIEW_SVG_SELECTOR );
+ if ( closest.length > 0 ) {
+ gSelectedLocationViewSvg = closest[0];
+ createTransformData( event, gSelectedLocationViewSvg );
+ return true;
+ }
+ return false;
}
function _handleDoublePointerEventMove( doublePointerEvent ) {
- if ( ! gSvgTransformData ) {
- return false;
- }
- let scaleFactor = ( 1.0 - ( doublePointerEvent.deltaDistancePrevious
- / DOUBLE_POINTER_EVENTS_SCALE_FACTOR ));
- let deltaAngle = doublePointerEvent.deltaAnglePrevious * DOUBLE_POINTER_EVENTS_ROTATE_FACTOR;
- zoom( scaleFactor );
- rotate( deltaAngle );
- return true;
+ if ( ! gSvgTransformData ) {
+ return false;
+ }
+ let scaleFactor = ( 1.0 - ( doublePointerEvent.deltaDistancePrevious
+ / DOUBLE_POINTER_EVENTS_SCALE_FACTOR ));
+ let deltaAngle = doublePointerEvent.deltaAnglePrevious * DOUBLE_POINTER_EVENTS_ROTATE_FACTOR;
+ zoom( scaleFactor );
+ rotate( deltaAngle );
+ return true;
}
function _handleDoublePointerEventEnd( doublePointerEvent ) {
- if ( ! gSvgTransformData ) {
- return false;
- }
- saveSvgGeometryDebouncer();
- abortScale();
- abortRotation();
- return true;
+ if ( ! gSvgTransformData ) {
+ return false;
+ }
+ saveSvgGeometryDebouncer();
+ abortScale();
+ abortRotation();
+ return true;
}
function _handleLastPointerLocation( x, y ) {
- gLastPointerPosition.x = x;
- gLastPointerPosition.y = y;
+ gLastPointerPosition.x = x;
+ gLastPointerPosition.y = y;
}
function _handleMouseWheel( event ) {
- if ( gSelectedLocationViewSvg && isEventInLocationArea( event )) {
- if ( gSvgTransformType == SvgTransformType.ROTATE ) {
- rotateFromMouseWheel( event );
-
- } else {
- abortScale();
- abortRotation();
- zoomFromMouseWheel( event );
- }
- event.preventDefault();
- event.stopImmediatePropagation();
- return true;
- }
- return false;
+ if ( gSelectedLocationViewSvg && isEventInLocationArea( event )) {
+ if ( gSvgTransformType == SvgTransformType.ROTATE ) {
+ rotateFromMouseWheel( event );
+
+ } else {
+ abortScale();
+ abortRotation();
+ zoomFromMouseWheel( event );
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+ }
+ return false;
}
function _handleClick( event ) {
- if ( gIgnoreCLick ) {
- if ( Hi.DEBUG ) { console.log( `Ignoring click [${MODULE_NAME}]`, event ); }
- gIgnoreCLick = false;
- return true;
- }
-
- if ( $(event.target).closest( Hi.LOCATION_VIEW_BASE_SELECTOR ).length > 0 ) {
- const closest = $(event.target).closest( Hi.LOCATION_VIEW_SVG_SELECTOR );
- if ( closest.length > 0 ) {
- if ( Hi.DEBUG ) { console.log( `Click handled: [${MODULE_NAME}]`, event ); }
- gSelectedLocationViewSvg = closest[0];
- clearTransformData();
- let data = {
- moduleName: MODULE_NAME,
- };
- Hi.edit.eventBus.emit( Hi.edit.SELECTION_MADE_EVENT_NAME, data );
- return true;
- }
- }
- if ( Hi.DEBUG ) { console.log( `Click skipped [${MODULE_NAME}]` ); }
- return false;
+ if ( gIgnoreCLick ) {
+ if ( Hi.DEBUG ) { console.log( `Ignoring click [${MODULE_NAME}]`, event ); }
+ gIgnoreCLick = false;
+ return true;
+ }
+
+ if ( $(event.target).closest( Hi.LOCATION_VIEW_BASE_SELECTOR ).length > 0 ) {
+ const closest = $(event.target).closest( Hi.LOCATION_VIEW_SVG_SELECTOR );
+ if ( closest.length > 0 ) {
+ if ( Hi.DEBUG ) { console.log( `Click handled: [${MODULE_NAME}]`, event ); }
+ gSelectedLocationViewSvg = closest[0];
+ clearTransformData();
+ let data = {
+ moduleName: MODULE_NAME,
+ };
+ Hi.edit.eventBus.emit( Hi.edit.SELECTION_MADE_EVENT_NAME, data );
+ return true;
+ }
+ }
+ if ( Hi.DEBUG ) { console.log( `Click skipped [${MODULE_NAME}]` ); }
+ return false;
}
function _handleKeyDown( event ) {
- if ( $(event.target).is('input, textarea') ) {
+ if ( $(event.target).is('input, textarea') ) {
return false;
- }
- if ($(event.target).closest('.modal').length > 0) {
+ }
+ if ($(event.target).closest('.modal').length > 0) {
return false;
- }
- if ( gSelectedLocationViewSvg ) {
+ }
+ if ( gSelectedLocationViewSvg ) {
- const targetArea = $(Hi.LOCATION_VIEW_AREA_SELECTOR);
+ const targetArea = $(Hi.LOCATION_VIEW_AREA_SELECTOR);
const targetOffset = targetArea.offset();
const targetWidth = targetArea.outerWidth();
const targetHeight = targetArea.outerHeight();
if (( gLastPointerPosition.x >= targetOffset.left )
- && ( gLastPointerPosition.x <= ( targetOffset.left + targetWidth ))
- && ( gLastPointerPosition.y >= targetOffset.top )
- && ( gLastPointerPosition.y <= ( targetOffset.top + targetHeight ))) {
-
- if ( Hi.DEBUG ) { console.log( `Key Down [${MODULE_NAME}]`, event ); }
-
- if ( event.key == SVG_TRANSFORM_ACTION_SCALE_KEY ) {
- abortRotation();
- startScale();
-
- } else if ( event.key == SVG_TRANSFORM_ACTION_ROTATE_KEY ) {
- abortScale();
- startRotation();
-
- } else if ( event.key == SVG_TRANSFORM_ACTION_INCREASE_KEY ) {
-
- if ( gSvgTransformType === SvgTransformType.ROTATE ) {
- rotateRightFromKeypress( event );
- } else {
- zoomInFromKeypress( event );
- }
-
- } else if ( event.key == SVG_TRANSFORM_ACTION_DECREASE_KEY ) {
- if ( gSvgTransformType === SvgTransformType.ROTATE ) {
- rotateLeftFromKeypress( event );
- } else {
- zoomOutFromKeypress( event );
- }
-
- } else if ( event.key == 'Escape' ) {
- abortScale();
- abortRotation();
- }
- }
- event.preventDefault();
- event.stopImmediatePropagation();
- return true;
- }
- if ( Hi.DEBUG ) { console.log( `Key down skipped [${MODULE_NAME}]` ); }
- return false;
+ && ( gLastPointerPosition.x <= ( targetOffset.left + targetWidth ))
+ && ( gLastPointerPosition.y >= targetOffset.top )
+ && ( gLastPointerPosition.y <= ( targetOffset.top + targetHeight ))) {
+
+ if ( Hi.DEBUG ) { console.log( `Key Down [${MODULE_NAME}]`, event ); }
+
+ if ( event.key == SVG_TRANSFORM_ACTION_SCALE_KEY ) {
+ abortRotation();
+ startScale();
+
+ } else if ( event.key == SVG_TRANSFORM_ACTION_ROTATE_KEY ) {
+ abortScale();
+ startRotation();
+
+ } else if ( event.key == SVG_TRANSFORM_ACTION_INCREASE_KEY ) {
+
+ if ( gSvgTransformType === SvgTransformType.ROTATE ) {
+ rotateRightFromKeypress( event );
+ } else {
+ zoomInFromKeypress( event );
+ }
+
+ } else if ( event.key == SVG_TRANSFORM_ACTION_DECREASE_KEY ) {
+ if ( gSvgTransformType === SvgTransformType.ROTATE ) {
+ rotateLeftFromKeypress( event );
+ } else {
+ zoomOutFromKeypress( event );
+ }
+
+ } else if ( event.key == 'Escape' ) {
+ abortScale();
+ abortRotation();
+ }
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+ }
+ if ( Hi.DEBUG ) { console.log( `Key down skipped [${MODULE_NAME}]` ); }
+ return false;
}
function isEventInLocationArea( event ) {
- if ( $(event.target).is('input, textarea') ) {
+ if ( $(event.target).is('input, textarea') ) {
return false;
- }
- if ($(event.target).closest('.modal').length > 0) {
+ }
+ if ($(event.target).closest('.modal').length > 0) {
return false;
- }
- return $(event.target).closest(Hi.LOCATION_VIEW_AREA_SELECTOR).length > 0;
+ }
+ return $(event.target).closest(Hi.LOCATION_VIEW_AREA_SELECTOR).length > 0;
}
- function createTransformData( event, locationViewSvg ) {
-
- let svgViewBox = Hi.svgUtils.getSvgViewBox( locationViewSvg );
+ function createTransformData( event, locationViewSvg ) {
+
+ let svgViewBox = Hi.svgUtils.getSvgViewBox( locationViewSvg );
let transform = $(locationViewSvg).attr('transform') || '';
let { scale, translate, rotate } = Hi.svgUtils.getSvgTransformValues( transform );
- let startX = event.clientX;
- let startY = event.clientY;
-
- gSvgTransformData = {
- isDragging: false,
- start: {
- x: startX,
- y: startY,
- scale: scale,
- rotate: rotate,
- viewBox: svgViewBox
- },
- last: {
- x: startX,
- y: startY,
- }
- };
- }
-
- function clearTransformData() {
- gSvgTransformData = null;
- gSvgTransformType = SvgTransformType.MOVE;
+ let startX = event.clientX;
+ let startY = event.clientY;
+
+ gSvgTransformData = {
+ isDragging: false,
+ start: {
+ x: startX,
+ y: startY,
+ scale: scale,
+ rotate: rotate,
+ viewBox: svgViewBox
+ },
+ last: {
+ x: startX,
+ y: startY,
+ }
+ };
+ }
+
+ function clearTransformData() {
+ gSvgTransformData = null;
+ gSvgTransformType = SvgTransformType.MOVE;
}
function clearSelectedLocationViewSvg() {
- if ( gSelectedLocationViewSvg ) {
+ if ( gSelectedLocationViewSvg ) {
if ( Hi.DEBUG ) { console.log('Clearing location view svg transform data'); }
- gSelectedLocationViewSvg = null;
- clearTransformData();
- }
+ gSelectedLocationViewSvg = null;
+ clearTransformData();
+ }
}
function startDrag( event ) {
}
function updateDragFromPointerMove( singlePointerEvent ) {
- if ( Hi.DEBUG ) { console.log( `updateDragFromPointerMove [${MODULE_NAME}]` ); }
- if ( ! gSelectedLocationViewSvg || ( gSvgTransformData == null )) {
- return;
- }
-
- let pixelsPerSvgUnit = Hi.svgUtils.getPixelsPerSvgUnit( gSelectedLocationViewSvg );
+ if ( Hi.DEBUG ) { console.log( `updateDragFromPointerMove [${MODULE_NAME}]` ); }
+ if ( ! gSelectedLocationViewSvg || ( gSvgTransformData == null )) {
+ return;
+ }
+
+ let pixelsPerSvgUnit = Hi.svgUtils.getPixelsPerSvgUnit( gSelectedLocationViewSvg );
let deltaSvgUnits = {
- x: ( singlePointerEvent.last.x - singlePointerEvent.start.x ) / pixelsPerSvgUnit.scaleX,
- y: ( singlePointerEvent.last.y - singlePointerEvent.start.y ) / pixelsPerSvgUnit.scaleX
- };
+ x: ( singlePointerEvent.last.x - singlePointerEvent.start.x ) / pixelsPerSvgUnit.scaleX,
+ y: ( singlePointerEvent.last.y - singlePointerEvent.start.y ) / pixelsPerSvgUnit.scaleX
+ };
- let transform = $(gSelectedLocationViewSvg).attr('transform');
+ let transform = $(gSelectedLocationViewSvg).attr('transform');
let { scale, translate, rotate } = Hi.svgUtils.getSvgTransformValues( transform );
- deltaSvgUnits = rotateVector( deltaSvgUnits, -1.0 * rotate.angle );
-
- let newX = gSvgTransformData.start.viewBox.x - deltaSvgUnits.x;
- let newY = gSvgTransformData.start.viewBox.y - deltaSvgUnits.y;
+ deltaSvgUnits = rotateVector( deltaSvgUnits, -1.0 * rotate.angle );
+
+ let newX = gSvgTransformData.start.viewBox.x - deltaSvgUnits.x;
+ let newY = gSvgTransformData.start.viewBox.y - deltaSvgUnits.y;
- adjustSvgViewBox( gSvgTransformData.start.viewBox,
- gSvgTransformData.start.viewBox.width,
- gSvgTransformData.start.viewBox.height,
- newX,
- newY );
+ adjustSvgViewBox( gSvgTransformData.start.viewBox,
+ gSvgTransformData.start.viewBox.width,
+ gSvgTransformData.start.viewBox.height,
+ newX,
+ newY );
- return;
+ return;
}
function endDrag( event ) {
- if ( Hi.DEBUG ) { console.log( `endDrag [${MODULE_NAME}]` ); }
- if ( gSvgTransformData && gSvgTransformData.isDragging ) {
- saveSvgGeometryDebouncer();
- }
- gSvgTransformData.isDragging = false;
+ if ( Hi.DEBUG ) { console.log( `endDrag [${MODULE_NAME}]` ); }
+ if ( gSvgTransformData && gSvgTransformData.isDragging ) {
+ saveSvgGeometryDebouncer();
+ }
+ gSvgTransformData.isDragging = false;
}
function zoomInFromKeypress( event ) {
- let scaleFactor = 1.0 / ( 1.0 + ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 ));
- zoom( scaleFactor );
- saveSvgGeometryDebouncer();
+ let scaleFactor = 1.0 / ( 1.0 + ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 ));
+ zoom( scaleFactor );
+ saveSvgGeometryDebouncer();
}
function zoomOutFromKeypress( event ) {
- let scaleFactor = 1.0 + ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
- zoom( scaleFactor );
- saveSvgGeometryDebouncer();
+ let scaleFactor = 1.0 + ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
+ zoom( scaleFactor );
+ saveSvgGeometryDebouncer();
}
function zoomFromMouseWheel( event ) {
- const e = event.originalEvent;
+ const e = event.originalEvent;
// Immediately update the visual
- let scaleFactor = 1.0 - ( MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
+ let scaleFactor = 1.0 - ( MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
if ( e.deltaY > 0 ) {
- scaleFactor = 1.0 + ( MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
+ scaleFactor = 1.0 + ( MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
}
- zoom( scaleFactor );
- saveSvgGeometryDebouncer();
+ zoom( scaleFactor );
+ saveSvgGeometryDebouncer();
}
function zoom( scaleFactor ) {
- let initialSvgViewBox = Hi.svgUtils.getSvgViewBox( gSelectedLocationViewSvg );
- scaleSvgViewBox( initialSvgViewBox, scaleFactor );
+ let initialSvgViewBox = Hi.svgUtils.getSvgViewBox( gSelectedLocationViewSvg );
+ scaleSvgViewBox( initialSvgViewBox, scaleFactor );
}
function startScale( event ) {
- if ( Hi.DEBUG ) { console.log( `startScale [${MODULE_NAME}]` ); }
- gSvgTransformType = SvgTransformType.SCALE;
- $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, gSvgTransformType );
+ if ( Hi.DEBUG ) { console.log( `startScale [${MODULE_NAME}]` ); }
+ gSvgTransformType = SvgTransformType.SCALE;
+ $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, gSvgTransformType );
}
function updateScaleFromPointerMove( event ) {
- if ( Hi.DEBUG ) { console.log( `updateScale [${MODULE_NAME}]` ); }
+ if ( Hi.DEBUG ) { console.log( `updateScale [${MODULE_NAME}]` ); }
- if ( gSvgTransformData == null ) {
- return;
- }
+ if ( gSvgTransformData == null ) {
+ return;
+ }
- let screenCenter = Hi.getScreenCenterPoint( gSelectedLocationViewSvg );
- const startVector = {
- x: gSvgTransformData.start.x- screenCenter.x,
- y: gSvgTransformData.start.y - screenCenter.y
- };
- const endVector = {
- x: event.clientX - screenCenter.x,
- y: event.clientY - screenCenter.y
- };
- const startVectorLength = Math.sqrt( ( startVector.x * startVector.x )
- + ( startVector.y * startVector.y ));
- const endVectorLength = Math.sqrt( ( endVector.x * endVector.x )
- + ( endVector.y * endVector.y ));
- const vectorLengthDelta = endVectorLength - startVectorLength;
+ let screenCenter = Hi.getScreenCenterPoint( gSelectedLocationViewSvg );
+ const startVector = {
+ x: gSvgTransformData.start.x- screenCenter.x,
+ y: gSvgTransformData.start.y - screenCenter.y
+ };
+ const endVector = {
+ x: event.clientX - screenCenter.x,
+ y: event.clientY - screenCenter.y
+ };
+ const startVectorLength = Math.sqrt( ( startVector.x * startVector.x )
+ + ( startVector.y * startVector.y ));
+ const endVectorLength = Math.sqrt( ( endVector.x * endVector.x )
+ + ( endVector.y * endVector.y ));
+ const vectorLengthDelta = endVectorLength - startVectorLength;
- let scaleFactor = ( 1.0 - ( vectorLengthDelta / SINGLE_POINTER_EVENTS_SCALE_FACTOR ));
+ let scaleFactor = ( 1.0 - ( vectorLengthDelta / SINGLE_POINTER_EVENTS_SCALE_FACTOR ));
- scaleSvgViewBox( gSvgTransformData.start.viewBox, scaleFactor );
+ scaleSvgViewBox( gSvgTransformData.start.viewBox, scaleFactor );
}
function endScale() {
- if ( Hi.DEBUG ) { console.log( `endScale [${MODULE_NAME}]` ); }
- gSvgTransformType = SvgTransformType.MOVE;
- $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '' );
- saveSvgGeometryDebouncer();
+ if ( Hi.DEBUG ) { console.log( `endScale [${MODULE_NAME}]` ); }
+ gSvgTransformType = SvgTransformType.MOVE;
+ $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '' );
+ saveSvgGeometryDebouncer();
}
function abortScale() {
- if ( Hi.DEBUG ) { console.log( `abortScale [${MODULE_NAME}]` ); }
- clearTransformData();
- $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '' );
+ if ( Hi.DEBUG ) { console.log( `abortScale [${MODULE_NAME}]` ); }
+ clearTransformData();
+ $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '' );
}
function scaleSvgViewBox( initialSvgViewBox, scaleFactor ) {
- let newWidth = scaleFactor * initialSvgViewBox.width;
- let newHeight = scaleFactor * initialSvgViewBox.height;
- adjustSvgViewBox( initialSvgViewBox, newWidth, newHeight );
- return;
+ let newWidth = scaleFactor * initialSvgViewBox.width;
+ let newHeight = scaleFactor * initialSvgViewBox.height;
+ adjustSvgViewBox( initialSvgViewBox, newWidth, newHeight );
+ return;
}
function startRotation( event ) {
- if ( Hi.DEBUG ) { console.log( `startRotation [${MODULE_NAME}]` ); }
- gSvgTransformType = SvgTransformType.ROTATE;
- $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, gSvgTransformType );
+ if ( Hi.DEBUG ) { console.log( `startRotation [${MODULE_NAME}]` ); }
+ gSvgTransformType = SvgTransformType.ROTATE;
+ $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, gSvgTransformType );
}
function updateRotationFromPointerMove( singlePointerEvent ) {
- if ( Hi.DEBUG ) { console.log( `updateRotationFromPointerMove [${MODULE_NAME}]` ); }
+ if ( Hi.DEBUG ) { console.log( `updateRotationFromPointerMove [${MODULE_NAME}]` ); }
- let screenCenter = Hi.getScreenCenterPoint( gSelectedLocationViewSvg );
+ let screenCenter = Hi.getScreenCenterPoint( gSelectedLocationViewSvg );
- let deltaAngle = Hi.getRotationAngle( screenCenter.x, screenCenter.y,
- singlePointerEvent.previous.x, singlePointerEvent.previous.y,
- singlePointerEvent.last.x, singlePointerEvent.last.y );
+ let deltaAngle = Hi.getRotationAngle( screenCenter.x, screenCenter.y,
+ singlePointerEvent.previous.x, singlePointerEvent.previous.y,
+ singlePointerEvent.last.x, singlePointerEvent.last.y );
- deltaAngle *= SINGLE_POINTER_EVENTS_ROTATE_FACTOR;
- rotate( deltaAngle );
+ deltaAngle *= SINGLE_POINTER_EVENTS_ROTATE_FACTOR;
+ rotate( deltaAngle );
}
function rotateRightFromKeypress( event ) {
- let deltaAngle = KEYPRESS_ROTATE_DEGREES;
- rotate( deltaAngle );
- saveSvgGeometryDebouncer();
+ let deltaAngle = KEYPRESS_ROTATE_DEGREES;
+ rotate( deltaAngle );
+ saveSvgGeometryDebouncer();
}
function rotateLeftFromKeypress( event ) {
- let deltaAngle = -1.0 * KEYPRESS_ROTATE_DEGREES;
- rotate( deltaAngle );
- saveSvgGeometryDebouncer();
+ let deltaAngle = -1.0 * KEYPRESS_ROTATE_DEGREES;
+ rotate( deltaAngle );
+ saveSvgGeometryDebouncer();
}
function rotateFromMouseWheel( event ) {
- const e = event.originalEvent;
+ const e = event.originalEvent;
// Immediately update the visual
- let deltaAngle = MOUSE_WHEEL_ROTATE_ANGLE;
+ let deltaAngle = MOUSE_WHEEL_ROTATE_ANGLE;
if ( e.deltaY > 0 ) {
- deltaAngle *= -1.0;
+ deltaAngle *= -1.0;
}
- rotate( deltaAngle );
- saveSvgGeometryDebouncer();
+ rotate( deltaAngle );
+ saveSvgGeometryDebouncer();
}
function rotate( deltaAngle ) {
-
+
let transform = $(gSelectedLocationViewSvg).attr('transform');
let { scale, translate, rotate } = Hi.svgUtils.getSvgTransformValues( transform );
- rotate.angle = rotate.angle + deltaAngle;
- rotate.angle = Hi.normalizeAngle( rotate.angle );
- let newTransform = `rotate(${rotate.angle}, ${rotate.cx}, ${rotate.cy})`;
+ rotate.angle = rotate.angle + deltaAngle;
+ rotate.angle = Hi.normalizeAngle( rotate.angle );
+ let newTransform = `rotate(${rotate.angle}, ${rotate.cx}, ${rotate.cy})`;
$(gSelectedLocationViewSvg).attr( 'transform', newTransform );
- // Some browser-device combinations have rendering bugs with the
- // transform property, but not the CSS versions.
+ // Some browser-device combinations have rendering bugs with the
+ // transform property, but not the CSS versions.
gSelectedLocationViewSvg.style.transform = `rotate( ${rotate.angle}deg )`;
}
function endRotation( ) {
- if ( Hi.DEBUG ) { console.log( `endRotation [${MODULE_NAME}]` ); }
- gSvgTransformType = SvgTransformType.MOVE;
- $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '' );
- saveSvgGeometryDebouncer();
+ if ( Hi.DEBUG ) { console.log( `endRotation [${MODULE_NAME}]` ); }
+ gSvgTransformType = SvgTransformType.MOVE;
+ $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '' );
+ saveSvgGeometryDebouncer();
}
function abortRotation( ) {
- if ( Hi.DEBUG ) { console.log( `abortRotation [${MODULE_NAME}]` ); }
- clearTransformData();
- $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '' );
+ if ( Hi.DEBUG ) { console.log( `abortRotation [${MODULE_NAME}]` ); }
+ clearTransformData();
+ $(gSelectedLocationViewSvg).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, '' );
}
function adjustSvgViewBox( initialSvgViewBox, newWidth, newHeight, newX = null, newY = null ) {
- // Need to account for possible SVG rotation
+ // Need to account for possible SVG rotation
let transform = $(gSelectedLocationViewSvg).attr('transform');
let { scale, translate, rotate } = Hi.svgUtils.getSvgTransformValues( transform );
- // Adjust the dimensions to fill as much as the screen as possible
- let containerRect = $(Hi.LOCATION_VIEW_AREA_SELECTOR)[0].getBoundingClientRect();
- let containerAspectRatio = containerRect.width / containerRect.height;
- let newAspectRatio = newWidth / newHeight;
-
- if ( newAspectRatio > containerAspectRatio ) {
- newHeight = newWidth / containerAspectRatio;
- } else if ( newAspectRatio < containerAspectRatio ) {
- newWidth = newHeight * containerAspectRatio;
- }
-
- // Ensure the new viewBox is clamped within the extents of the SVG
- let extentsSvgViewBox = Hi.svgUtils.getExtentsSvgViewBox( gSelectedLocationViewSvg );
-
- extentsSvgViewBox = calculateRotatedRectangle( extentsSvgViewBox, rotate.angle );
-
- newWidth = Math.min( newWidth, extentsSvgViewBox.width );
- newHeight = Math.min( newHeight, extentsSvgViewBox.height );
-
- // Center the new viewBox within the initial viewBox (if no explicit newX/newY)
- if ( ! newX ) {
- newX = initialSvgViewBox.x + ( initialSvgViewBox.width - newWidth ) / 2.0;
- }
- if ( ! newY ) {
- newY = initialSvgViewBox.y + ( initialSvgViewBox.height - newHeight ) / 2.0;
- }
-
- if (newX < extentsSvgViewBox.x) {
+ // Adjust the dimensions to fill as much as the screen as possible
+ let containerRect = $(Hi.LOCATION_VIEW_AREA_SELECTOR)[0].getBoundingClientRect();
+ let containerAspectRatio = containerRect.width / containerRect.height;
+ let newAspectRatio = newWidth / newHeight;
+
+ if ( newAspectRatio > containerAspectRatio ) {
+ newHeight = newWidth / containerAspectRatio;
+ } else if ( newAspectRatio < containerAspectRatio ) {
+ newWidth = newHeight * containerAspectRatio;
+ }
+
+ // Ensure the new viewBox is clamped within the extents of the SVG
+ let extentsSvgViewBox = Hi.svgUtils.getExtentsSvgViewBox( gSelectedLocationViewSvg );
+
+ extentsSvgViewBox = calculateRotatedRectangle( extentsSvgViewBox, rotate.angle );
+
+ newWidth = Math.min( newWidth, extentsSvgViewBox.width );
+ newHeight = Math.min( newHeight, extentsSvgViewBox.height );
+
+ // Center the new viewBox within the initial viewBox (if no explicit newX/newY)
+ if ( ! newX ) {
+ newX = initialSvgViewBox.x + ( initialSvgViewBox.width - newWidth ) / 2.0;
+ }
+ if ( ! newY ) {
+ newY = initialSvgViewBox.y + ( initialSvgViewBox.height - newHeight ) / 2.0;
+ }
+
+ if (newX < extentsSvgViewBox.x) {
newX = extentsSvgViewBox.x;
- }
- if (newY < extentsSvgViewBox.y) {
+ }
+ if (newY < extentsSvgViewBox.y) {
newY = extentsSvgViewBox.y;
- }
- if (( newX + newWidth ) > ( extentsSvgViewBox.x + extentsSvgViewBox.width )) {
+ }
+ if (( newX + newWidth ) > ( extentsSvgViewBox.x + extentsSvgViewBox.width )) {
newX = extentsSvgViewBox.x + extentsSvgViewBox.width - newWidth;
- }
- if (( newY + newHeight ) > ( extentsSvgViewBox.y + extentsSvgViewBox.height )) {
+ }
+ if (( newY + newHeight ) > ( extentsSvgViewBox.y + extentsSvgViewBox.height )) {
newY = extentsSvgViewBox.y + extentsSvgViewBox.height - newHeight;
- }
+ }
- Hi.svgUtils.setSvgViewBox( gSelectedLocationViewSvg, newX, newY, newWidth, newHeight );
+ Hi.svgUtils.setSvgViewBox( gSelectedLocationViewSvg, newX, newY, newWidth, newHeight );
}
function calculateRotatedRectangle( initialRect, rotationAngle ) {
- let corners = [
+ let corners = [
{ x: initialRect.x, y: initialRect.y },
{ x: initialRect.x + initialRect.width, y: initialRect.y },
{ x: initialRect.x, y: initialRect.y + initialRect.height },
{ x: initialRect.x + initialRect.width, y: initialRect.y + initialRect.height }
- ];
-
- // Rotate the corners around the center of the viewBox
- let centerX = initialRect.x + ( initialRect.width / 2.0 );
- let centerY = initialRect.y + ( initialRect.height / 2.0 );
- let radians = (Math.PI / 180) * rotationAngle;
-
- let rotatedCorners = corners.map((corner) => {
+ ];
+
+ // Rotate the corners around the center of the viewBox
+ let centerX = initialRect.x + ( initialRect.width / 2.0 );
+ let centerY = initialRect.y + ( initialRect.height / 2.0 );
+ let radians = (Math.PI / 180) * rotationAngle;
+
+ let rotatedCorners = corners.map((corner) => {
let dx = corner.x - centerX;
let dy = corner.y - centerY;
return {
- x: centerX + (dx * Math.cos(radians) - dy * Math.sin(radians)),
- y: centerY + (dx * Math.sin(radians) + dy * Math.cos(radians)),
+ x: centerX + (dx * Math.cos(radians) - dy * Math.sin(radians)),
+ y: centerY + (dx * Math.sin(radians) + dy * Math.cos(radians)),
};
- });
-
- // Calculate the new bounding box from the rotated corners
- let minX = Math.min(...rotatedCorners.map(c => c.x));
- let minY = Math.min(...rotatedCorners.map(c => c.y));
- let maxX = Math.max(...rotatedCorners.map(c => c.x));
- let maxY = Math.max(...rotatedCorners.map(c => c.y));
-
- return {
+ });
+
+ // Calculate the new bounding box from the rotated corners
+ let minX = Math.min(...rotatedCorners.map(c => c.x));
+ let minY = Math.min(...rotatedCorners.map(c => c.y));
+ let maxX = Math.max(...rotatedCorners.map(c => c.x));
+ let maxY = Math.max(...rotatedCorners.map(c => c.y));
+
+ return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY,
- };
+ };
}
function rotateVector( point, rotationAngle ) {
- let radians = (Math.PI / 180) * rotationAngle;
- let newX = point.x * Math.cos(radians) - point.y * Math.sin(radians);
- let newY = point.x * Math.sin(radians) + point.y * Math.cos(radians);
- return { x: newX, y: newY };
+ let radians = (Math.PI / 180) * rotationAngle;
+ let newX = point.x * Math.cos(radians) - point.y * Math.sin(radians);
+ let newY = point.x * Math.sin(radians) + point.y * Math.cos(radians);
+ return { x: newX, y: newY };
}
function saveSvgGeometryDebouncer() {
- if ( ! shouldSaveGeometry() ) {
- return;
- }
+ if ( ! shouldSaveGeometry() ) {
+ return;
+ }
const currentTime = Date.now();
const timeSinceLastApiCall = currentTime - lastZoomApiCallTime;
clearTimeout( zoomApiCallDebounceTimer );
zoomApiCallDebounceTimer = setTimeout(() => {
- saveSvgGeometryIfNeeded();
+ saveSvgGeometryIfNeeded();
lastZoomApiCallTime = Date.now();
}, ZOOM_API_CALL_DEBOUNCE_MS );
}
function saveSvgGeometryIfNeeded( ) {
- if ( ! shouldSaveGeometry() ) {
- return;
- }
- if ( Hi.DEBUG ) { console.log( `Saving SVG geometry [${MODULE_NAME}]` ); }
+ if ( ! shouldSaveGeometry() ) {
+ return;
+ }
+ if ( Hi.DEBUG ) { console.log( `Saving SVG geometry [${MODULE_NAME}]` ); }
- let locationViewId = $(gSelectedLocationViewSvg).attr('location-view-id');
- let svgViewBoxStr = $(gSelectedLocationViewSvg).attr('viewBox');
+ let locationViewId = $(gSelectedLocationViewSvg).attr('location-view-id');
+ let svgViewBoxStr = $(gSelectedLocationViewSvg).attr('viewBox');
let transform = $(gSelectedLocationViewSvg).attr('transform');
let { scale, translate, rotate } = Hi.svgUtils.getSvgTransformValues( transform );
- let data = {
- svg_view_box_str: svgViewBoxStr,
- svg_rotate: rotate.angle
- };
-
- AN.post( `${API_EDIT_LOCATION_VIEW_GEOMETRY_URL}/${locationViewId}`, data );
+ let data = {
+ svg_view_box_str: svgViewBoxStr,
+ svg_rotate: rotate.angle
+ };
+
+ AN.post( `${API_EDIT_LOCATION_VIEW_GEOMETRY_URL}/${locationViewId}`, data );
}
function shouldSaveGeometry() {
- /* We only save the current location view geometry on a change if
- the Location View editing pane is showing. automatically saving
- the geometry after all move/scale/rotate operations is more
- inconvenient than helpful. While editing, it is often useful to
- manipulate the location view geometry while editing and
- arranging the entities. If these entity refinements happen
- after the the desired geometry has been set, then the act of
- editing those entities and manipulating the location view will
- result in undoing the original geometry work. Further, the user
- only finds this out after they exit editing mode and see that it
- has changed. Thus, we changed to require an explicit the location
- editing view pane to be visible.
- */
- return ( Hi.isEditMode
- && gSelectedLocationViewSvg
- && ( $(LOCATION_VIEW_EDIT_PANE_SELECTOR).length > 0 ));
+ /* We only save the current location view geometry on a change if
+ the Location View editing pane is showing. automatically saving
+ the geometry after all move/scale/rotate operations is more
+ inconvenient than helpful. While editing, it is often useful to
+ manipulate the location view geometry while editing and
+ arranging the entities. If these entity refinements happen
+ after the the desired geometry has been set, then the act of
+ editing those entities and manipulating the location view will
+ result in undoing the original geometry work. Further, the user
+ only finds this out after they exit editing mode and see that it
+ has changed. Thus, we changed to require an explicit the location
+ editing view pane to be visible.
+ */
+ return ( Hi.isEditMode
+ && gSelectedLocationViewSvg
+ && ( $(LOCATION_VIEW_EDIT_PANE_SELECTOR).length > 0 ));
}
})();
diff --git a/src/hi/static/js/svg-path.js b/src/hi/static/js/svg-path.js
index 0bdd407b..10aac1c7 100644
--- a/src/hi/static/js/svg-path.js
+++ b/src/hi/static/js/svg-path.js
@@ -10,18 +10,18 @@
const HiEditSvgPath = {
init: function() {
Hi.edit.eventBus.subscribe( Hi.edit.SELECTION_MADE_EVENT_NAME,
- this.clearSelection.bind( this ) );
+ this.clearSelection.bind( this ) );
+ },
+ handleClick: function( event ) {
+ return _handleClick( event );
+ },
+ handleKeyDown: function( event ) {
+ return _handleKeyDown( event );
},
- handleClick: function( event ) {
- return _handleClick( event );
- },
- handleKeyDown: function( event ) {
- return _handleKeyDown( event );
- },
clearSelection: function( data ) {
- gCurrentSelectionModule = data.moduleName;
- if ( data.moduleName != MODULE_NAME ) {
- clearSelectedPathSvgGroup();
+ gCurrentSelectionModule = data.moduleName;
+ if ( data.moduleName != MODULE_NAME ) {
+ clearSelectedPathSvgGroup();
}
}
};
@@ -66,20 +66,20 @@
const AFTER_PROXY_POINT_ID = 'after-proxy-point-id';
const PATH_ACTION_DELETE_KEY_CODES = [
- 88, // 'x'
- 8, // Backspace
- 46 // Delete
+ 88, // 'x'
+ 8, // Backspace
+ 46 // Delete
];
const PATH_ACTION_INSERT_KEY_CODES = [
- 73, // 'i'
- 45 // Insert
+ 73, // 'i'
+ 45 // Insert
];
const PATH_ACTION_ADD_KEY_CODES = [
- 65, // 'a'
- 61 // '+'
+ 65, // 'a'
+ 61 // '+'
];
const PATH_ACTION_END_KEY_CODES = [
- 27 // Escape
+ 27 // Escape
];
const CURSOR_MOVEMENT_THRESHOLD_PIXELS = 3; // Differentiate between move events and sloppy clicks
@@ -89,11 +89,11 @@
const PATH_EDIT_PROXY_LINE_COLOR = 'red';
const PATH_EDIT_PROXY_POINT_COLOR = 'red';
- const API_EDIT_SVG_PATH_URL = '/location/edit/location-item/path';
+ const API_EDIT_SVG_PATH_URL = '/location/edit/item/path';
const ProxyPathType = {
- OPEN: 'open',
- CLOSED: 'closed'
+ OPEN: 'open',
+ CLOSED: 'closed'
};
let gSelectedPathSvgGroup = null;
@@ -101,837 +101,837 @@
let gIgnoreCLick = false; // Set by mouseup handling when no click handling should be done
function _handleClick( event ) {
- if ( gSelectedPathSvgGroup && gIgnoreCLick ) {
- if ( Hi.DEBUG ) { console.log( `Ignoring click: [${MODULE_NAME}]`, event ); }
- gIgnoreCLick = false;
- return true;
- }
- gIgnoreCLick = false;
-
- const enclosingSvgGroup = $(event.target).closest('g');
- let handled = false;
- if ( enclosingSvgGroup.length > 0 ) {
- let svgDataType = $(enclosingSvgGroup).attr( Hi.DATA_TYPE_ATTR );
- const isSvgPath = ( svgDataType == Hi.DATA_TYPE_PATH_VALUE );
- const svgItemId = enclosingSvgGroup.attr('id');
- if ( isSvgPath && svgItemId ) {
- handleSvgPathClick( event, enclosingSvgGroup );
- handled = true;
- }
- }
- if ( ! handled && gSelectedPathSvgGroup ) {
- const enclosingSvg = $(event.target).closest('svg');
- if ( $(enclosingSvg).hasClass( Hi.LOCATION_VIEW_SVG_CLASS ) ) {
- handleProxyPathClick( event );
- handled = true;
- }
- }
-
- if ( handled ) {
- if ( Hi.DEBUG ) { console.log( `Click handled: [${MODULE_NAME}]`, event ); }
- } else {
- if ( Hi.DEBUG ) { console.log( `Click skipped: [${MODULE_NAME}]` ); }
- }
- return handled;
+ if ( gSelectedPathSvgGroup && gIgnoreCLick ) {
+ if ( Hi.DEBUG ) { console.log( `Ignoring click: [${MODULE_NAME}]`, event ); }
+ gIgnoreCLick = false;
+ return true;
+ }
+ gIgnoreCLick = false;
+
+ const enclosingSvgGroup = $(event.target).closest('g');
+ let handled = false;
+ if ( enclosingSvgGroup.length > 0 ) {
+ let svgDataType = $(enclosingSvgGroup).attr( Hi.DATA_TYPE_ATTR );
+ const isSvgPath = ( svgDataType == Hi.DATA_TYPE_PATH_VALUE );
+ const svgItemId = enclosingSvgGroup.attr('id');
+ if ( isSvgPath && svgItemId ) {
+ handleSvgPathClick( event, enclosingSvgGroup );
+ handled = true;
+ }
+ }
+ if ( ! handled && gSelectedPathSvgGroup ) {
+ const enclosingSvg = $(event.target).closest('svg');
+ if ( $(enclosingSvg).hasClass( Hi.LOCATION_VIEW_SVG_CLASS ) ) {
+ handleProxyPathClick( event );
+ handled = true;
+ }
+ }
+
+ if ( handled ) {
+ if ( Hi.DEBUG ) { console.log( `Click handled: [${MODULE_NAME}]`, event ); }
+ } else {
+ if ( Hi.DEBUG ) { console.log( `Click skipped: [${MODULE_NAME}]` ); }
+ }
+ return handled;
}
function _handleKeyDown( event ) {
- if ( ! Hi.isEditMode ) { return false; }
- if ( $(event.target).is('input[type="text"], textarea') ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ if ( $(event.target).is('input[type="text"], textarea') ) {
return false;
- }
- if ($(event.target).closest('.modal').length > 0) {
+ }
+ if ($(event.target).closest('.modal').length > 0) {
+ return false;
+ }
+ if ( ! gSvgPathEditData ) {
+ if ( Hi.DEBUG ) { console.log( `Key down skipped [${MODULE_NAME}]` ); }
return false;
- }
- if ( ! gSvgPathEditData ) {
- if ( Hi.DEBUG ) { console.log( `Key down skipped [${MODULE_NAME}]` ); }
- return false;
- }
- if ( Hi.DEBUG ) { console.log( `Key Down [${MODULE_NAME}]`, event ); }
-
- if ( PATH_ACTION_ADD_KEY_CODES.includes( event.keyCode ) ) {
- addProxyPath();
- return true;
-
- } else if ( PATH_ACTION_END_KEY_CODES.includes( event.keyCode ) ) {
- clearSelectedPathSvgGroup();
- let data = { moduleName: null };
- Hi.edit.eventBus.emit( Hi.edit.SELECTION_MADE_EVENT_NAME, data );
- return true;
-
- } else {
- if ( ! gSvgPathEditData.selectedProxyElement ) {
- if ( Hi.DEBUG ) { console.log( `Key down skipped [${MODULE_NAME}]` ); }
- return false;
- }
-
- if ( PATH_ACTION_DELETE_KEY_CODES.includes( event.keyCode )) {
- if ( $(gSvgPathEditData.selectedProxyElement).hasClass( PROXY_POINT_CLASS ) ) {
- deleteProxyPoint( gSvgPathEditData.selectedProxyElement );
- return true;
-
- } else if ( $(gSvgPathEditData.selectedProxyElement).hasClass( PROXY_LINE_CLASS ) ) {
- deleteProxyLine( gSvgPathEditData.selectedProxyElement );
- return true;
- }
-
- } else if ( PATH_ACTION_INSERT_KEY_CODES.includes( event.keyCode ) ) {
- if ( $(gSvgPathEditData.selectedProxyElement).hasClass( PROXY_LINE_CLASS ) ) {
- divideProxyLine( gSvgPathEditData.selectedProxyElement );
- return true;
-
- } else if ( $(gSvgPathEditData.selectedProxyElement).hasClass( PROXY_POINT_CLASS ) ) {
- let svgProxyLine = getPrecedingProxyLine( gSvgPathEditData.selectedProxyElement );
- if ( svgProxyLine.length > 0 ) {
- divideProxyLine( svgProxyLine );
- return true;
-
- } else {
- // Fallback for case of last proxy point selected.
- let svgProxyLine = getFollowingProxyLine( gSvgPathEditData.selectedProxyElement );
- if( svgProxyLine.length > 0 ) {
- divideProxyLine( svgProxyLine );
- return true;
- }
- }
- }
- }
- }
- if ( Hi.DEBUG ) { console.log( `Key down skipped [${MODULE_NAME}]` ); }
- return false;
+ }
+ if ( Hi.DEBUG ) { console.log( `Key Down [${MODULE_NAME}]`, event ); }
+
+ if ( PATH_ACTION_ADD_KEY_CODES.includes( event.keyCode ) ) {
+ addProxyPath();
+ return true;
+
+ } else if ( PATH_ACTION_END_KEY_CODES.includes( event.keyCode ) ) {
+ clearSelectedPathSvgGroup();
+ let data = { moduleName: null };
+ Hi.edit.eventBus.emit( Hi.edit.SELECTION_MADE_EVENT_NAME, data );
+ return true;
+
+ } else {
+ if ( ! gSvgPathEditData.selectedProxyElement ) {
+ if ( Hi.DEBUG ) { console.log( `Key down skipped [${MODULE_NAME}]` ); }
+ return false;
+ }
+
+ if ( PATH_ACTION_DELETE_KEY_CODES.includes( event.keyCode )) {
+ if ( $(gSvgPathEditData.selectedProxyElement).hasClass( PROXY_POINT_CLASS ) ) {
+ deleteProxyPoint( gSvgPathEditData.selectedProxyElement );
+ return true;
+
+ } else if ( $(gSvgPathEditData.selectedProxyElement).hasClass( PROXY_LINE_CLASS ) ) {
+ deleteProxyLine( gSvgPathEditData.selectedProxyElement );
+ return true;
+ }
+
+ } else if ( PATH_ACTION_INSERT_KEY_CODES.includes( event.keyCode ) ) {
+ if ( $(gSvgPathEditData.selectedProxyElement).hasClass( PROXY_LINE_CLASS ) ) {
+ divideProxyLine( gSvgPathEditData.selectedProxyElement );
+ return true;
+
+ } else if ( $(gSvgPathEditData.selectedProxyElement).hasClass( PROXY_POINT_CLASS ) ) {
+ let svgProxyLine = getPrecedingProxyLine( gSvgPathEditData.selectedProxyElement );
+ if ( svgProxyLine.length > 0 ) {
+ divideProxyLine( svgProxyLine );
+ return true;
+
+ } else {
+ // Fallback for case of last proxy point selected.
+ let svgProxyLine = getFollowingProxyLine( gSvgPathEditData.selectedProxyElement );
+ if( svgProxyLine.length > 0 ) {
+ divideProxyLine( svgProxyLine );
+ return true;
+ }
+ }
+ }
+ }
+ }
+ if ( Hi.DEBUG ) { console.log( `Key down skipped [${MODULE_NAME}]` ); }
+ return false;
}
function handleSvgPathClick( event, enclosingSvgGroup ) {
- const svgItemId = $(enclosingSvgGroup).attr('id');
-
- if ( Hi.isEditMode ) {
- clearSelectedPathSvgGroup();
- gSelectedPathSvgGroup = enclosingSvgGroup;
- expandSvgPath( enclosingSvgGroup );
- let data = {
- moduleName: MODULE_NAME,
- };
- Hi.edit.eventBus.emit( Hi.edit.SELECTION_MADE_EVENT_NAME, data );
- AN.get( `${Hi.API_LOCATION_ITEM_DETAILS_URL}/${svgItemId}` );
- } else {
- AN.get( `${Hi.API_LOCATION_ITEM_INFO_URL}/${svgItemId}` );
- }
+ const svgItemId = $(enclosingSvgGroup).attr('id');
+
+ if ( Hi.isEditMode ) {
+ clearSelectedPathSvgGroup();
+ gSelectedPathSvgGroup = enclosingSvgGroup;
+ expandSvgPath( enclosingSvgGroup );
+ let data = {
+ moduleName: MODULE_NAME,
+ };
+ Hi.edit.eventBus.emit( Hi.edit.SELECTION_MADE_EVENT_NAME, data );
+ AN.get( `${Hi.API_LOCATION_ITEM_EDIT_MODE_URL}/${svgItemId}` );
+ } else {
+ AN.get( `${Hi.API_LOCATION_ITEM_STATUS_URL}/${svgItemId}` );
+ }
}
function clearSelectedPathSvgGroup() {
- if ( gSelectedPathSvgGroup ) {
+ if ( gSelectedPathSvgGroup ) {
console.log('Clearing svg path selection');
- collapseSvgPath( );
- gSelectedPathSvgGroup = null;
- }
+ collapseSvgPath( );
+ gSelectedPathSvgGroup = null;
+ }
}
function handleProxyPathClick( event ) {
- const isProxyElement = $(event.target).hasClass( PROXY_ITEM_CLASS );
- if ( isProxyElement ) {
- setSelectedProxyElement( event.target );
- }
- else {
- extendProxyPath( event );
- }
+ const isProxyElement = $(event.target).hasClass( PROXY_ITEM_CLASS );
+ if ( isProxyElement ) {
+ setSelectedProxyElement( event.target );
+ }
+ else {
+ extendProxyPath( event );
+ }
}
function setSelectedProxyElement( proxyElement ) {
- if ( ! gSvgPathEditData ) {
- return;
- }
- $(gSvgPathEditData.proxyPathContainer).find('.' + PROXY_ITEM_CLASS).removeClass( Hi.HIGHLIGHTED_CLASS );
- if ( proxyElement ) {
- $(proxyElement).addClass( Hi.HIGHLIGHTED_CLASS );
- }
- gSvgPathEditData.selectedProxyElement = proxyElement;
+ if ( ! gSvgPathEditData ) {
+ return;
+ }
+ $(gSvgPathEditData.proxyPathContainer).find('.' + PROXY_ITEM_CLASS).removeClass( Hi.HIGHLIGHTED_CLASS );
+ if ( proxyElement ) {
+ $(proxyElement).addClass( Hi.HIGHLIGHTED_CLASS );
+ }
+ gSvgPathEditData.selectedProxyElement = proxyElement;
}
function expandSvgPath( pathSvgGroup ) {
- if ( Hi.DEBUG ) { console.log( 'Expand SVG Path', pathSvgGroup ); }
-
- pathSvgGroup.hide();
-
- const baseSvgElement = $(Hi.BASE_SVG_SELECTOR)[0];
- const proxyPathContainer = document.createElementNS('http://www.w3.org/2000/svg', 'g');
- proxyPathContainer.setAttribute('id', PROXY_PATH_CONTAINER_ID );
- baseSvgElement.appendChild( proxyPathContainer );
-
- gSvgPathEditData = {
- proxyPathContainer: proxyPathContainer,
- selectedProxyElement: null,
- dragProxyPoint: null,
- };
-
- let svgPathElement = $(pathSvgGroup).find('path');
- const pathData = svgPathElement.attr('d');
- const segments = pathData.match(/[ML][^MLZ]+|Z/g);
- if ( Hi.DEBUG ) { console.log('Path segments', segments ); }
-
- /* Algorithm Description:
-
- - We first create all the proxy 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 proxy points.
- - First and last proxy 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.
- - We organize all the proxy item into SVG groups:
- - A SVG group excloses all with one child SVG group for each line segment (called a proxyPath)
- - Insert items in DOM in order since we rely on this ordering as a data structure.
- - Lines should be drawn before proxy points, so use a subgrouping for each type.
- */
-
- // - Create all proxy points.
- let currentProxyPathGroup = null;
- let currentProxyPointsGroup = null;
- for ( let i = 0; i < segments.length; i++ ) {
-
+ if ( Hi.DEBUG ) { console.log( 'Expand SVG Path', pathSvgGroup ); }
+
+ pathSvgGroup.hide();
+
+ const baseSvgElement = $(Hi.BASE_SVG_SELECTOR)[0];
+ const proxyPathContainer = document.createElementNS('http://www.w3.org/2000/svg', 'g');
+ proxyPathContainer.setAttribute('id', PROXY_PATH_CONTAINER_ID );
+ baseSvgElement.appendChild( proxyPathContainer );
+
+ gSvgPathEditData = {
+ proxyPathContainer: proxyPathContainer,
+ selectedProxyElement: null,
+ dragProxyPoint: null,
+ };
+
+ let svgPathElement = $(pathSvgGroup).find('path');
+ const pathData = svgPathElement.attr('d');
+ const segments = pathData.match(/[ML][^MLZ]+|Z/g);
+ if ( Hi.DEBUG ) { console.log('Path segments', segments ); }
+
+ /* Algorithm Description:
+
+ - We first create all the proxy 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 proxy points.
+ - First and last proxy 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.
+ - We organize all the proxy item into SVG groups:
+ - A SVG group excloses all with one child SVG group for each line segment (called a proxyPath)
+ - Insert items in DOM in order since we rely on this ordering as a data structure.
+ - Lines should be drawn before proxy points, so use a subgrouping for each type.
+ */
+
+ // - Create all proxy points.
+ let currentProxyPathGroup = null;
+ let currentProxyPointsGroup = 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') {
- currentProxyPathGroup = createProxyPathGroup( ProxyPathType.OPEN );
- $(proxyPathContainer).append( currentProxyPathGroup );
-
- let newProxyPoint = createProxyPathProxyPoint( coords[0], coords[1] );
- $(currentProxyPathGroup).find( PROXY_POINTS_GROUP_SELECTOR ).append( newProxyPoint );
-
+ currentProxyPathGroup = createProxyPathGroup( ProxyPathType.OPEN );
+ $(proxyPathContainer).append( currentProxyPathGroup );
+
+ let newProxyPoint = createProxyPathProxyPoint( coords[0], coords[1] );
+ $(currentProxyPathGroup).find( PROXY_POINTS_GROUP_SELECTOR ).append( newProxyPoint );
+
} else if (command === 'L' && currentProxyPathGroup ) {
- let newProxyPoint = createProxyPathProxyPoint( coords[0], coords[1] );
- $(currentProxyPathGroup).find( PROXY_POINTS_GROUP_SELECTOR ).append( newProxyPoint );
+ let newProxyPoint = createProxyPathProxyPoint( coords[0], coords[1] );
+ $(currentProxyPathGroup).find( PROXY_POINTS_GROUP_SELECTOR ).append( newProxyPoint );
} else if (command === 'Z' && currentProxyPathGroup ) {
- $(currentProxyPathGroup).attr( PROXY_PATH_TYPE_ATTR, ProxyPathType.CLOSED );
- currentProxyPathGroup = null;
+ $(currentProxyPathGroup).attr( PROXY_PATH_TYPE_ATTR, ProxyPathType.CLOSED );
+ currentProxyPathGroup = null;
}
- }
-
- // Paths can have multiple segments
- $(proxyPathContainer).find( PROXY_PATH_GROUP_SELECTOR ).each(function( index, proxyPathGroup ) {
-
- if ( Hi.DEBUG ) { console.log( 'Proxy path group: ', proxyPathGroup ); }
-
- // Create interior lines and proxy point handlers with bookkeeping for first/last edge cases.
- let previousProxyPoint = null;
- let firstLine = null;
- let previousLine = null;
-
- let proxyLinesGroup = $(proxyPathGroup).find( PROXY_LINES_GROUP_SELECTOR );
- let proxyPoints = $(proxyPathGroup).find( PROXY_POINT_SELECTOR );
-
- $(proxyPoints).each(function( index, currentProxyPoint ) {
-
- if ( previousProxyPoint ) {
- const x1 = parseFloat(previousProxyPoint.getAttribute('cx'));
- const y1 = parseFloat(previousProxyPoint.getAttribute('cy'));
- const x2 = parseFloat(currentProxyPoint.getAttribute('cx'));
- const y2 = parseFloat(currentProxyPoint.getAttribute('cy'));
- let currentLine = createProxyPathLine( previousProxyPoint, currentProxyPoint,
- x1, y1, x2, y2 );
- $(proxyLinesGroup).append( currentLine );
-
- if ( previousLine ) {
- addProxyPointEventHandler( previousProxyPoint, previousLine, currentLine );
- }
- if ( ! firstLine ) {
- firstLine = currentLine;
- }
- previousLine = currentLine;
- }
-
- previousProxyPoint = currentProxyPoint;
- });
-
- // Degerate cases of zero or one point and no lines.
- if ( proxyPoints.length < 2 ) {
- addProxyPointEventHandler( previousProxyPoint, null, null );
- return;
- }
-
- // Edge cases for first and last points.
- let firstProxyPoint = proxyPoints[0];
- let lastProxyPoint = proxyPoints[proxyPoints.length -1];
-
- if ( $(proxyPathGroup).attr( PROXY_PATH_TYPE_ATTR ) == ProxyPathType.OPEN ) {
- addProxyPointEventHandler( firstProxyPoint, null, firstLine );
- addProxyPointEventHandler( lastProxyPoint, previousLine, null );
- } else {
- const x1 = parseFloat(lastProxyPoint.getAttribute('cx'));
- const y1 = parseFloat(lastProxyPoint.getAttribute('cy'));
- const x2 = parseFloat(firstProxyPoint.getAttribute('cx'));
- const y2 = parseFloat(firstProxyPoint.getAttribute('cy'));
- let closureLine = createProxyPathLine( lastProxyPoint, firstProxyPoint,
- x1, y1, x2, y2 );
- $(proxyLinesGroup).append( closureLine );
- addProxyPointEventHandler( firstProxyPoint, closureLine, firstLine );
- addProxyPointEventHandler( lastProxyPoint, previousLine, closureLine );
- }
- });
+ }
+
+ // Paths can have multiple segments
+ $(proxyPathContainer).find( PROXY_PATH_GROUP_SELECTOR ).each(function( index, proxyPathGroup ) {
+
+ if ( Hi.DEBUG ) { console.log( 'Proxy path group: ', proxyPathGroup ); }
+
+ // Create interior lines and proxy point handlers with bookkeeping for first/last edge cases.
+ let previousProxyPoint = null;
+ let firstLine = null;
+ let previousLine = null;
+
+ let proxyLinesGroup = $(proxyPathGroup).find( PROXY_LINES_GROUP_SELECTOR );
+ let proxyPoints = $(proxyPathGroup).find( PROXY_POINT_SELECTOR );
+
+ $(proxyPoints).each(function( index, currentProxyPoint ) {
+
+ if ( previousProxyPoint ) {
+ const x1 = parseFloat(previousProxyPoint.getAttribute('cx'));
+ const y1 = parseFloat(previousProxyPoint.getAttribute('cy'));
+ const x2 = parseFloat(currentProxyPoint.getAttribute('cx'));
+ const y2 = parseFloat(currentProxyPoint.getAttribute('cy'));
+ let currentLine = createProxyPathLine( previousProxyPoint, currentProxyPoint,
+ x1, y1, x2, y2 );
+ $(proxyLinesGroup).append( currentLine );
+
+ if ( previousLine ) {
+ addProxyPointEventHandler( previousProxyPoint, previousLine, currentLine );
+ }
+ if ( ! firstLine ) {
+ firstLine = currentLine;
+ }
+ previousLine = currentLine;
+ }
+
+ previousProxyPoint = currentProxyPoint;
+ });
+
+ // Degerate cases of zero or one point and no lines.
+ if ( proxyPoints.length < 2 ) {
+ addProxyPointEventHandler( previousProxyPoint, null, null );
+ return;
+ }
+
+ // Edge cases for first and last points.
+ let firstProxyPoint = proxyPoints[0];
+ let lastProxyPoint = proxyPoints[proxyPoints.length -1];
+
+ if ( $(proxyPathGroup).attr( PROXY_PATH_TYPE_ATTR ) == ProxyPathType.OPEN ) {
+ addProxyPointEventHandler( firstProxyPoint, null, firstLine );
+ addProxyPointEventHandler( lastProxyPoint, previousLine, null );
+ } else {
+ const x1 = parseFloat(lastProxyPoint.getAttribute('cx'));
+ const y1 = parseFloat(lastProxyPoint.getAttribute('cy'));
+ const x2 = parseFloat(firstProxyPoint.getAttribute('cx'));
+ const y2 = parseFloat(firstProxyPoint.getAttribute('cy'));
+ let closureLine = createProxyPathLine( lastProxyPoint, firstProxyPoint,
+ x1, y1, x2, y2 );
+ $(proxyLinesGroup).append( closureLine );
+ addProxyPointEventHandler( firstProxyPoint, closureLine, firstLine );
+ addProxyPointEventHandler( lastProxyPoint, previousLine, closureLine );
+ }
+ });
}
function extendProxyPath( event ) {
-
- console.log( 'Extending proxy path' );
- const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
- const svgViewBox = Hi.svgUtils.getSvgViewBox( baseSvgElement );
- let svgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement, event.clientX, event.clientY );
-
- // Do not allow creating points outside viewbox (else cannot manipulate them).
- if (( svgPoint.x < svgViewBox.x )
- || ( svgPoint.x > ( svgViewBox.x + svgViewBox.width ))
- || ( svgPoint.y < svgViewBox.y )
- || ( svgPoint.y > ( svgViewBox.y + svgViewBox.height )) ) {
- return;
- }
-
- let referenceElement = getReferenceElementForExtendingProxyPath();
- let proxyPathGroup = $(referenceElement).closest(PROXY_PATH_GROUP_SELECTOR);
- let newProxyPoint = null;
-
- if ( $(referenceElement).hasClass( PROXY_POINT_CLASS) ) {
- if ( $(proxyPathGroup).attr( PROXY_PATH_TYPE_ATTR ) == ProxyPathType.OPEN ) {
- if ( $(referenceElement).is(':first-of-type') ) {
- newProxyPoint = prependNewProxyPoint( svgPoint, proxyPathGroup );
-
- } else {
- newProxyPoint = appendNewProxyPoint( svgPoint, proxyPathGroup );
- }
- } else {
- let followingProxyLine = getFollowingProxyLine( referenceElement );
- newProxyPoint = insertNewProxyPoint( svgPoint, followingProxyLine );
-
- }
- } else if ( $(referenceElement).hasClass( PROXY_LINE_CLASS ) ) {
- newProxyPoint = insertNewProxyPoint( svgPoint, referenceElement );
- } else {
- console.log( 'Unrecognized reference proxy element.' );
- return;
- }
-
- if ( newProxyPoint ) {
- setSelectedProxyElement( newProxyPoint );
- saveSvgPath();
- }
+
+ console.log( 'Extending proxy path' );
+ const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
+ const svgViewBox = Hi.svgUtils.getSvgViewBox( baseSvgElement );
+ let svgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement, event.clientX, event.clientY );
+
+ // Do not allow creating points outside viewbox (else cannot manipulate them).
+ if (( svgPoint.x < svgViewBox.x )
+ || ( svgPoint.x > ( svgViewBox.x + svgViewBox.width ))
+ || ( svgPoint.y < svgViewBox.y )
+ || ( svgPoint.y > ( svgViewBox.y + svgViewBox.height )) ) {
+ return;
+ }
+
+ let referenceElement = getReferenceElementForExtendingProxyPath();
+ let proxyPathGroup = $(referenceElement).closest(PROXY_PATH_GROUP_SELECTOR);
+ let newProxyPoint = null;
+
+ if ( $(referenceElement).hasClass( PROXY_POINT_CLASS) ) {
+ if ( $(proxyPathGroup).attr( PROXY_PATH_TYPE_ATTR ) == ProxyPathType.OPEN ) {
+ if ( $(referenceElement).is(':first-of-type') ) {
+ newProxyPoint = prependNewProxyPoint( svgPoint, proxyPathGroup );
+
+ } else {
+ newProxyPoint = appendNewProxyPoint( svgPoint, proxyPathGroup );
+ }
+ } else {
+ let followingProxyLine = getFollowingProxyLine( referenceElement );
+ newProxyPoint = insertNewProxyPoint( svgPoint, followingProxyLine );
+
+ }
+ } else if ( $(referenceElement).hasClass( PROXY_LINE_CLASS ) ) {
+ newProxyPoint = insertNewProxyPoint( svgPoint, referenceElement );
+ } else {
+ console.log( 'Unrecognized reference proxy element.' );
+ return;
+ }
+
+ if ( newProxyPoint ) {
+ setSelectedProxyElement( newProxyPoint );
+ saveSvgPath();
+ }
}
function prependNewProxyPoint( newSvgPoint, proxyPathGroup ) {
- let firstProxyPoint = proxyPathGroup.find( PROXY_POINT_SELECTOR ).first();
- let firstLine = proxyPathGroup.find( PROXY_LINE_SELECTOR ).first();
+ let firstProxyPoint = proxyPathGroup.find( PROXY_POINT_SELECTOR ).first();
+ let firstLine = proxyPathGroup.find( PROXY_LINE_SELECTOR ).first();
- if ( Hi.DEBUG ) { console.log( 'Prepend: First point and line: ', firstProxyPoint, firstLine ); }
-
- const firstX = parseFloat( $(firstProxyPoint).attr('cx') );
- const firstY = parseFloat( $(firstProxyPoint).attr('cy') );
+ if ( Hi.DEBUG ) { console.log( 'Prepend: First point and line: ', firstProxyPoint, firstLine ); }
+
+ const firstX = parseFloat( $(firstProxyPoint).attr('cx') );
+ const firstY = parseFloat( $(firstProxyPoint).attr('cy') );
- let newProxyPoint = createProxyPathProxyPoint( newSvgPoint.x, newSvgPoint.y );
- let newLine = createProxyPathLine( newProxyPoint, firstProxyPoint,
- newSvgPoint.x, newSvgPoint.y, firstX, firstY );
+ let newProxyPoint = createProxyPathProxyPoint( newSvgPoint.x, newSvgPoint.y );
+ let newLine = createProxyPathLine( newProxyPoint, firstProxyPoint,
+ newSvgPoint.x, newSvgPoint.y, firstX, firstY );
- let proxyPointsGroup = $(proxyPathGroup).find( PROXY_POINTS_GROUP_SELECTOR );
- let proxyLinesGroup = $(proxyPathGroup).find( PROXY_LINES_GROUP_SELECTOR );
- $(proxyPointsGroup).prepend( newProxyPoint );
- $(proxyLinesGroup).prepend( newLine );
-
- $(firstProxyPoint).off(); // Removes event listeners
- addProxyPointEventHandler( firstProxyPoint, newLine, firstLine );
- addProxyPointEventHandler( newProxyPoint, null, newLine );
+ let proxyPointsGroup = $(proxyPathGroup).find( PROXY_POINTS_GROUP_SELECTOR );
+ let proxyLinesGroup = $(proxyPathGroup).find( PROXY_LINES_GROUP_SELECTOR );
+ $(proxyPointsGroup).prepend( newProxyPoint );
+ $(proxyLinesGroup).prepend( newLine );
+
+ $(firstProxyPoint).off(); // Removes event listeners
+ addProxyPointEventHandler( firstProxyPoint, newLine, firstLine );
+ addProxyPointEventHandler( newProxyPoint, null, newLine );
- return newProxyPoint;
+ return newProxyPoint;
}
function appendNewProxyPoint( newSvgPoint, proxyPathGroup ) {
- let lastProxyPoint = proxyPathGroup.find( PROXY_POINT_SELECTOR ).last();
- let lastLine = proxyPathGroup.find( PROXY_LINE_SELECTOR ).last();
+ let lastProxyPoint = proxyPathGroup.find( PROXY_POINT_SELECTOR ).last();
+ let lastLine = proxyPathGroup.find( PROXY_LINE_SELECTOR ).last();
- if ( Hi.DEBUG ) { console.log( 'Append: Last point and line: ', lastProxyPoint, lastLine ); }
-
- const lastX = parseFloat($(lastProxyPoint).attr('cx'));
- const lastY = parseFloat($(lastProxyPoint).attr('cy'));
+ if ( Hi.DEBUG ) { console.log( 'Append: Last point and line: ', lastProxyPoint, lastLine ); }
+
+ const lastX = parseFloat($(lastProxyPoint).attr('cx'));
+ const lastY = parseFloat($(lastProxyPoint).attr('cy'));
- let newProxyPoint = createProxyPathProxyPoint( newSvgPoint.x, newSvgPoint.y );
- let newLine = createProxyPathLine( lastProxyPoint, newProxyPoint,
- lastX, lastY, newSvgPoint.x, newSvgPoint.y );
+ let newProxyPoint = createProxyPathProxyPoint( newSvgPoint.x, newSvgPoint.y );
+ let newLine = createProxyPathLine( lastProxyPoint, newProxyPoint,
+ lastX, lastY, newSvgPoint.x, newSvgPoint.y );
- let proxyPointsGroup = $(proxyPathGroup).find( PROXY_POINTS_GROUP_SELECTOR );
- let proxyLinesGroup = $(proxyPathGroup).find( PROXY_LINES_GROUP_SELECTOR );
- $(proxyPointsGroup).append( newProxyPoint );
- $(proxyLinesGroup).append( newLine );
-
- $(lastProxyPoint).off(); // Removes event listeners
- addProxyPointEventHandler( lastProxyPoint, lastLine, newLine );
- addProxyPointEventHandler( newProxyPoint, newLine, null );
+ let proxyPointsGroup = $(proxyPathGroup).find( PROXY_POINTS_GROUP_SELECTOR );
+ let proxyLinesGroup = $(proxyPathGroup).find( PROXY_LINES_GROUP_SELECTOR );
+ $(proxyPointsGroup).append( newProxyPoint );
+ $(proxyLinesGroup).append( newLine );
+
+ $(lastProxyPoint).off(); // Removes event listeners
+ addProxyPointEventHandler( lastProxyPoint, lastLine, newLine );
+ addProxyPointEventHandler( newProxyPoint, newLine, null );
- return newProxyPoint;
+ return newProxyPoint;
}
function insertNewProxyPoint( newSvgPoint, referenceProxyLine ) {
- const beforeProxyPointId = $(referenceProxyLine).attr( BEFORE_PROXY_POINT_ID );
- const afterProxyPointId = $(referenceProxyLine).attr( AFTER_PROXY_POINT_ID );
+ const beforeProxyPointId = $(referenceProxyLine).attr( BEFORE_PROXY_POINT_ID );
+ const afterProxyPointId = $(referenceProxyLine).attr( AFTER_PROXY_POINT_ID );
- let beforeProxyPoint = $('#' + beforeProxyPointId );
- let afterProxyPoint = $('#' + afterProxyPointId );
- let followingProxyLine = getFollowingProxyLine( afterProxyPoint );
-
- if ( Hi.DEBUG ) { console.log( 'Insert: ', referenceProxyLine, beforeProxyPoint,
- afterProxyPoint, followingProxyLine ); }
+ let beforeProxyPoint = $('#' + beforeProxyPointId );
+ let afterProxyPoint = $('#' + afterProxyPointId );
+ let followingProxyLine = getFollowingProxyLine( afterProxyPoint );
+
+ if ( Hi.DEBUG ) { console.log( 'Insert: ', referenceProxyLine, beforeProxyPoint,
+ afterProxyPoint, followingProxyLine ); }
- const beforeX = parseFloat($(beforeProxyPoint).attr('cx'));
- const beforeY = parseFloat($(beforeProxyPoint).attr('cy'));
+ const beforeX = parseFloat($(beforeProxyPoint).attr('cx'));
+ const beforeY = parseFloat($(beforeProxyPoint).attr('cy'));
- const afterX = parseFloat($(afterProxyPoint).attr('cx'));
- const afterY = parseFloat($(afterProxyPoint).attr('cy'));
+ const afterX = parseFloat($(afterProxyPoint).attr('cx'));
+ const afterY = parseFloat($(afterProxyPoint).attr('cy'));
- let newProxyPoint = createProxyPathProxyPoint( newSvgPoint.x, newSvgPoint.y );
- let newLine = createProxyPathLine( newProxyPoint, afterProxyPoint,
- newSvgPoint.x, newSvgPoint.y, afterX, afterY );
+ let newProxyPoint = createProxyPathProxyPoint( newSvgPoint.x, newSvgPoint.y );
+ let newLine = createProxyPathLine( newProxyPoint, afterProxyPoint,
+ newSvgPoint.x, newSvgPoint.y, afterX, afterY );
- $(referenceProxyLine).attr( AFTER_PROXY_POINT_ID, $(newProxyPoint).attr('id') );
- $(referenceProxyLine).attr( 'x2', newSvgPoint.x );
- $(referenceProxyLine).attr( 'y2', newSvgPoint.y );
+ $(referenceProxyLine).attr( AFTER_PROXY_POINT_ID, $(newProxyPoint).attr('id') );
+ $(referenceProxyLine).attr( 'x2', newSvgPoint.x );
+ $(referenceProxyLine).attr( 'y2', newSvgPoint.y );
- $(beforeProxyPoint).after( newProxyPoint );
- $(referenceProxyLine).after( newLine );
-
- $(afterProxyPoint).off(); // Removes event listeners
- addProxyPointEventHandler( afterProxyPoint, newLine, followingProxyLine );
- addProxyPointEventHandler( newProxyPoint, referenceProxyLine, newLine );
+ $(beforeProxyPoint).after( newProxyPoint );
+ $(referenceProxyLine).after( newLine );
+
+ $(afterProxyPoint).off(); // Removes event listeners
+ addProxyPointEventHandler( afterProxyPoint, newLine, followingProxyLine );
+ addProxyPointEventHandler( newProxyPoint, referenceProxyLine, newLine );
- return newProxyPoint;
+ return newProxyPoint;
}
function deleteProxyPoint( svgProxyPoint ) {
- let proxyPathGroup = $(svgProxyPoint).closest( PROXY_PATH_GROUP_SELECTOR );
- let proxyPathType = $(proxyPathGroup).attr( PROXY_PATH_TYPE_ATTR );
- let proxyPointsGroup = $(svgProxyPoint).closest( PROXY_POINTS_GROUP_SELECTOR );
- let minPoints = 2;
- if ( proxyPathType == ProxyPathType.CLOSED ) {
- minPoints = 3;
- }
- if ( $(proxyPointsGroup).children().length <= minPoints ) {
- removeProxyPathIfAllowed( proxyPathGroup );
- return;
- }
-
- let svgProxyPointId = $(svgProxyPoint).attr('id');
-
- let beforeProxyLine = getPrecedingProxyLine( svgProxyPoint );
- let afterProxyLine = getFollowingProxyLine( svgProxyPoint );
-
- if (( beforeProxyLine.length > 0 ) && ( afterProxyLine.length > 0)) {
-
- let afterProxyPointId = $(afterProxyLine).attr( AFTER_PROXY_POINT_ID );
- let afterProxyPoint = $('#' + afterProxyPointId);
- let followingProxyLine = getFollowingProxyLine( afterProxyPoint );
-
- const afterX = parseFloat( $(afterProxyPoint).attr('cx') );
- const afterY = parseFloat( $(afterProxyPoint).attr('cy') );
- $(beforeProxyLine).attr( AFTER_PROXY_POINT_ID, $(afterProxyPoint).attr('id') );
- $(beforeProxyLine).attr( 'x2', afterX );
- $(beforeProxyLine).attr( 'y2', afterY );
-
- $(afterProxyPoint).off(); // Removes event listeners
- addProxyPointEventHandler( afterProxyPoint, beforeProxyLine, followingProxyLine );
-
- $(svgProxyPoint).remove();
- $(afterProxyLine).remove();
-
- setSelectedProxyElement( afterProxyPoint );
-
- } else if ( afterProxyLine.length > 0 ) {
-
- let afterProxyPointId = $(afterProxyLine).attr( AFTER_PROXY_POINT_ID );
- let afterProxyPoint = $('#' + afterProxyPointId);
- let followingProxyLine = getFollowingProxyLine( afterProxyPoint );
-
- $(afterProxyPoint).off(); // Removes event listeners
- addProxyPointEventHandler( afterProxyPoint, null, followingProxyLine );
-
- $(svgProxyPoint).remove();
- $(afterProxyLine).remove();
-
- setSelectedProxyElement( afterProxyPoint );
-
- } else if ( beforeProxyLine.length > 0 ) {
- let beforeProxyPointId = $(beforeProxyLine).attr( BEFORE_PROXY_POINT_ID );
- let beforeProxyPoint = $('#' + beforeProxyPointId);
- let precedingProxyLine =getPrecedingProxyLine( beforeProxyPoint );
-
- $(beforeProxyPoint).off(); // Removes event listeners
- addProxyPointEventHandler( beforeProxyPoint, precedingProxyLine, null );
-
- $(svgProxyPoint).remove();
- $(beforeProxyLine).remove();
-
- setSelectedProxyElement( beforeProxyPoint );
-
- } else {
- $(svgProxyPoint).remove();
- setSelectedProxyElement( null );
- }
-
- saveSvgPath();
+ let proxyPathGroup = $(svgProxyPoint).closest( PROXY_PATH_GROUP_SELECTOR );
+ let proxyPathType = $(proxyPathGroup).attr( PROXY_PATH_TYPE_ATTR );
+ let proxyPointsGroup = $(svgProxyPoint).closest( PROXY_POINTS_GROUP_SELECTOR );
+ let minPoints = 2;
+ if ( proxyPathType == ProxyPathType.CLOSED ) {
+ minPoints = 3;
+ }
+ if ( $(proxyPointsGroup).children().length <= minPoints ) {
+ removeProxyPathIfAllowed( proxyPathGroup );
+ return;
+ }
+
+ let svgProxyPointId = $(svgProxyPoint).attr('id');
+
+ let beforeProxyLine = getPrecedingProxyLine( svgProxyPoint );
+ let afterProxyLine = getFollowingProxyLine( svgProxyPoint );
+
+ if (( beforeProxyLine.length > 0 ) && ( afterProxyLine.length > 0)) {
+
+ let afterProxyPointId = $(afterProxyLine).attr( AFTER_PROXY_POINT_ID );
+ let afterProxyPoint = $('#' + afterProxyPointId);
+ let followingProxyLine = getFollowingProxyLine( afterProxyPoint );
+
+ const afterX = parseFloat( $(afterProxyPoint).attr('cx') );
+ const afterY = parseFloat( $(afterProxyPoint).attr('cy') );
+ $(beforeProxyLine).attr( AFTER_PROXY_POINT_ID, $(afterProxyPoint).attr('id') );
+ $(beforeProxyLine).attr( 'x2', afterX );
+ $(beforeProxyLine).attr( 'y2', afterY );
+
+ $(afterProxyPoint).off(); // Removes event listeners
+ addProxyPointEventHandler( afterProxyPoint, beforeProxyLine, followingProxyLine );
+
+ $(svgProxyPoint).remove();
+ $(afterProxyLine).remove();
+
+ setSelectedProxyElement( afterProxyPoint );
+
+ } else if ( afterProxyLine.length > 0 ) {
+
+ let afterProxyPointId = $(afterProxyLine).attr( AFTER_PROXY_POINT_ID );
+ let afterProxyPoint = $('#' + afterProxyPointId);
+ let followingProxyLine = getFollowingProxyLine( afterProxyPoint );
+
+ $(afterProxyPoint).off(); // Removes event listeners
+ addProxyPointEventHandler( afterProxyPoint, null, followingProxyLine );
+
+ $(svgProxyPoint).remove();
+ $(afterProxyLine).remove();
+
+ setSelectedProxyElement( afterProxyPoint );
+
+ } else if ( beforeProxyLine.length > 0 ) {
+ let beforeProxyPointId = $(beforeProxyLine).attr( BEFORE_PROXY_POINT_ID );
+ let beforeProxyPoint = $('#' + beforeProxyPointId);
+ let precedingProxyLine =getPrecedingProxyLine( beforeProxyPoint );
+
+ $(beforeProxyPoint).off(); // Removes event listeners
+ addProxyPointEventHandler( beforeProxyPoint, precedingProxyLine, null );
+
+ $(svgProxyPoint).remove();
+ $(beforeProxyLine).remove();
+
+ setSelectedProxyElement( beforeProxyPoint );
+
+ } else {
+ $(svgProxyPoint).remove();
+ setSelectedProxyElement( null );
+ }
+
+ saveSvgPath();
}
function deleteProxyLine( svgProxyLine ) {
- // Acts like a delete for 'before' proxy point.
- let beforeProxyPointId = $(svgProxyLine).attr( BEFORE_PROXY_POINT_ID );
- let beforeProxyPoint = $('#' + beforeProxyPointId);
- deleteProxyPoint( beforeProxyPoint );
+ // Acts like a delete for 'before' proxy point.
+ let beforeProxyPointId = $(svgProxyLine).attr( BEFORE_PROXY_POINT_ID );
+ let beforeProxyPoint = $('#' + beforeProxyPointId);
+ deleteProxyPoint( beforeProxyPoint );
}
function divideProxyLine( svgProxyLine ) {
- // Same as inserting via mouse click, but use midpoint as the insertion point.
+ // Same as inserting via mouse click, but use midpoint as the insertion point.
- let beforeProxyPointId = $(svgProxyLine).attr( BEFORE_PROXY_POINT_ID );
- let afterProxyPointId = $(svgProxyLine).attr( AFTER_PROXY_POINT_ID );
- let beforeProxyPoint = $('#' + beforeProxyPointId);
- let afterProxyPoint = $('#' + afterProxyPointId);
+ let beforeProxyPointId = $(svgProxyLine).attr( BEFORE_PROXY_POINT_ID );
+ let afterProxyPointId = $(svgProxyLine).attr( AFTER_PROXY_POINT_ID );
+ let beforeProxyPoint = $('#' + beforeProxyPointId);
+ let afterProxyPoint = $('#' + afterProxyPointId);
- const beforeX = parseFloat($(beforeProxyPoint).attr('cx'));
- const beforeY = parseFloat($(beforeProxyPoint).attr('cy'));
+ const beforeX = parseFloat($(beforeProxyPoint).attr('cx'));
+ const beforeY = parseFloat($(beforeProxyPoint).attr('cy'));
- const afterX = parseFloat($(afterProxyPoint).attr('cx'));
- const afterY = parseFloat($(afterProxyPoint).attr('cy'));
+ const afterX = parseFloat($(afterProxyPoint).attr('cx'));
+ const afterY = parseFloat($(afterProxyPoint).attr('cy'));
- let midSvgPoint = {
- x: ( beforeX + afterX ) / 2,
- y: ( beforeY + afterY ) / 2
- };
- insertNewProxyPoint( midSvgPoint, svgProxyLine );
- saveSvgPath();
+ let midSvgPoint = {
+ x: ( beforeX + afterX ) / 2,
+ y: ( beforeY + afterY ) / 2
+ };
+ insertNewProxyPoint( midSvgPoint, svgProxyLine );
+ saveSvgPath();
}
function addProxyPath( ) {
- let proxyPathContainer = $('#' + PROXY_PATH_CONTAINER_ID );
- let firstProxyPath = $(proxyPathContainer).find( PROXY_PATH_GROUP_SELECTOR ).first();
- let proxyPathType = $(firstProxyPath).attr( PROXY_PATH_TYPE_ATTR );
- let newProxyPathGroup = createProxyPathGroup( proxyPathType );
- $(proxyPathContainer).append( newProxyPathGroup );
-
- const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
- const svgViewBox = Hi.svgUtils.getSvgViewBox( baseSvgElement );
- let svgCenter = {
- x: svgViewBox.x + ( svgViewBox.width / 2 ),
- y: svgViewBox.y + ( svgViewBox.height / 2 )
- };
- let svgUnitRadius = {
- x: svgViewBox.width * ( PATH_EDIT_NEW_PATH_RADIUS_PERCENT / 100.0 ),
- y: svgViewBox.height * ( PATH_EDIT_NEW_PATH_RADIUS_PERCENT / 100.0 )
- };
-
- if ( Hi.DEBUG ) { console.log( 'Add proxy path.', svgViewBox, svgCenter ); }
-
- let proxyPointsGroup = $(newProxyPathGroup).find( PROXY_POINTS_GROUP_SELECTOR );
- let proxyLinesGroup = $(newProxyPathGroup).find( PROXY_LINES_GROUP_SELECTOR );
-
- if ( proxyPathType == ProxyPathType.OPEN ) {
-
- const leftSvgPoint = {
- x: svgCenter.x - svgUnitRadius.x,
- y: svgCenter.y,
- };
- const rightSvgPoint = {
- x: svgCenter.x + svgUnitRadius.x,
- y: svgCenter.y,
- };
-
- let beforeProxyPoint = createProxyPathProxyPoint( leftSvgPoint.x, leftSvgPoint.y );
- let afterProxyPoint = createProxyPathProxyPoint( rightSvgPoint.x, rightSvgPoint.y );
- proxyPointsGroup.append( beforeProxyPoint );
- proxyPointsGroup.append( afterProxyPoint );
-
- let newProxyLine = createProxyPathLine( beforeProxyPoint, afterProxyPoint,
- leftSvgPoint.x, leftSvgPoint.y,
- rightSvgPoint.x, rightSvgPoint.y );
- $(proxyLinesGroup).append( newProxyLine );
-
- addProxyPointEventHandler( beforeProxyPoint, null, newProxyLine );
- addProxyPointEventHandler( afterProxyPoint, newProxyLine, null );
-
- } else if ( proxyPathType == ProxyPathType.CLOSED ) {
-
- const topLeftSvgPoint = {
- x: svgCenter.x - svgUnitRadius.x,
- y: svgCenter.y - svgUnitRadius.y,
- };
- const topRightSvgPoint = {
- x: svgCenter.x + svgUnitRadius.x,
- y: svgCenter.y - svgUnitRadius.y,
- };
- const bottomRightSvgPoint = {
- x: svgCenter.x + svgUnitRadius.x,
- y: svgCenter.y + svgUnitRadius.y,
- };
- const bottomLeftSvgPoint = {
- x: svgCenter.x - svgUnitRadius.x,
- y: svgCenter.y + svgUnitRadius.y,
- };
-
- let topLeftProxyPoint = createProxyPathProxyPoint( topLeftSvgPoint.x,
- topLeftSvgPoint.y );
- let topRightProxyPoint = createProxyPathProxyPoint( topRightSvgPoint.x,
- topRightSvgPoint.y );
- let bottomRightProxyPoint = createProxyPathProxyPoint( bottomRightSvgPoint.x,
- bottomRightSvgPoint.y );
- let bottomLeftProxyPoint = createProxyPathProxyPoint( bottomLeftSvgPoint.x,
- bottomLeftSvgPoint.y );
- proxyPointsGroup.append( topLeftProxyPoint );
- proxyPointsGroup.append( topRightProxyPoint );
- proxyPointsGroup.append( bottomRightProxyPoint );
- proxyPointsGroup.append( bottomLeftProxyPoint );
-
- let topProxyLine = createProxyPathLine( topLeftProxyPoint, topRightProxyPoint,
- topLeftSvgPoint.x, topLeftSvgPoint.y,
- topRightSvgPoint.x, topRightSvgPoint.y );
- let rightProxyLine = createProxyPathLine( topRightProxyPoint, bottomRightProxyPoint,
- topRightSvgPoint.x, topRightSvgPoint.y,
- bottomRightSvgPoint.x, bottomRightSvgPoint.y );
- let bottomProxyLine = createProxyPathLine( bottomRightProxyPoint, bottomLeftProxyPoint,
- bottomRightSvgPoint.x, bottomRightSvgPoint.y,
- bottomLeftSvgPoint.x, bottomLeftSvgPoint.y );
- let leftProxyLine = createProxyPathLine( bottomLeftProxyPoint, topLeftProxyPoint,
- bottomLeftSvgPoint.x, bottomLeftSvgPoint.y,
- topLeftSvgPoint.x, topLeftSvgPoint.y );
- $(proxyLinesGroup).append( topProxyLine );
- $(proxyLinesGroup).append( rightProxyLine );
- $(proxyLinesGroup).append( bottomProxyLine );
- $(proxyLinesGroup).append( leftProxyLine );
-
- addProxyPointEventHandler( topLeftProxyPoint, leftProxyLine, topProxyLine );
- addProxyPointEventHandler( topRightProxyPoint, topProxyLine, rightProxyLine );
- addProxyPointEventHandler( bottomRightProxyPoint, rightProxyLine, bottomProxyLine );
- addProxyPointEventHandler( bottomLeftProxyPoint, bottomProxyLine, leftProxyLine );
-
- } else {
- console.log( `Unknown proxy path type: ${proxyPathType}` );
- }
- saveSvgPath();
+ let proxyPathContainer = $('#' + PROXY_PATH_CONTAINER_ID );
+ let firstProxyPath = $(proxyPathContainer).find( PROXY_PATH_GROUP_SELECTOR ).first();
+ let proxyPathType = $(firstProxyPath).attr( PROXY_PATH_TYPE_ATTR );
+ let newProxyPathGroup = createProxyPathGroup( proxyPathType );
+ $(proxyPathContainer).append( newProxyPathGroup );
+
+ const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
+ const svgViewBox = Hi.svgUtils.getSvgViewBox( baseSvgElement );
+ let svgCenter = {
+ x: svgViewBox.x + ( svgViewBox.width / 2 ),
+ y: svgViewBox.y + ( svgViewBox.height / 2 )
+ };
+ let svgUnitRadius = {
+ x: svgViewBox.width * ( PATH_EDIT_NEW_PATH_RADIUS_PERCENT / 100.0 ),
+ y: svgViewBox.height * ( PATH_EDIT_NEW_PATH_RADIUS_PERCENT / 100.0 )
+ };
+
+ if ( Hi.DEBUG ) { console.log( 'Add proxy path.', svgViewBox, svgCenter ); }
+
+ let proxyPointsGroup = $(newProxyPathGroup).find( PROXY_POINTS_GROUP_SELECTOR );
+ let proxyLinesGroup = $(newProxyPathGroup).find( PROXY_LINES_GROUP_SELECTOR );
+
+ if ( proxyPathType == ProxyPathType.OPEN ) {
+
+ const leftSvgPoint = {
+ x: svgCenter.x - svgUnitRadius.x,
+ y: svgCenter.y,
+ };
+ const rightSvgPoint = {
+ x: svgCenter.x + svgUnitRadius.x,
+ y: svgCenter.y,
+ };
+
+ let beforeProxyPoint = createProxyPathProxyPoint( leftSvgPoint.x, leftSvgPoint.y );
+ let afterProxyPoint = createProxyPathProxyPoint( rightSvgPoint.x, rightSvgPoint.y );
+ proxyPointsGroup.append( beforeProxyPoint );
+ proxyPointsGroup.append( afterProxyPoint );
+
+ let newProxyLine = createProxyPathLine( beforeProxyPoint, afterProxyPoint,
+ leftSvgPoint.x, leftSvgPoint.y,
+ rightSvgPoint.x, rightSvgPoint.y );
+ $(proxyLinesGroup).append( newProxyLine );
+
+ addProxyPointEventHandler( beforeProxyPoint, null, newProxyLine );
+ addProxyPointEventHandler( afterProxyPoint, newProxyLine, null );
+
+ } else if ( proxyPathType == ProxyPathType.CLOSED ) {
+
+ const topLeftSvgPoint = {
+ x: svgCenter.x - svgUnitRadius.x,
+ y: svgCenter.y - svgUnitRadius.y,
+ };
+ const topRightSvgPoint = {
+ x: svgCenter.x + svgUnitRadius.x,
+ y: svgCenter.y - svgUnitRadius.y,
+ };
+ const bottomRightSvgPoint = {
+ x: svgCenter.x + svgUnitRadius.x,
+ y: svgCenter.y + svgUnitRadius.y,
+ };
+ const bottomLeftSvgPoint = {
+ x: svgCenter.x - svgUnitRadius.x,
+ y: svgCenter.y + svgUnitRadius.y,
+ };
+
+ let topLeftProxyPoint = createProxyPathProxyPoint( topLeftSvgPoint.x,
+ topLeftSvgPoint.y );
+ let topRightProxyPoint = createProxyPathProxyPoint( topRightSvgPoint.x,
+ topRightSvgPoint.y );
+ let bottomRightProxyPoint = createProxyPathProxyPoint( bottomRightSvgPoint.x,
+ bottomRightSvgPoint.y );
+ let bottomLeftProxyPoint = createProxyPathProxyPoint( bottomLeftSvgPoint.x,
+ bottomLeftSvgPoint.y );
+ proxyPointsGroup.append( topLeftProxyPoint );
+ proxyPointsGroup.append( topRightProxyPoint );
+ proxyPointsGroup.append( bottomRightProxyPoint );
+ proxyPointsGroup.append( bottomLeftProxyPoint );
+
+ let topProxyLine = createProxyPathLine( topLeftProxyPoint, topRightProxyPoint,
+ topLeftSvgPoint.x, topLeftSvgPoint.y,
+ topRightSvgPoint.x, topRightSvgPoint.y );
+ let rightProxyLine = createProxyPathLine( topRightProxyPoint, bottomRightProxyPoint,
+ topRightSvgPoint.x, topRightSvgPoint.y,
+ bottomRightSvgPoint.x, bottomRightSvgPoint.y );
+ let bottomProxyLine = createProxyPathLine( bottomRightProxyPoint, bottomLeftProxyPoint,
+ bottomRightSvgPoint.x, bottomRightSvgPoint.y,
+ bottomLeftSvgPoint.x, bottomLeftSvgPoint.y );
+ let leftProxyLine = createProxyPathLine( bottomLeftProxyPoint, topLeftProxyPoint,
+ bottomLeftSvgPoint.x, bottomLeftSvgPoint.y,
+ topLeftSvgPoint.x, topLeftSvgPoint.y );
+ $(proxyLinesGroup).append( topProxyLine );
+ $(proxyLinesGroup).append( rightProxyLine );
+ $(proxyLinesGroup).append( bottomProxyLine );
+ $(proxyLinesGroup).append( leftProxyLine );
+
+ addProxyPointEventHandler( topLeftProxyPoint, leftProxyLine, topProxyLine );
+ addProxyPointEventHandler( topRightProxyPoint, topProxyLine, rightProxyLine );
+ addProxyPointEventHandler( bottomRightProxyPoint, rightProxyLine, bottomProxyLine );
+ addProxyPointEventHandler( bottomLeftProxyPoint, bottomProxyLine, leftProxyLine );
+
+ } else {
+ console.log( `Unknown proxy path type: ${proxyPathType}` );
+ }
+ saveSvgPath();
}
function removeProxyPathIfAllowed( targetProxyPathGroup ) {
- let proxyPathContainer = $('#' + PROXY_PATH_CONTAINER_ID );
- let proxyPathGroups = $(proxyPathContainer).find( PROXY_PATH_GROUP_SELECTOR );
- if ( proxyPathGroups.length < 2 ) {
- return;
- }
- $(targetProxyPathGroup).remove();
- setSelectedProxyElement( null );
- saveSvgPath();
+ let proxyPathContainer = $('#' + PROXY_PATH_CONTAINER_ID );
+ let proxyPathGroups = $(proxyPathContainer).find( PROXY_PATH_GROUP_SELECTOR );
+ if ( proxyPathGroups.length < 2 ) {
+ return;
+ }
+ $(targetProxyPathGroup).remove();
+ setSelectedProxyElement( null );
+ saveSvgPath();
}
function createProxyPathGroup( proxyPathType ) {
- let proxyPathGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
- proxyPathGroup.setAttribute('id', Hi.generateUniqueId() );
- proxyPathGroup.setAttribute('class', PROXY_PATH_CLASS );
- proxyPathGroup.setAttribute( PROXY_PATH_TYPE_ATTR, proxyPathType );
+ let proxyPathGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
+ proxyPathGroup.setAttribute('id', Hi.generateUniqueId() );
+ proxyPathGroup.setAttribute('class', PROXY_PATH_CLASS );
+ proxyPathGroup.setAttribute( PROXY_PATH_TYPE_ATTR, proxyPathType );
- // Lines should come before points so mouse clicks land on points before lines.
- let proxyLinesGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
- proxyLinesGroup.setAttribute('class', PROXY_LINES_CLASS );
- proxyPathGroup.appendChild( proxyLinesGroup );
+ // Lines should come before points so mouse clicks land on points before lines.
+ let proxyLinesGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
+ proxyLinesGroup.setAttribute('class', PROXY_LINES_CLASS );
+ proxyPathGroup.appendChild( proxyLinesGroup );
- let proxyPointsGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
- proxyPointsGroup.setAttribute('class', PROXY_POINTS_CLASS );
- proxyPathGroup.appendChild( proxyPointsGroup );
+ let proxyPointsGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
+ proxyPointsGroup.setAttribute('class', PROXY_POINTS_CLASS );
+ proxyPathGroup.appendChild( proxyPointsGroup );
- return proxyPathGroup;
+ return proxyPathGroup;
}
function createProxyPathProxyPoint( cx, cy ) {
- const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
- const pixelsPerSvgUnit = Hi.svgUtils.getPixelsPerSvgUnit( baseSvgElement );
- const svgRadius = PATH_EDIT_PROXY_POINT_RADIUS_PIXELS / pixelsPerSvgUnit.scaleX;
-
- const proxyPoint = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
- proxyPoint.setAttribute('cx', cx);
- proxyPoint.setAttribute('cy', cy);
- proxyPoint.setAttribute('r', svgRadius);
- proxyPoint.setAttribute('id', Hi.generateUniqueId() );
- $(proxyPoint).addClass( 'draggable');
- $(proxyPoint).addClass( PROXY_ITEM_CLASS );
- $(proxyPoint).addClass( PROXY_POINT_CLASS );
- proxyPoint.setAttribute('fill', PATH_EDIT_PROXY_POINT_COLOR );
- proxyPoint.setAttribute('vector-effect', 'non-scaling-stroke');
- return proxyPoint;
+ const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
+ const pixelsPerSvgUnit = Hi.svgUtils.getPixelsPerSvgUnit( baseSvgElement );
+ const svgRadius = PATH_EDIT_PROXY_POINT_RADIUS_PIXELS / pixelsPerSvgUnit.scaleX;
+
+ const proxyPoint = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
+ proxyPoint.setAttribute('cx', cx);
+ proxyPoint.setAttribute('cy', cy);
+ proxyPoint.setAttribute('r', svgRadius);
+ proxyPoint.setAttribute('id', Hi.generateUniqueId() );
+ $(proxyPoint).addClass( 'draggable');
+ $(proxyPoint).addClass( PROXY_ITEM_CLASS );
+ $(proxyPoint).addClass( PROXY_POINT_CLASS );
+ proxyPoint.setAttribute('fill', PATH_EDIT_PROXY_POINT_COLOR );
+ proxyPoint.setAttribute('vector-effect', 'non-scaling-stroke');
+ return proxyPoint;
}
function createProxyPathLine( beforeProxyPoint, afterProxyPoint, x1, y1, x2, y2, ) {
- const proxyLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
- proxyLine.setAttribute('x1', x1);
- proxyLine.setAttribute('y1', y1);
- proxyLine.setAttribute('x2', x2);
- proxyLine.setAttribute('y2', y2);
- $(proxyLine).addClass( PROXY_ITEM_CLASS );
- $(proxyLine).addClass( PROXY_LINE_CLASS );
- proxyLine.setAttribute( BEFORE_PROXY_POINT_ID, $(beforeProxyPoint).attr('id') );
- proxyLine.setAttribute( AFTER_PROXY_POINT_ID, $(afterProxyPoint).attr('id'));
- proxyLine.setAttribute('stroke', PATH_EDIT_PROXY_LINE_COLOR );
- proxyLine.setAttribute('stroke-width', PATH_EDIT_PROXY_LINE_WIDTH_PIXELS );
- proxyLine.setAttribute('vector-effect', 'non-scaling-stroke');
- return proxyLine;
+ const proxyLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
+ proxyLine.setAttribute('x1', x1);
+ proxyLine.setAttribute('y1', y1);
+ proxyLine.setAttribute('x2', x2);
+ proxyLine.setAttribute('y2', y2);
+ $(proxyLine).addClass( PROXY_ITEM_CLASS );
+ $(proxyLine).addClass( PROXY_LINE_CLASS );
+ proxyLine.setAttribute( BEFORE_PROXY_POINT_ID, $(beforeProxyPoint).attr('id') );
+ proxyLine.setAttribute( AFTER_PROXY_POINT_ID, $(afterProxyPoint).attr('id'));
+ proxyLine.setAttribute('stroke', PATH_EDIT_PROXY_LINE_COLOR );
+ proxyLine.setAttribute('stroke-width', PATH_EDIT_PROXY_LINE_WIDTH_PIXELS );
+ proxyLine.setAttribute('vector-effect', 'non-scaling-stroke');
+ return proxyLine;
}
function addProxyPointEventHandler( proxyPoint, beforeProxyLine, afterProxyLine ) {
- // Drag logic for the proxy point
- $(proxyPoint).on('mousedown', function( event ) {
+ // Drag logic for the proxy point
+ $(proxyPoint).on('mousedown', function( event ) {
event.preventDefault();
- event.stopImmediatePropagation();
+ event.stopImmediatePropagation();
- let startMousePosition = {
- x: event.clientX,
- y: event.clientY
- };
+ let startMousePosition = {
+ x: event.clientX,
+ y: event.clientY
+ };
- const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
+ const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
const eventSvgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement, event.clientX, event.clientY );
-
+
const offsetX = eventSvgPoint.x - parseFloat($(proxyPoint).attr('cx'));
const offsetY = eventSvgPoint.y - parseFloat($(proxyPoint).attr('cy'));
- let isDragging = false;
-
+ let isDragging = false;
+
// Function to handle mouse movement
function onMouseMove( event ) {
- if ( ! gSvgPathEditData ) {
- return;
- }
-
- let currentMousePosition = {
- x: event.clientX,
- y: event.clientY
- };
- const distanceX = Math.abs( currentMousePosition.x - startMousePosition.x );
- const distanceY = Math.abs( currentMousePosition.y - startMousePosition.y );
-
- if ( isDragging
- || ( distanceX > CURSOR_MOVEMENT_THRESHOLD_PIXELS )
- || ( distanceY > CURSOR_MOVEMENT_THRESHOLD_PIXELS )) {
- isDragging = true;
- event.preventDefault();
- event.stopImmediatePropagation();
-
- const eventSvgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement,
- event.clientX,
- event.clientY );
-
- gSvgPathEditData.dragProxyPoint = event.target;
- const newCx = eventSvgPoint.x - offsetX;
- const newCy = eventSvgPoint.y - offsetY;
- $(proxyPoint).attr('cx', newCx).attr('cy', newCy);
-
- // Update the line endpoints to follow proxy point movement
- if ( $(beforeProxyLine).length > 0 ) {
- $(beforeProxyLine).attr('x2', newCx).attr('y2', newCy);
- }
- if ( $(afterProxyLine).length > 0 ) {
- $(afterProxyLine).attr('x1', newCx).attr('y1', newCy);
- }
-
- setSelectedProxyElement(proxyPoint);
- }
+ if ( ! gSvgPathEditData ) {
+ return;
+ }
+
+ let currentMousePosition = {
+ x: event.clientX,
+ y: event.clientY
+ };
+ const distanceX = Math.abs( currentMousePosition.x - startMousePosition.x );
+ const distanceY = Math.abs( currentMousePosition.y - startMousePosition.y );
+
+ if ( isDragging
+ || ( distanceX > CURSOR_MOVEMENT_THRESHOLD_PIXELS )
+ || ( distanceY > CURSOR_MOVEMENT_THRESHOLD_PIXELS )) {
+ isDragging = true;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+
+ const eventSvgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement,
+ event.clientX,
+ event.clientY );
+
+ gSvgPathEditData.dragProxyPoint = event.target;
+ const newCx = eventSvgPoint.x - offsetX;
+ const newCy = eventSvgPoint.y - offsetY;
+ $(proxyPoint).attr('cx', newCx).attr('cy', newCy);
+
+ // Update the line endpoints to follow proxy point movement
+ if ( $(beforeProxyLine).length > 0 ) {
+ $(beforeProxyLine).attr('x2', newCx).attr('y2', newCy);
+ }
+ if ( $(afterProxyLine).length > 0 ) {
+ $(afterProxyLine).attr('x1', newCx).attr('y1', newCy);
+ }
+
+ setSelectedProxyElement(proxyPoint);
+ }
}
// Function to handle mouse up (end of drag)
function onMouseUp( event ) {
- if ( ! gSvgPathEditData ) {
- return;
- }
-
- event.preventDefault();
- event.stopImmediatePropagation();
- saveSvgPath();
- gSvgPathEditData.dragProxyPoint = null;
- if ( isDragging ) {
- gIgnoreCLick = true;
- }
- $(document).off('mousemove', onMouseMove);
- $(document).off('mouseup', onMouseUp);
+ if ( ! gSvgPathEditData ) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ saveSvgPath();
+ gSvgPathEditData.dragProxyPoint = null;
+ if ( isDragging ) {
+ gIgnoreCLick = true;
+ }
+ $(document).off('mousemove', onMouseMove);
+ $(document).off('mouseup', onMouseUp);
}
// Bind the mousemove and mouseup handlers using jQuery
$(document).on('mousemove', onMouseMove);
$(document).on('mouseup', onMouseUp);
- });
+ });
}
function collapseSvgPath( ) {
- if ( Hi.DEBUG ) { console.log( 'Collapse SVG Path' ); }
+ if ( Hi.DEBUG ) { console.log( 'Collapse SVG Path' ); }
- let newSvgPath = getSvgPathStringFromProxyPaths();
- $(gSelectedPathSvgGroup).find('path').attr( 'd', newSvgPath );
+ let newSvgPath = getSvgPathStringFromProxyPaths();
+ $(gSelectedPathSvgGroup).find('path').attr( 'd', newSvgPath );
- const proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
- $(proxyPathContainer).remove();
+ const proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
+ $(proxyPathContainer).remove();
- gSelectedPathSvgGroup.show();
+ gSelectedPathSvgGroup.show();
- gSvgPathEditData = null;
+ gSvgPathEditData = null;
}
function saveSvgPath() {
- if ( ! gSelectedPathSvgGroup ) {
- return;
- }
-
- let svgItemId = $(gSelectedPathSvgGroup).attr('id');
- let svgPathString = getSvgPathStringFromProxyPaths();
- let data = {
- svg_path: svgPathString
- };
- AN.post( `${API_EDIT_SVG_PATH_URL}/${svgItemId}`, data );
+ if ( ! gSelectedPathSvgGroup ) {
+ return;
+ }
+
+ let svgItemId = $(gSelectedPathSvgGroup).attr('id');
+ let svgPathString = getSvgPathStringFromProxyPaths();
+ let data = {
+ svg_path: svgPathString
+ };
+ AN.post( `${API_EDIT_SVG_PATH_URL}/${svgItemId}`, data );
}
function getSvgPathStringFromProxyPaths() {
- const proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
- const proxyPathGroups = $(proxyPathContainer).find( PROXY_PATH_GROUP_SELECTOR );
-
- let pathString = '';
- $(proxyPathGroups).each(function( index, proxyPathGroup ) {
-
- let proxyPoints = $(proxyPathGroup).find( PROXY_POINT_SELECTOR );
- $(proxyPoints).each(function( index, proxyPoint ) {
- if ( index == 0 ) {
- pathString += ' M ';
- } else {
- pathString += ' L ';
- }
- pathString += proxyPoint.getAttribute('cx') + ',' + proxyPoint.getAttribute('cy');
- });
- if ( $(proxyPathGroup).attr( PROXY_PATH_TYPE_ATTR ) == ProxyPathType.CLOSED ) {
- pathString += ' Z';
- }
-
- });
-
- console.log( `PATH = ${pathString}` );
- return pathString;
+ const proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
+ const proxyPathGroups = $(proxyPathContainer).find( PROXY_PATH_GROUP_SELECTOR );
+
+ let pathString = '';
+ $(proxyPathGroups).each(function( index, proxyPathGroup ) {
+
+ let proxyPoints = $(proxyPathGroup).find( PROXY_POINT_SELECTOR );
+ $(proxyPoints).each(function( index, proxyPoint ) {
+ if ( index == 0 ) {
+ pathString += ' M ';
+ } else {
+ pathString += ' L ';
+ }
+ pathString += proxyPoint.getAttribute('cx') + ',' + proxyPoint.getAttribute('cy');
+ });
+ if ( $(proxyPathGroup).attr( PROXY_PATH_TYPE_ATTR ) == ProxyPathType.CLOSED ) {
+ pathString += ' Z';
+ }
+
+ });
+
+ console.log( `PATH = ${pathString}` );
+ return pathString;
}
function getReferenceElementForExtendingProxyPath( ) {
- if ( gSvgPathEditData.selectedProxyElement ) {
- return gSvgPathEditData.selectedProxyElement;
- }
- let lastProxyPath = $(gSvgPathEditData.proxyPathContainer).find( PROXY_PATH_GROUP_SELECTOR ).last();
- let lastProxyPoint = lastProxyPath.find( PROXY_POINT_SELECTOR ).last();
- return lastProxyPoint;
+ if ( gSvgPathEditData.selectedProxyElement ) {
+ return gSvgPathEditData.selectedProxyElement;
+ }
+ let lastProxyPath = $(gSvgPathEditData.proxyPathContainer).find( PROXY_PATH_GROUP_SELECTOR ).last();
+ let lastProxyPoint = lastProxyPath.find( PROXY_POINT_SELECTOR ).last();
+ return lastProxyPoint;
}
function getPrecedingProxyLine( proxyPoint ) {
- const proxyPointId = $(proxyPoint).attr('id');
- return $('line[' + AFTER_PROXY_POINT_ID + '="' + proxyPointId + '"]');
+ const proxyPointId = $(proxyPoint).attr('id');
+ return $('line[' + AFTER_PROXY_POINT_ID + '="' + proxyPointId + '"]');
}
function getFollowingProxyLine( proxyPoint ) {
- const proxyPointId = $(proxyPoint).attr('id');
- return $('line[' + BEFORE_PROXY_POINT_ID + '="' + proxyPointId + '"]');
+ const proxyPointId = $(proxyPoint).attr('id');
+ return $('line[' + BEFORE_PROXY_POINT_ID + '="' + proxyPointId + '"]');
}
})();