Skip to content

Home Information - Your home, your data, organized.

Python

New background SVG editor (#276)

Tony C8151961fecff
diff --git a/README.md b/README.md
index 9748f374..08b0a4b7 100644
--- a/README.md
+++ b/README.md
@@ -49,7 +49,7 @@ The install script automatically handles everything: Docker setup verification,
**Visual Organization:**
- Position items exactly where they belong on floor plans or property maps
- Create multiple views (whole house, kitchen only, security zones, etc.)
-- Upload custom background images of your actual property
+- Customize the floor plan to match your home and property
**Home Automation Integration:**
- Control lights, switches, and devices through [Home Assistant](docs/Integrations.md)
diff --git a/docs/CustomBackgrounds.md b/docs/CustomBackgrounds.md
index 4a42c62a..097eb55c 100644
--- a/docs/CustomBackgrounds.md
+++ b/docs/CustomBackgrounds.md
@@ -1,66 +1,87 @@
<img src="../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-# Custom Background Images
-
-## Core Requirements
-
-- Images must be in the SVG format.
-- Must be well defined SVG structure.
-- Recommended viewbox sizes in the 1500 to 3000 range.
-- Any aspect ratio.
-
-## Considerations
-
-- Lighter, uncluttered images since all items get displayed over it.
-- The fancier the SVG features you include, the less likely it has been tested in this app.
-
-## Recommended Styling
-
-If you use `<path>` drawing elements in the SVG, you can give then one of the pre-defined `class` atributes ot get some default styling. e.g.,
-```
-<path class="grass" ...>
-...
-</path>
-```
-
-The predefined classes are:
-```
-asphalt
-bathtubs
-brick
-ceiling-transitions
-countertops
-dead-space
-door-arcs
-doors
-exterior-walls
-fencing
-fireplaces
-floor-transitions
-foliage
-furniture
-grass
-gravel
-ground
-interior-floors
-interior-walls
-landscape-transitions
-mulch
-pavement
-pavers
-pool-coping
-property-lines
-rock-beds
-secondary-walls
-sheds
-shelves
-sinks
-stairs
-stone-walls
-tiles
-toilets
-utilities
-water
-windows
-wood-decks
-```
+# Creating Floor Plans
+
+Home Information includes a built-in floor plan editor that lets you draw your home's layout directly in the app. No external design tools needed — you can create walls, doors, windows, floors, and landscape elements all from your browser or tablet.
+
+If you'd rather not draw your own, you can pick from a set of predefined templates or upload an SVG file you've created elsewhere.
+
+![Floor plan editor](img/screenshots/floor-plan-editor.png)
+*The floor plan editor with the element palette across the top*
+
+## Getting Started
+
+The floor plan is the background image for each Space (Location) in the app. To create or change it:
+
+1. Enter **Edit Mode** using the Edit button
+2. Select the Space you want to edit in the header dropdown
+3. Click to edit the Space (next to header dropdown)
+4. Click the **BACKGROUND IMAGE** button in the Space properties panel sidebar
+5. Choose **Edit Current** to open the floor plan editor from modal selection
+
+![Background Image button](img/screenshots/background-image-button.png)
+*The Background Image button in the Space properties panel*
+
+From the Background Image dialog, you can also:
+- **Choose a Template** — pick from predefined floor plans to use as-is or as a starting point
+- **Upload SVG** — use an SVG file created in an external tool
+
+## The Floor Plan Editor
+
+The editor is a full-screen workspace with your floor plan in the center, an element palette across the top, and controls in the header and footer.
+
+### Adding Elements
+
+Drag any element from the palette and drop it onto the canvas. Elements are organized into three categories:
+
+- **Structural** — walls, floors, doors, windows
+- **Features** — countertops, fireplaces, stairs, shelves, cabinets
+- **Exterior** — grass, ground, pavement, deck, fencing, property lines
+
+![Palette drag and drop](img/screenshots/palette-drag-drop.png)
+*Dragging a wall element from the palette onto the canvas*
+
+### Editing Elements
+
+Click any element to select it. Walls, floors, and areas show red vertex points that you can drag to reshape. Doors and windows can be dragged to reposition, and scaled or rotated using keyboard shortcuts.
+
+Use **Ctrl+drag** on a vertex to move an entire wall or floor without reshaping it. Press **m** to mirror a door or window horizontally.
+
+The **HELP** button in the footer bar shows the complete list of keyboard shortcuts and editing commands.
+
+### Navigating the Canvas
+
+Zoom with the mouse wheel or **+** / **-** keys. Click and drag on empty space to pan.
+
+## Saving Your Work
+
+Changes are auto-saved as you work. When you're done:
+
+- **DONE** — saves your changes and returns to the normal view
+- **CANCEL** — discards all changes since you entered the editor
+- **REVERT** — discards changes but stays in the editor (start over)
+
+Your changes are saved to a draft while editing. If your browser closes unexpectedly, your work is preserved — the editor will resume where you left off next time you open it.
+
+## Templates
+
+The template selector shows visual previews of all available floor plans. Selecting a template replaces the current background.
+
+![Template selector](img/screenshots/template-selector.png)
+*Choosing from predefined floor plan templates*
+
+Templates are a good starting point — select one that roughly matches your layout, then use the editor to customize it.
+
+## Tips
+
+- **Start with the outline** — draw exterior walls first to establish the shape of your home, then add interior walls, floors, and openings.
+- **Zoom in** for detail work on doors and windows.
+- **You can always come back** — the editor is available any time from Edit Mode.
+
+## Uploading External SVGs
+
+If you have an SVG file from another tool (an architect's floor plan, a tracing, etc.), you can upload it via the **Upload SVG** option in the Background Image dialog. Uploaded SVGs render as the background, and you can add editor elements on top of them. Note that elements in uploaded SVGs cannot be individually edited — only elements added through the editor are editable.
+
+## Exporting
+
+The **EXPORT** button in the editor footer downloads your floor plan as a standalone SVG file. This is useful for sharing floor plans with others or backing up your work.
diff --git a/docs/Editing.md b/docs/Editing.md
index 089570bd..de5fa872 100644
--- a/docs/Editing.md
+++ b/docs/Editing.md
@@ -1,8 +1,8 @@
<img src="../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-# Layout Editor
+# Item Layout Editor
-This page provides an overview of the editing mode features and basic operations. Editing mode is not the main mode used day-to-day. It is only used to initially setup you home and then occasionally to adjust the layout and add/remove items.
+This page provides an overview of the item editing mode features and basic operations. Editing mode is not the main mode used day-to-day. It is only used to initially setup you home and then occasionally to adjust the layout and add/remove items.
You enter edit mode with the "EDIT" button near the top right of the screen.
@@ -118,11 +118,9 @@ Below is the Attic space's view after using a custom SVG background and adding t
## Custom Background Images
-When creating a new space, you get the option to add a custom background image. However, you can also change the background image at any time by choosing "EDIT" by the space name.
+When creating a new space, you get a blank floor plan background to start. You can then customize this by using the Background Editor, choosing from a list of predefined templates or even upload your own SVG background image.
-<img src="img/editing/location-layout-edit-button-1024x768.png" alt="location-layout-edit-button-1024x768.png" width="250" />
+<img src="img/editing/location-layout-edit-button-1024x768.png" alt="location-layout-edit-button-1024x768.png" width="250" /> &nbsp; <img src="img/editing/location-layout-edit-1024x768.png" alt="location-layout-edit-1024x768.png" width="400" />
-<img src="img/editing/location-layout-edit-1024x768.png" alt="location-layout-edit-1024x768.png" width="400" />
-
-To create your own custom background image, see the [Custom Background Image Page](CustomBackgrounds.md).
+For more details, see the [Custom Background Image Page](CustomBackgrounds.md).
diff --git a/docs/GettingStarted.md b/docs/GettingStarted.md
index 044e03b9..cd396566 100644
--- a/docs/GettingStarted.md
+++ b/docs/GettingStarted.md
@@ -6,7 +6,7 @@ Once successfully running (see the [Installation Page](Installation.md)), you wi
<img src="img/getting-started/start-page-1024x768.png" alt="Home Information Start Page" width="400">
-Choose which home type you want to use. If you choose "Single Story", you will see this initial screen with some common household items pre-populated.
+Choose which home type you want to use. If you choose "Two Story", you will see this initial screen with some common household items pre-populated.
<img src="img/getting-started/initial-view-1024x768.png" alt="initial-view-1024x768" width="400" />
@@ -30,7 +30,7 @@ Some information may not be associated with an individual item, but the home ove
## Multiple Spaces
-If you have a multi-story house, basement, attic or even another vacation home or second property, you can create a different "space" for that. Here we have an extra space defined for the attic.
+If you have a multi-story house, basement, attic or even another vacation home or second property, you can create a different "space" for that. Here we have an extra space defined for the second floor rooms and crawl spaces.
<img src="img/getting-started/spaces-dropdown-1024x768.png" alt="spaces-dropdown-1024x768" width="250" /> &nbsp; <img src="img/getting-started/view-second-space-1024x768.png" alt="view-second-space-1024x768" width="300" />
diff --git a/docs/dev/Setup.md b/docs/dev/Setup.md
index f713875c..8452ff65 100644
--- a/docs/dev/Setup.md
+++ b/docs/dev/Setup.md
@@ -204,17 +204,21 @@ make docker-run # Background
make docker-stop
```
-### Documentation
+### Documentation Preview
-Use `grip` for previewing GitHub markdown documents locally.
+To preview GitHub-flavored markdown locally before committing, we recommend
+VS Code with the
+[Markdown Preview Github Styling](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-preview-github-styles)
+extension. It renders markdown with GitHub's CSS locally — no API calls or
+additional dependencies needed.
-```
-sudo apt install grip
-cd $PROJ_DIR
-grip
+If you already use VS Code for this project, install the extension and open
+any `.md` file with `Ctrl+Shift+V` to preview (or `Ctrl+K V` for side-by-side).
-# Then visit:
-http://localhost:6419
+If you use a different editor for development, you can open this project in
+a separate VS Code window just for markdown editing:
+```bash
+code -n $PROJ_DIR
```
## Getting Started
diff --git a/docs/dev/domain/profile-management.md b/docs/dev/domain/profile-management.md
new file mode 100644
index 00000000..73448596
--- /dev/null
+++ b/docs/dev/domain/profile-management.md
@@ -0,0 +1,137 @@
+# Profile Management
+
+## Overview
+
+Profiles are predefined configurations that create a fully populated Home Information setup — Locations with background SVGs, LocationViews with zoom/pan settings, Entities with positions, and Collections. They provide the first-time user experience when a user selects a home type (Single Story, Two Story, Apartment) on the welcome page.
+
+## Profile Structure
+
+### JSON Format
+
+Profile data is stored as JSON files in `src/hi/apps/profiles/assets/profiles/`. Each file defines a complete set of Locations, Entities, and Collections.
+
+The field constants for the JSON structure are defined in `src/hi/apps/profiles/constants.py`. The JSON structure follows this hierarchy:
+
+```
+profile
+ ├── locations[]
+ │ ├── svg_template_name → references a background template
+ │ └── views[] → LocationViews with zoom/pan/rotate settings
+ ├── entities[]
+ │ ├── positions[] → placement on specific Locations
+ │ ├── paths[] → SVG paths on specific Locations
+ │ └── visible_in_views[] → which LocationViews show this entity
+ └── collections[]
+ ├── entities[] → entity names in this collection
+ ├── positions[] → collection positioning
+ └── visible_in_views[] → which LocationViews show this collection
+```
+
+### SVG Template References
+
+Each Location in the profile JSON has a `svg_template_name` field that references a Django template in the backgrounds directory (see [SVG Background System](svg-background-system.md) for template details). At profile load time, the template is rendered, processed, and written to MEDIA_ROOT. The viewBox is extracted from the rendered SVG — it is not stored in the JSON.
+
+### Profile Types
+
+Profile types are defined in `src/hi/apps/profiles/enums.py` (`ProfileType` enum). Each type maps to a JSON file via the `json_filename()` method.
+
+## Profile Loading
+
+Profile loading is handled by `ProfileManager` in `src/hi/apps/profiles/profile_manager.py`. The load process:
+
+1. Load the JSON file for the selected profile type
+2. Render SVG background templates and write to MEDIA_ROOT (`_render_svg_templates`)
+3. Create Location and LocationView database objects
+4. Create Entity objects with positions and paths
+5. Create Collection objects with entity assignments and positioning
+6. Set up entity and collection visibility in LocationViews
+
+The `_render_svg_templates` method uses `LocationManager.render_svg_template_to_media()` which renders the Django template, runs it through the SVG processing pipeline, and writes the fragment to MEDIA_ROOT. The rendered filename and extracted viewBox are stored as temporary fields on the location data dict for use during Location creation.
+
+### Error Handling
+
+`ProfileManager` has both strict (`load_profile`) and robust (`load_profile_robust`) loading modes. The robust mode tracks statistics via `ProfileLoadingStats` and continues past individual failures, useful for development and testing.
+
+## Creating a New Profile
+
+### Workflow
+
+The goal is to arrive at a fully configured database state that can be captured as a new profile. How you populate the data is flexible — the snapshot tool captures whatever is in the database.
+
+The typical workflow:
+
+1. **Start with an empty database** — delete existing data or use a fresh database.
+2. **Choose "Start with an empty layout"** on the welcome page. This puts you in edit mode with a blank Location.
+3. **Create the background SVG** for the first Location using the background editor. Use the palette to draw walls, floors, doors, windows, etc.
+4. **Add more Locations** if needed (e.g., second floor, attic, basement). Each gets its own background SVG.
+5. **Set up LocationViews** for each Location — configure zoom, pan, and rotation for different viewing perspectives (e.g., "Interior", "Exterior", "Kitchen").
+6. **Add Entities** — create all the entities that should be part of this profile. Position them on the appropriate Locations and assign them to LocationViews.
+7. **Add Collections** — group entities into collections, position collections, assign visibility.
+8. **Generate the snapshot** using the Profile Snapshot Generator (see below). Write to `/tmp` first for review.
+9. **Register the profile type** — add a new value to the `ProfileType` enum if this is a completely new profile type.
+10. **Commit** — once verified, generate with `output_to_tmp=False` to write the real profile files, then commit.
+
+## Updating an Existing Profile
+
+### Workflow
+
+When updating an existing profile, you want to start from the current profile state, make modifications, and re-capture.
+
+1. **Start with an empty database** — delete existing data or use a fresh database.
+2. **Choose the profile to update** on the welcome page (e.g., "Single Story"). This loads the existing profile with all its Locations, Entities, and Collections.
+3. **Modify as needed** — edit backgrounds, reposition entities, add/remove items, adjust views. The existing profile gives you the starting point so you only change what needs changing.
+4. **Generate the snapshot** — this captures the modified state. The SVG template reconciliation will match unchanged backgrounds to their existing templates and create new template files for any backgrounds you edited.
+5. **Review** — check the JSON and any new SVG template files in `/tmp`.
+6. **Commit** — generate with `output_to_tmp=False` and commit.
+
+## Profile Snapshot Generator
+
+The snapshot generator captures the current database state into a profile JSON file. It lives at `src/hi/apps/profiles/tests/devtools/profile_snapshot_generator.py`.
+
+### Usage
+
+From the Django shell:
+```python
+from hi.apps.profiles.tests.devtools.profile_snapshot_generator import ProfileSnapshotGenerator
+from hi.apps.profiles.enums import ProfileType
+
+generator = ProfileSnapshotGenerator()
+
+# Write to /tmp for review (safe — doesn't modify real profile files)
+output_path = generator.generate_snapshot(ProfileType.SINGLE_STORY, output_to_tmp=True)
+
+# Write directly to the real profile location (overwrites existing)
+output_path = generator.generate_snapshot(ProfileType.SINGLE_STORY, output_to_tmp=False)
+```
+
+### SVG Template Reconciliation
+
+When generating a snapshot, the generator must determine which background template each Location corresponds to. The Location model only stores a MEDIA_ROOT filename — there's no record of the originating template.
+
+The generator handles this by comparing the Location's SVG fragment content against all rendered background templates:
+
+- **Match found**: The JSON references the matched template name.
+- **No match**: The SVG has been customized. The generator creates a new template file by wrapping the fragment in an `<svg>` element with the viewBox and saving it to the backgrounds template directory (or `/tmp` if `output_to_tmp=True`).
+
+This is implemented in `_reconcile_svg_templates()` in the snapshot generator.
+
+### Review Checklist
+
+After generating a snapshot:
+
+1. **Review the JSON** — check the output file for correctness. Verify `svg_template_name` fields reference valid templates.
+2. **Review new SVG templates** — if the generator created new template files, open them in a browser to verify they render correctly.
+3. **Test the round-trip** — load the generated profile on a fresh database to verify it produces the expected result.
+
+## Key Files
+
+| File | Purpose |
+|------|---------|
+| `src/hi/apps/profiles/profile_manager.py` | Profile loading logic |
+| `src/hi/apps/profiles/constants.py` | JSON field name constants |
+| `src/hi/apps/profiles/enums.py` | ProfileType enum |
+| `src/hi/apps/profiles/assets/profiles/*.json` | Profile JSON data files |
+| `src/hi/apps/profiles/tests/devtools/profile_snapshot_generator.py` | Snapshot generation tool |
+| `src/hi/apps/profiles/templates/profiles/svg/backgrounds/` | Background SVG templates |
+| `src/hi/apps/location/location_manager.py` | SVG template rendering to MEDIA_ROOT |
+| `src/hi/apps/common/svg_utils.py` | SVG processing pipeline |
diff --git a/docs/dev/domain/svg-background-system.md b/docs/dev/domain/svg-background-system.md
new file mode 100644
index 00000000..f6d25190
--- /dev/null
+++ b/docs/dev/domain/svg-background-system.md
@@ -0,0 +1,130 @@
+# SVG Background System
+
+## Overview
+
+Each Location in Home Information has a background SVG image that provides the visual context for the spatial layout. The background SVG is rendered behind entity icons and paths. Users can customize their background using the built-in SVG editor, by selecting from predefined templates, or by uploading their own SVG files.
+
+## Architecture
+
+### Storage
+
+- **MEDIA_ROOT**: Background SVGs are stored as fragment files (inner content without the `<svg>` wrapper). The Location model's `svg_fragment_filename` field points to this file.
+- **Templates**: Predefined backgrounds are Django templates at `src/hi/apps/profiles/templates/profiles/svg/backgrounds/`. These are full SVG files (with `<svg>` wrapper and viewBox) that get rendered, stripped, and written to MEDIA_ROOT.
+- **Editor palette**: The shared palette definitions live at `src/hi/apps/location/templates/location/edit/svg/svg_edit_palette.svg`. This is injected into the editor's DOM at runtime by the editor canvas template (`src/hi/apps/location/templates/location/edit/panes/location_svg_edit_canvas.html`), not stored in the SVG files themselves.
+
+### SVG Processing Pipeline
+
+All SVG content (uploaded, template-rendered, or editor-saved) goes through `hi.apps.common.svg_utils.process_svg_content()` which validates structure, extracts the viewBox, strips the outer `<svg>` element, cleans XML namespaces, scans for dangerous elements, and generates a unique timestamped filename for MEDIA_ROOT.
+
+### Rendering
+
+The background SVG fragment is rendered via the `{% include_media_template %}` custom template tag (`hi.apps.common.templatetags.common_tags`), which reads from MEDIA_ROOT and renders as a Django template within the Location view's `<svg>` element.
+
+## Editor-Compatible SVG Structure
+
+The canonical reference for the editor-compatible SVG structure is the editor canvas template at `src/hi/apps/location/templates/location/edit/panes/location_svg_edit_canvas.html`. This template shows how the SVG is assembled: fill pattern `<defs>`, the palette `<defs>` (injected here as a sibling, not stored in the SVG files), and the background content loaded from MEDIA_ROOT.
+
+### Element Types
+
+Background elements use three editing modes, specified by the `data-bg-edit-type` attribute:
+
+- **Closed paths** (`closed`): Polygonal areas (`M...L...Z`). Edited by manipulating vertices.
+- **Open paths** (`open`): Line segments (`M...L`). Visual thickness from CSS `stroke-width`. Include a duplicate `<path class="hi-bg-hit-area">` for click targeting.
+- **Icons** (`icon`): Predefined shapes positioned via SVG `transform`. Include a `<rect class="hi-bg-hit-area">` for click targeting.
+
+### Layer Ordering
+
+Elements are ordered back-to-front in the SVG DOM, with layer numbers controlling insertion order. The layer definitions and their enforcement are in the JS palette drop handler in `src/hi/static/js/location-svg-edit.js` (see the `insertAtLayer` function). The correct ordering matters for visual rendering — ground elements must be behind walls, which must be behind doors, etc.
+
+## Palette System
+
+The palette defines the set of element types available in the background editor. Each palette item is a `<g>` element inside a `<defs>` block containing the canonical shape and metadata attributes.
+
+**Palette definition file**: `src/hi/apps/location/templates/location/edit/svg/svg_edit_palette.svg`
+
+The palette is injected into the editor's SVG DOM at runtime. It is NOT stored in MEDIA_ROOT SVG files.
+
+### How to Add a New Palette Item
+
+1. **Add the `<defs>` entry** in `svg_edit_palette.svg`:
+ ```xml
+ <g id="hi-my-new-type" data-bg-edit-type="closed" data-bg-label="My Type"
+ data-bg-category="features" data-bg-layer="6">
+ <path class="my-new-type" d="M 0,0 L 80,0 L 80,40 L 0,40 Z" />
+ </g>
+ ```
+ - `id`: Must be `hi-{type-name}`. The `hi-` prefix is stripped to derive `data-bg-type` for placed elements.
+ - `data-bg-edit-type`: `icon`, `open`, or `closed`
+ - `data-bg-label`: Display name shown in the palette UI
+ - `data-bg-category`: `structural`, `features`, or `exterior` (determines palette grouping)
+ - `data-bg-layer`: Rendering layer number (see Layer Ordering above)
+ - Inner `<path>`: Default geometry with the CSS class for styling
+
+2. **Add CSS styling** in `src/hi/static/css/svg-location-color.css`:
+ ```css
+ svg.hi-location-view-svg path.my-new-type {
+ fill: #color;
+ stroke: black;
+ stroke-width: 1;
+ }
+ ```
+ This styling applies both in the editor and in the normal Location view.
+
+3. **Add palette swatch CSS** in `src/hi/static/css/location-svg-edit.css` (in the "Palette Swatch Fills" section):
+ ```css
+ .hi-palette-swatch path.my-new-type { fill: #color; stroke: black; stroke-width: 1; }
+ ```
+ Swatches use flat colors since fill patterns from the main SVG are not available in the separate palette mini-SVGs.
+
+4. **For open-path types** (like walls): Hit areas are handled by the shared `.hi-bg-hit-area` CSS rules already in `svg-location-color.css`. No additional CSS needed.
+
+5. **For new icon types**: The `<defs>` entry defines the canonical shape. When dragged from the palette, the JS creates an inline copy with a `transform` attribute and a `<rect class="hi-bg-hit-area">` for click targeting.
+
+## Background Templates
+
+### What is a Background Template
+
+A background template is a Django template file (`.svg` extension) containing a complete SVG document. Templates are rendered via `render_to_string()`, processed through `process_svg_content()`, and the resulting fragment is written to MEDIA_ROOT.
+
+**Template directory**: `src/hi/apps/profiles/templates/profiles/svg/backgrounds/`
+
+Templates placed in this directory automatically appear in the "Choose a Template" modal. The display name is derived from the filename (hyphens to spaces, version suffix stripped, title-cased) or from the `data-hi-name` attribute on the outer `<g>` element.
+
+### How to Add a New Template
+
+1. **Create the SVG using the editor**: Use the background editor to build the floor plan.
+2. **Export it**: Click the EXPORT button in the editor footer to download the SVG file.
+3. **Copy to the templates directory**: Place the downloaded file in the backgrounds template directory listed above.
+4. **Name it**: Use lowercase with hyphens and a numeric version suffix: `my-layout-0.svg`
+5. **Verify the `data-hi-name`**: Check that the outer `<g>` has `data-hi-name="My Layout"`. The EXPORT includes this if the SVG was editor-compatible. Add it manually if needed.
+
+### Template Format
+
+A minimal template:
+```xml
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000">
+<g data-hi-editor="1" data-hi-name="My Template">
+ <!-- Placed elements here, ordered by layer -->
+</g>
+</svg>
+```
+
+Templates can use Django template tags (e.g., `{% include %}`) but currently none do — the palette defs are injected separately by the editor canvas template.
+
+## Key Files
+
+| File | Purpose |
+|------|---------|
+| `src/hi/apps/common/svg_utils.py` | SVG processing pipeline (`process_svg_content`) |
+| `src/hi/apps/common/svg_forms.py` | Form-based SVG handling for user uploads |
+| `src/hi/apps/location/location_manager.py` | SVG file management, draft system, template rendering |
+| `src/hi/apps/location/templates/location/edit/svg/svg_edit_palette.svg` | Palette definitions |
+| `src/hi/apps/location/templates/location/edit/panes/location_svg_edit_canvas.html` | Editor canvas rendering |
+| `src/hi/apps/profiles/templates/profiles/svg/backgrounds/` | Background SVG templates |
+| `src/hi/static/css/svg-location-color.css` | SVG element styling (shared between editor and normal views) |
+| `src/hi/static/css/location-svg-edit.css` | Editor-specific styling (palette swatches, layout) |
+| `src/hi/static/js/location-svg-edit.js` | Editor initialization, palette building, draft save, drag-and-drop |
+| `src/hi/static/js/svg-icon-core.js` | Icon editing core (drag, scale, rotate, mirror) |
+| `src/hi/static/js/svg-path-core.js` | Path editing core (proxy points, vertex manipulation) |
+| `src/hi/static/js/svg-pan-zoom-core.js` | Pan/zoom core (viewBox manipulation) |
+| `src/hi/static/js/svg-bg-event-listeners.js` | Event dispatcher for editor context |
diff --git a/docs/graphics/Branding.md b/docs/graphics/Branding.md
deleted file mode 100644
index 8c58264a..00000000
--- a/docs/graphics/Branding.md
+++ /dev/null
@@ -1,33 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-_WORK IN PROGRESS_
-
-# Branding, Icons, Logos
-
-## Gimp Assets
-
-_TBD_
-
-## ImageMagick
-
-Required for Makefdile (below) and scaling and installing logos/icons.
-
-### Installtion
-
-#### MacOS
-
-``` shell
-brew install imagemagick potrace
-```
-
-#### Ubuntu (GNU/Linux)
-
-``` shell
-sudo apt install imagemagick potrace
-```
-
-## Makefile
-
-For scaling and installing logos/icons into static code area from one large master image.
-
-_TBD_
diff --git a/docs/graphics/LocationSVG.md b/docs/graphics/LocationSVG.md
deleted file mode 100644
index 5c850a32..00000000
--- a/docs/graphics/LocationSVG.md
+++ /dev/null
@@ -1,73 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-_WORK IN PROGRESS_
-
-# Location SVGs
-
-## Location SVG Guidelines
-
-- For best result use SVG viewbox at least 1200 in each direction and less than 2200.
-- Location image does not have to be square.
-
-## Creating Location SVGs
-
-Create a series of individual SVG files with a single `<path>` tag to represent different types of features. The `<path>` "id" attribute should have one of the following ids to indicate which feature it is:
-
-``` text
-asphalt
-bathtubs
-brick
-ceiling-transitions
-countertops
-dead-space
-door-arcs
-doors
-exterior-walls
-fencing
-fireplaces
-floor-transitions
-foliage
-furniture
-grass
-gravel
-ground
-interior-floors
-interior-walls
-landscape-transitions
-mulch
-pavement
-pavers
-pool-coping
-property-lines
-rock-beds
-secondary-walls
-sheds
-shelves
-sinks
-stairs
-stone-walls
-tiles
-toilets
-utilities
-water
-windows
-wood-decks
-```
-
-If using Gimp, this translates to having a "Path" layer with the given name, then using the "Export Path" function since Gimp will add the path name as the path id.
-
-With the individual SVG files assembled in a directory, run the following command to combine and format them into a single SVG suitable for importing.
-
-``` shell
-./tools/combine-svgs.py -i <INPUT_DIR> -o <OUTPUT_FILE>
-```
-
-e.g.,
-
-``` shell
-./tools/combine-svgs.py -i locations/bordeaux/paths -o locations/bordeaux/bordeaux.svg
-./tools/combine-svgs.py -i locations/bordeaux-attic/paths -o locations/bordeaux-attic//bordeaux-attic.svg
-./tools/combine-svgs.py -i locations/default/paths -o locations/default/default.svg
-```
-
-Try to keep the SVG image size on the small side. It will get loaded and manipulated by javascript, so past a certain size there will probably be issues.
diff --git a/docs/graphics/README.md b/docs/graphics/README.md
deleted file mode 100644
index 808af4a2..00000000
--- a/docs/graphics/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Graphic Design Documentation
-
-See the markdown files in this directory for various graphic design-related documentation.
diff --git a/docs/img/editing/location-layout-edit-1024x768.png b/docs/img/editing/location-layout-edit-1024x768.png
index a6cf6686..e0a34579 100644
Binary files a/docs/img/editing/location-layout-edit-1024x768.png and b/docs/img/editing/location-layout-edit-1024x768.png differ
diff --git a/docs/img/editing/location-layout-edit-button-1024x768.png b/docs/img/editing/location-layout-edit-button-1024x768.png
index 2a31008a..a08b512d 100644
Binary files a/docs/img/editing/location-layout-edit-button-1024x768.png and b/docs/img/editing/location-layout-edit-button-1024x768.png differ
diff --git a/docs/img/getting-started/edit-button.png b/docs/img/getting-started/edit-button.png
index a9fab0f5..e191a3f7 100644
Binary files a/docs/img/getting-started/edit-button.png and b/docs/img/getting-started/edit-button.png differ
diff --git a/docs/img/getting-started/edit-mode-1024x768.png b/docs/img/getting-started/edit-mode-1024x768.png
index ad801af1..0fdc2eed 100644
Binary files a/docs/img/getting-started/edit-mode-1024x768.png and b/docs/img/getting-started/edit-mode-1024x768.png differ
diff --git a/docs/img/getting-started/initial-view-1024x768.png b/docs/img/getting-started/initial-view-1024x768.png
index 61535afb..fe2b84f0 100644
Binary files a/docs/img/getting-started/initial-view-1024x768.png and b/docs/img/getting-started/initial-view-1024x768.png differ
diff --git a/docs/img/getting-started/integrations-enable-modal-1024x768.png b/docs/img/getting-started/integrations-enable-modal-1024x768.png
index 7b2b8bc0..362f1459 100644
Binary files a/docs/img/getting-started/integrations-enable-modal-1024x768.png and b/docs/img/getting-started/integrations-enable-modal-1024x768.png differ
diff --git a/docs/img/getting-started/integrations-page-view-1024x768.png b/docs/img/getting-started/integrations-page-view-1024x768.png
index 9d9d3bde..41fbb925 100644
Binary files a/docs/img/getting-started/integrations-page-view-1024x768.png and b/docs/img/getting-started/integrations-page-view-1024x768.png differ
diff --git a/docs/img/getting-started/integrations-sync-result-1024x768.png b/docs/img/getting-started/integrations-sync-result-1024x768.png
index 9eb7ac38..c7987546 100644
Binary files a/docs/img/getting-started/integrations-sync-result-1024x768.png and b/docs/img/getting-started/integrations-sync-result-1024x768.png differ
diff --git a/docs/img/getting-started/item-edit-add-file-1024x768.png b/docs/img/getting-started/item-edit-add-file-1024x768.png
index 90f035a5..b7392abf 100644
Binary files a/docs/img/getting-started/item-edit-add-file-1024x768.png and b/docs/img/getting-started/item-edit-add-file-1024x768.png differ
diff --git a/docs/img/getting-started/item-edit-add-info-1024x768.png b/docs/img/getting-started/item-edit-add-info-1024x768.png
index 61adfeaa..6704f07a 100644
Binary files a/docs/img/getting-started/item-edit-add-info-1024x768.png and b/docs/img/getting-started/item-edit-add-info-1024x768.png differ
diff --git a/docs/img/getting-started/item-edit-modal-empty-1024x768.png b/docs/img/getting-started/item-edit-modal-empty-1024x768.png
index b5a0cb57..39e6c701 100644
Binary files a/docs/img/getting-started/item-edit-modal-empty-1024x768.png and b/docs/img/getting-started/item-edit-modal-empty-1024x768.png differ
diff --git a/docs/img/getting-started/location-edit-modal-1024x768.png b/docs/img/getting-started/location-edit-modal-1024x768.png
index 3c91416f..076fe3cd 100644
Binary files a/docs/img/getting-started/location-edit-modal-1024x768.png and b/docs/img/getting-started/location-edit-modal-1024x768.png differ
diff --git a/docs/img/getting-started/view-second-space-1024x768.png b/docs/img/getting-started/view-second-space-1024x768.png
index 0149a112..872ebdfb 100644
Binary files a/docs/img/getting-started/view-second-space-1024x768.png and b/docs/img/getting-started/view-second-space-1024x768.png differ
diff --git a/docs/img/screenshots/background-image-button-1024x768-bordered.png b/docs/img/screenshots/background-image-button-1024x768-bordered.png
new file mode 100644
index 00000000..a6972b0f
Binary files /dev/null and b/docs/img/screenshots/background-image-button-1024x768-bordered.png differ
diff --git a/docs/img/screenshots/floor-plan-editor-1024x768-bordered.png b/docs/img/screenshots/floor-plan-editor-1024x768-bordered.png
new file mode 100644
index 00000000..bca5ddcf
Binary files /dev/null and b/docs/img/screenshots/floor-plan-editor-1024x768-bordered.png differ
diff --git a/docs/img/screenshots/palette-drag-drop-1024x768-bordered.png b/docs/img/screenshots/palette-drag-drop-1024x768-bordered.png
new file mode 100644
index 00000000..893eb6ef
Binary files /dev/null and b/docs/img/screenshots/palette-drag-drop-1024x768-bordered.png differ
diff --git a/docs/img/screenshots/template-selector-1024x768-bordered.png b/docs/img/screenshots/template-selector-1024x768-bordered.png
new file mode 100644
index 00000000..9b3a51fb
Binary files /dev/null and b/docs/img/screenshots/template-selector-1024x768-bordered.png differ
diff --git a/src/hi/apps/common/file_utils.py b/src/hi/apps/common/file_utils.py
index 5ac289b0..3282c40c 100644
--- a/src/hi/apps/common/file_utils.py
+++ b/src/hi/apps/common/file_utils.py
@@ -1,4 +1,5 @@
import os
+import re
import time
@@ -7,3 +8,16 @@ def generate_unique_filename( filename : str ):
timestamp = int( time.time() )
unique_name = f'{original_name}-{timestamp}{extension}'
return unique_name
+
+
+def derive_new_unique_filename( filename : str ):
+ """
+ Generate a new unique filename, replacing any existing timestamp suffix
+ rather than appending. If the filename was previously generated by
+ generate_unique_filename (ending in -{digits}), the old timestamp is
+ replaced with a new one. Otherwise behaves like generate_unique_filename.
+ """
+ original_name, extension = os.path.splitext( filename )
+ original_name = re.sub( r'-\d+$', '', original_name )
+ timestamp = int( time.time() )
+ return f'{original_name}-{timestamp}{extension}'
diff --git a/src/hi/apps/common/svg_forms.py b/src/hi/apps/common/svg_forms.py
index 7b22e7ba..cd7264c8 100644
--- a/src/hi/apps/common/svg_forms.py
+++ b/src/hi/apps/common/svg_forms.py
@@ -5,14 +5,10 @@ import xml.etree.ElementTree as ET
from django import forms
from django.core.exceptions import ValidationError
-from hi.apps.common.file_utils import generate_unique_filename
-from hi.apps.common.svg_models import SvgViewBox
+from hi.apps.common.svg_utils import process_svg_content
logger = logging.getLogger(__name__)
-# Need this to avoid library adding "ns0:" namespacing when writing content.
-ET.register_namespace('', 'http://www.w3.org/2000/svg')
-
class SvgDecimalFormField( forms.FloatField ):
"""
@@ -92,19 +88,18 @@ class SvgFileForm(forms.Form):
def get_media_destination_directory(self):
# Relative to MEDIA_ROOT.
raise NotImplementedError( 'Subclasses must override this method.' )
+
+ def get_default_svg_content(self):
+ default_svg_path = os.path.join(
+ self.get_default_source_directory(),
+ self.get_default_basename(),
+ )
+ with open( default_svg_path, 'r' ) as f:
+ return f.read()
MAX_SVG_FILE_SIZE_MEGABYTES = 5
MAX_SVG_FILE_SIZE_BYTES = MAX_SVG_FILE_SIZE_MEGABYTES * 1024 * 1024
- DANGEROUS_TAGS = {
- 'script', 'foreignObject', 'iframe', 'object',
- 'animation', 'audio', 'video', 'style',
- }
- DANGEROUS_ATTRS = {
- 'onload', 'onclick', 'onmouseover', 'xlink:href',
- 'href',
- }
-
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._has_dangerous_svg_items = bool( self.data.get('has_dangerous_svg_items', 'false' ) == 'true' )
@@ -135,13 +130,8 @@ class SvgFileForm(forms.Form):
if require_svg_file:
raise ValidationError( 'You need to re-select the SVG file.' )
- default_svg_path = os.path.join(
- self.get_default_source_directory(),
- self.get_default_basename(),
- )
- with open( default_svg_path, 'r' ) as f:
- svg_content = f.read()
- svg_filename = self.get_default_basename()
+ svg_content = self.get_default_svg_content()
+ svg_filename = self.get_default_basename()
else:
svg_file_handle.seek(0) # Guard against multiple calls to clean()
svg_content = svg_file_handle.read().decode('utf-8')
@@ -151,62 +141,33 @@ class SvgFileForm(forms.Form):
if len(svg_content) > self.MAX_SVG_FILE_SIZE_BYTES:
raise ValidationError( f'SVG file too large. Max {self.MAX_SVG_FILE_SIZE_MEGABYTES} MB.' )
- root = ET.fromstring( svg_content )
- if root.tag != '{http://www.w3.org/2000/svg}svg':
- raise ValidationError( 'The uploaded file is not a valid SVG file.' )
+ result = process_svg_content(
+ svg_content = svg_content,
+ media_destination_directory = self.get_media_destination_directory(),
+ source_filename = svg_filename,
+ remove_dangerous = bool( remove_dangerous_svg_items ),
+ )
- view_box_str = root.attrib.get( 'viewBox' )
- if not view_box_str:
- raise ValidationError( 'The SVG must contain a viewBox attribute.' )
+ self._dangerous_tag_counts = result['dangerous_tag_counts']
+ self._dangerous_attr_counts = result['dangerous_attr_counts']
- svg_viewbox = SvgViewBox.from_attribute_value( view_box_str )
- cleaned_data['svg_viewbox'] = svg_viewbox
-
- # Remove the outer <svg> tag if necessary
- for element in list( root.iter() ):
- if element is root:
- continue
-
- # Remove the namespace from the child elements
- if element.tag.startswith('{http://www.w3.org/2000/svg}'):
- element.tag = element.tag.split('}', 1)[1] # Strip the namespace
-
- tag_name = element.tag.split('}')[-1] # Handle namespaces
- if tag_name in self.DANGEROUS_TAGS:
- logger.debug( f'Removing dangerous SVG tag "{tag_name}"' )
- root.remove(element)
- self._increment_dangerous_tag_count( tag_name )
- continue
-
- for attr_name in list(element.attrib):
- if attr_name in self.DANGEROUS_ATTRS:
- logger.debug(f'Removing dangerous SVG attribute "{attr_name}"')
- del element.attrib[attr_name]
- self._increment_dangerous_attr_count( attr_name )
- continue
-
- continue
-
if ( not remove_dangerous_svg_items
and (( len(self._dangerous_tag_counts) + len(self._dangerous_attr_counts) ) > 0 )):
self._add_dangerous_messages()
self.fields['remove_dangerous_svg_items'].widget.attrs.update( { 'style': '' } )
- self.data = self.data.copy() # Need a mutable copy to change this data
+ self.data = self.data.copy()
self.data['has_dangerous_svg_items'] = 'true'
self._has_dangerous_svg_items = True
-
- inner_content = ''.join( ET.tostring( element, encoding = 'unicode' ) for element in root )
- cleaned_data['svg_fragment_content'] = inner_content
- svg_fragment_filename = os.path.join(
- self.get_media_destination_directory(),
- generate_unique_filename( svg_filename ),
- )
- cleaned_data['svg_fragment_filename'] = svg_fragment_filename
-
+ cleaned_data['svg_fragment_content'] = result['svg_fragment_content']
+ cleaned_data['svg_viewbox'] = result['svg_viewbox']
+ cleaned_data['svg_fragment_filename'] = result['svg_fragment_filename']
+
except ET.ParseError as pe:
logger.exception( pe )
raise ValidationError( 'The uploaded file is not a valid XML (SVG) file.' )
+ except ValueError as ve:
+ raise ValidationError( str(ve) )
except Exception as e:
logger.exception( e )
raise ValidationError(f'Error processing the SVG file: {str(e)}' )
diff --git a/src/hi/apps/common/svg_utils.py b/src/hi/apps/common/svg_utils.py
new file mode 100644
index 00000000..3a1aa247
--- /dev/null
+++ b/src/hi/apps/common/svg_utils.py
@@ -0,0 +1,109 @@
+import logging
+import os
+import xml.etree.ElementTree as ET
+
+from hi.apps.common.file_utils import generate_unique_filename
+from hi.apps.common.svg_models import SvgViewBox
+
+logger = logging.getLogger(__name__)
+
+ET.register_namespace('', 'http://www.w3.org/2000/svg')
+
+DANGEROUS_TAGS = {
+ 'script', 'foreignObject', 'iframe', 'object',
+ 'animation', 'audio', 'video', 'style',
+}
+DANGEROUS_ATTRS = {
+ 'onload', 'onclick', 'onmouseover',
+}
+HREF_ATTRS = {
+ 'href', 'xlink:href',
+ '{http://www.w3.org/1999/xlink}href',
+}
+
+
+def process_svg_content( svg_content,
+ media_destination_directory,
+ source_filename,
+ remove_dangerous = True ):
+ """
+ Process a full SVG document: validate, extract viewBox, strip the
+ outer <svg> wrapper, clean namespaces, scan for dangerous elements,
+ and generate a unique MEDIA_ROOT filename.
+
+ Args:
+ svg_content: Full SVG content string with outer <svg> element.
+ media_destination_directory: Relative directory in MEDIA_ROOT (e.g., 'location/svg').
+ source_filename: Original filename for generating unique destination name.
+ remove_dangerous: If True, silently remove dangerous elements.
+ If False, return counts but do not remove.
+
+ Returns:
+ dict with keys:
+ 'svg_fragment_content': Inner SVG content string (outer <svg> stripped).
+ 'svg_viewbox': SvgViewBox instance.
+ 'svg_fragment_filename': Generated filename relative to MEDIA_ROOT.
+ 'dangerous_tag_counts': dict of {tag_name: count} for dangerous tags found.
+ 'dangerous_attr_counts': dict of {attr_name: count} for dangerous attrs found.
+
+ Raises:
+ ValueError: If content is not valid SVG or missing viewBox.
+ """
+ root = ET.fromstring( svg_content )
+ if root.tag != '{http://www.w3.org/2000/svg}svg':
+ raise ValueError( 'Content is not a valid SVG.' )
+
+ view_box_str = root.attrib.get( 'viewBox' )
+ if not view_box_str:
+ raise ValueError( 'SVG must contain a viewBox attribute.' )
+
+ svg_viewbox = SvgViewBox.from_attribute_value( view_box_str )
+
+ dangerous_tag_counts = dict()
+ dangerous_attr_counts = dict()
+
+ for element in list( root.iter() ):
+ if element is root:
+ continue
+
+ if element.tag.startswith( '{http://www.w3.org/2000/svg}' ):
+ element.tag = element.tag.split( '}', 1 )[1]
+
+ tag_name = element.tag.split( '}' )[-1]
+ if tag_name in DANGEROUS_TAGS:
+ dangerous_tag_counts[tag_name] = dangerous_tag_counts.get( tag_name, 0 ) + 1
+ if remove_dangerous:
+ logger.debug( f'Removing dangerous SVG tag "{tag_name}"' )
+ root.remove( element )
+ continue
+
+ for attr_name in list( element.attrib ):
+ if attr_name in DANGEROUS_ATTRS:
+ dangerous_attr_counts[attr_name] = dangerous_attr_counts.get( attr_name, 0 ) + 1
+ if remove_dangerous:
+ logger.debug( f'Removing dangerous SVG attribute "{attr_name}"' )
+ del element.attrib[attr_name]
+ elif attr_name in HREF_ATTRS:
+ attr_value = element.attrib[attr_name].strip()
+ if not attr_value.startswith( '#' ):
+ dangerous_attr_counts[attr_name] = dangerous_attr_counts.get( attr_name, 0 ) + 1
+ if remove_dangerous:
+ logger.debug( f'Removing dangerous SVG href "{attr_name}={attr_value}"' )
+ del element.attrib[attr_name]
+
+ inner_content = ''.join(
+ ET.tostring( element, encoding='unicode' ) for element in root
+ )
+
+ svg_fragment_filename = os.path.join(
+ media_destination_directory,
+ generate_unique_filename( source_filename ),
+ )
+
+ return {
+ 'svg_fragment_content': inner_content,
+ 'svg_viewbox': svg_viewbox,
+ 'svg_fragment_filename': svg_fragment_filename,
+ 'dangerous_tag_counts': dangerous_tag_counts,
+ 'dangerous_attr_counts': dangerous_attr_counts,
+ }
diff --git a/src/hi/apps/common/templatetags/icons.py b/src/hi/apps/common/templatetags/icons.py
index f8e0e981..c90af140 100644
--- a/src/hi/apps/common/templatetags/icons.py
+++ b/src/hi/apps/common/templatetags/icons.py
@@ -36,6 +36,7 @@ AVAILABLE_ICONS = {
'collection',
'delete',
'disabled',
+ 'download',
'edit',
'exclamation-circle',
'eye',
@@ -64,6 +65,7 @@ AVAILABLE_ICONS = {
'sync',
'tasks',
'times-circle',
+ 'undo',
'unlock',
'upload',
'video',
diff --git a/src/hi/apps/common/tests/test_file_utils.py b/src/hi/apps/common/tests/test_file_utils.py
new file mode 100644
index 00000000..f22fbab9
--- /dev/null
+++ b/src/hi/apps/common/tests/test_file_utils.py
@@ -0,0 +1,64 @@
+from unittest.mock import patch
+
+from hi.apps.common.file_utils import derive_new_unique_filename, generate_unique_filename
+from hi.testing.base_test_case import BaseTestCase
+
+
+class TestDeriveNewUniqueFilename(BaseTestCase):
+
+ @patch('hi.apps.common.file_utils.time')
+ def test_replaces_existing_timestamp(self, mock_time):
+ """An existing timestamp suffix is replaced, not appended."""
+ mock_time.time.return_value = 9999999999
+ result = derive_new_unique_filename('location/svg/my-file-1713285600.svg')
+ self.assertEqual(result, 'location/svg/my-file-9999999999.svg')
+
+ @patch('hi.apps.common.file_utils.time')
+ def test_adds_timestamp_when_none_exists(self, mock_time):
+ """A filename without a timestamp gets one added."""
+ mock_time.time.return_value = 9999999999
+ result = derive_new_unique_filename('location/svg/my-file.svg')
+ self.assertEqual(result, 'location/svg/my-file-9999999999.svg')
+
+ @patch('hi.apps.common.file_utils.time')
+ def test_preserves_directory_path(self, mock_time):
+ """The directory portion of the path is preserved."""
+ mock_time.time.return_value = 1000000000
+ result = derive_new_unique_filename('some/deep/path/file-5555.svg')
+ self.assertEqual(result, 'some/deep/path/file-1000000000.svg')
+
+ @patch('hi.apps.common.file_utils.time')
+ def test_preserves_extension(self, mock_time):
+ """The file extension is preserved."""
+ mock_time.time.return_value = 1000000000
+ result = derive_new_unique_filename('file-5555.html')
+ self.assertEqual(result, 'file-1000000000.html')
+
+ @patch('hi.apps.common.file_utils.time')
+ def test_does_not_accumulate_timestamps(self, mock_time):
+ """Calling repeatedly does not grow the filename."""
+ mock_time.time.return_value = 1111111111
+ first = derive_new_unique_filename('location/svg/my-file-1000000000.svg')
+ self.assertEqual(first, 'location/svg/my-file-1111111111.svg')
+
+ mock_time.time.return_value = 2222222222
+ second = derive_new_unique_filename(first)
+ self.assertEqual(second, 'location/svg/my-file-2222222222.svg')
+
+ @patch('hi.apps.common.file_utils.time')
+ def test_handles_name_with_hyphens_and_digits(self, mock_time):
+ """Hyphens in the base name that are not timestamps are preserved."""
+ mock_time.time.return_value = 9999999999
+ result = derive_new_unique_filename('location/svg/single-story-0-1713285600.svg')
+ self.assertEqual(result, 'location/svg/single-story-0-9999999999.svg')
+
+ @patch('hi.apps.common.file_utils.time')
+ def test_round_trip_with_generate_unique_filename(self, mock_time):
+ """Output of generate_unique_filename is handled correctly."""
+ mock_time.time.return_value = 1000000000
+ generated = generate_unique_filename('location/svg/blank.svg')
+ self.assertEqual(generated, 'location/svg/blank-1000000000.svg')
+
+ mock_time.time.return_value = 2000000000
+ derived = derive_new_unique_filename(generated)
+ self.assertEqual(derived, 'location/svg/blank-2000000000.svg')
diff --git a/src/hi/apps/common/tests/test_svg_forms.py b/src/hi/apps/common/tests/test_svg_forms.py
new file mode 100644
index 00000000..027ab791
--- /dev/null
+++ b/src/hi/apps/common/tests/test_svg_forms.py
@@ -0,0 +1,212 @@
+import logging
+
+from django.core.files.uploadedfile import SimpleUploadedFile
+
+from hi.apps.common.svg_forms import SvgFileForm
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestSvgFileForm(SvgFileForm):
+ """Concrete subclass of SvgFileForm for testing purposes."""
+
+ def allow_default_svg_file(self):
+ return False
+
+ def get_media_destination_directory(self):
+ return 'test/svg'
+
+
+def _make_svg_with_element(inner_element):
+ """Build a minimal valid SVG string wrapping the given inner element."""
+ return (
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">'
+ f'{inner_element}'
+ '</svg>'
+ )
+
+
+def _make_upload(svg_string, filename='test.svg'):
+ """Wrap SVG string content into a SimpleUploadedFile."""
+ return SimpleUploadedFile(
+ name=filename,
+ content=svg_string.encode('utf-8'),
+ content_type='image/svg+xml',
+ )
+
+
+class TestSvgFileFormHrefHandling(BaseTestCase):
+ """
+ Tests for SvgFileForm.clean() handling of href and xlink:href attributes.
+
+ Internal fragment references (starting with '#') should be preserved.
+ External URLs should be removed and counted as dangerous.
+ """
+
+ def _submit_form(self, svg_content, remove_dangerous=True):
+ """
+ Submit SVG content through the form and return (form, is_valid).
+
+ When remove_dangerous is True, the form will strip dangerous items
+ and return cleaned content. When False, the form will flag dangerous
+ items but not strip them (requires a second submission).
+ """
+ svg_file = _make_upload(svg_content)
+ data = {
+ 'has_dangerous_svg_items': 'false',
+ }
+ if remove_dangerous:
+ data['remove_dangerous_svg_items'] = 'on'
+ data['has_dangerous_svg_items'] = 'true'
+
+ files = {'svg_file': svg_file}
+ form = TestSvgFileForm(data=data, files=files)
+ return form, form.is_valid()
+
+ def test_internal_href_is_preserved(self):
+ """An href starting with '#' should remain in the cleaned SVG content."""
+ svg = _make_svg_with_element('<a href="#section1"><rect width="10" height="10"/></a>')
+ form, is_valid = self._submit_form(svg)
+
+ self.assertTrue(is_valid)
+ fragment_content = form.cleaned_data['svg_fragment_content']
+ self.assertIn('href="#section1"', fragment_content)
+
+ def test_external_href_is_removed_when_dangerous_items_accepted(self):
+ """An href with an external URL should be stripped from cleaned content."""
+ svg = _make_svg_with_element('<a href="http://evil.com"><rect width="10" height="10"/></a>')
+ form, is_valid = self._submit_form(svg, remove_dangerous=True)
+
+ self.assertTrue(is_valid)
+ fragment_content = form.cleaned_data['svg_fragment_content']
+ self.assertNotIn('http://evil.com', fragment_content)
+ self.assertNotIn('href=', fragment_content)
+
+ def test_external_href_is_flagged_as_dangerous(self):
+ """An href with external URL should be counted as a dangerous attribute."""
+ svg = _make_svg_with_element('<a href="http://evil.com"><rect width="10" height="10"/></a>')
+ form, is_valid = self._submit_form(svg, remove_dangerous=False)
+
+ # Form should be invalid because dangerous items were found but not approved
+ self.assertFalse(is_valid)
+ # The dangerous attr count should include href
+ self.assertIn('href', form._dangerous_attr_counts)
+ self.assertEqual(form._dangerous_attr_counts['href'], 1)
+
+ def test_xlink_href_internal_is_preserved(self):
+ """An xlink:href starting with '#' should remain in cleaned SVG content."""
+ svg = _make_svg_with_element(
+ '<use xlink:href="#my-symbol" xmlns:xlink="http://www.w3.org/1999/xlink"/>'
+ )
+ form, is_valid = self._submit_form(svg)
+
+ self.assertTrue(is_valid)
+ fragment_content = form.cleaned_data['svg_fragment_content']
+ # The attribute value should reference the internal fragment
+ self.assertIn('#my-symbol', fragment_content)
+
+ def test_xlink_href_external_is_removed(self):
+ """External xlink:href URLs should be removed as dangerous."""
+ svg = _make_svg_with_element(
+ '<use xlink:href="http://evil.com/sprite.svg#icon"'
+ ' xmlns:xlink="http://www.w3.org/1999/xlink"/>'
+ )
+ form, is_valid = self._submit_form(svg, remove_dangerous=True)
+
+ self.assertTrue(is_valid)
+ fragment_content = form.cleaned_data['svg_fragment_content']
+ self.assertNotIn('evil.com', fragment_content)
+
+ def test_onclick_event_handler_is_flagged(self):
+ """Event handler attributes like onclick should be removed."""
+ svg = _make_svg_with_element('<rect width="10" height="10" onclick="alert(1)"/>')
+ form, is_valid = self._submit_form(svg, remove_dangerous=True)
+
+ self.assertTrue(is_valid)
+ fragment_content = form.cleaned_data['svg_fragment_content']
+ self.assertNotIn('onclick', fragment_content)
+ self.assertNotIn('alert', fragment_content)
+
+ def test_onclick_is_counted_as_dangerous(self):
+ """onclick should appear in the dangerous attribute counts."""
+ svg = _make_svg_with_element('<rect width="10" height="10" onclick="alert(1)"/>')
+ form, is_valid = self._submit_form(svg, remove_dangerous=False)
+
+ self.assertFalse(is_valid)
+ self.assertIn('onclick', form._dangerous_attr_counts)
+ self.assertEqual(form._dangerous_attr_counts['onclick'], 1)
+
+ def test_onload_event_handler_is_flagged(self):
+ """onload event handler should be removed from cleaned content."""
+ svg = _make_svg_with_element('<rect width="10" height="10" onload="init()"/>')
+ form, is_valid = self._submit_form(svg, remove_dangerous=True)
+
+ self.assertTrue(is_valid)
+ fragment_content = form.cleaned_data['svg_fragment_content']
+ self.assertNotIn('onload', fragment_content)
+
+ def test_onmouseover_event_handler_is_flagged(self):
+ """onmouseover event handler should be removed from cleaned content."""
+ svg = _make_svg_with_element('<rect width="10" height="10" onmouseover="highlight()"/>')
+ form, is_valid = self._submit_form(svg, remove_dangerous=True)
+
+ self.assertTrue(is_valid)
+ fragment_content = form.cleaned_data['svg_fragment_content']
+ self.assertNotIn('onmouseover', fragment_content)
+
+ def test_multiple_dangerous_attrs_are_all_counted(self):
+ """Multiple dangerous attributes across elements should all be counted."""
+ svg = _make_svg_with_element(
+ '<rect width="10" height="10" onclick="a()" onload="b()"/>'
+ '<circle r="5" onmouseover="c()"/>'
+ )
+ form, is_valid = self._submit_form(svg, remove_dangerous=False)
+
+ self.assertFalse(is_valid)
+ self.assertIn('onclick', form._dangerous_attr_counts)
+ self.assertIn('onload', form._dangerous_attr_counts)
+ self.assertIn('onmouseover', form._dangerous_attr_counts)
+
+ def test_safe_attributes_are_preserved(self):
+ """Normal SVG attributes like fill, stroke should not be affected."""
+ svg = _make_svg_with_element(
+ '<rect width="10" height="10" fill="blue" stroke="red" stroke-width="2"/>'
+ )
+ form, is_valid = self._submit_form(svg)
+
+ self.assertTrue(is_valid)
+ fragment_content = form.cleaned_data['svg_fragment_content']
+ self.assertIn('fill="blue"', fragment_content)
+ self.assertIn('stroke="red"', fragment_content)
+
+ def test_dangerous_tags_are_removed(self):
+ """Dangerous tags like <script> should be removed from cleaned content."""
+ svg = _make_svg_with_element(
+ '<rect width="10" height="10"/>'
+ '<script>alert("xss")</script>'
+ )
+ form, is_valid = self._submit_form(svg, remove_dangerous=True)
+
+ self.assertTrue(is_valid)
+ fragment_content = form.cleaned_data['svg_fragment_content']
+ self.assertNotIn('script', fragment_content)
+ self.assertNotIn('alert', fragment_content)
+
+ def test_viewbox_is_extracted(self):
+ """The SVG viewBox should be parsed and available in cleaned_data."""
+ svg = _make_svg_with_element('<rect width="10" height="10"/>')
+ form, is_valid = self._submit_form(svg)
+
+ self.assertTrue(is_valid)
+ svg_viewbox = form.cleaned_data['svg_viewbox']
+ self.assertEqual(svg_viewbox.x, 0)
+ self.assertEqual(svg_viewbox.y, 0)
+ self.assertEqual(svg_viewbox.width, 100)
+ self.assertEqual(svg_viewbox.height, 100)
+
+ def test_missing_svg_file_raises_validation_error(self):
+ """Submitting with no file and allow_default=False should fail validation."""
+ data = {'has_dangerous_svg_items': 'false'}
+ form = TestSvgFileForm(data=data, files={})
+ self.assertFalse(form.is_valid())
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index 82a84374..4200b308 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -91,6 +91,7 @@ class EntityType(LabeledEnum):
PRESENCE_SENSOR = ( 'Presence Sensor', '' )
PRINTER = ( 'Printer', '' )
PUMP = ( 'Pump', '' )
+ RADON_DETECTOR = ( 'Radon Detector', '' )
RANGE_HOOD = ( 'Range Hood', '' )
REFRIGERATOR = ( 'Refrigerator', '' )
SATELLITE_DISH = ( 'Satellite Dish' , '' )
@@ -100,7 +101,6 @@ class EntityType(LabeledEnum):
SHOWER = ( 'Shower', '' )
SINK = ( 'Sink', '' )
SKYLIGHT = ( 'Skylight', '' )
- RADON_DETECTOR = ( 'Radon Detector', '' )
SMOKE_DETECTOR = ( 'Smoke Detector', '' )
SOLAR_PANEL = ( 'Solar Panel', '' )
SPEAKER = ( 'Speaker', '' )
diff --git a/src/hi/apps/location/edit/forms.py b/src/hi/apps/location/edit/forms.py
index 0d52a4b6..4acaca4c 100644
--- a/src/hi/apps/location/edit/forms.py
+++ b/src/hi/apps/location/edit/forms.py
@@ -3,6 +3,7 @@ import os
from django import forms
from django.conf import settings
+from django.template.loader import render_to_string
from hi.apps.common.svg_forms import SvgDecimalFormField, SvgFileForm
from hi.apps.common.svg_models import SvgItemPositionBounds
@@ -17,34 +18,52 @@ logger = logging.getLogger(__name__)
class LocationSvgFileForm( SvgFileForm ):
-
+
+ BACKGROUNDS_TEMPLATE_DIR = 'profiles/svg/backgrounds'
+ DEFAULT_BACKGROUND_TEMPLATE = 'single-story-0.svg'
+
def get_default_source_directory(self):
return os.path.join(
settings.BASE_DIR,
'static',
'img',
+ 'backgrounds',
)
def get_default_basename(self):
- return 'location-default.svg'
-
+ return 'single-story.svg'
+
+ def get_default_svg_content(self):
+ template_name = os.path.join(
+ self.BACKGROUNDS_TEMPLATE_DIR,
+ self.DEFAULT_BACKGROUND_TEMPLATE,
+ )
+ return render_to_string( template_name )
+
def get_media_destination_directory(self):
return 'location/svg'
class LocationAddForm( LocationSvgFileForm ):
- # N.B. When adding a Location, we use limited field options to
- # keep it simpler.
-
+ DEFAULT_BACKGROUND_TEMPLATE = 'blank.svg'
+
name = forms.CharField(
- label = 'Location Name',
+ label = 'Name',
required = True,
+ widget = forms.TextInput( attrs={ 'class': 'form-control', 'style': 'min-width: 20rem;' } ),
)
def allow_default_svg_file(self):
return True
+ def get_default_svg_content(self):
+ template_name = os.path.join(
+ self.BACKGROUNDS_TEMPLATE_DIR,
+ self.DEFAULT_BACKGROUND_TEMPLATE,
+ )
+ return render_to_string( template_name )
+
class LocationSvgReplaceForm( LocationSvgFileForm ):
diff --git a/src/hi/apps/location/edit/tests/test_svg_edit_views.py b/src/hi/apps/location/edit/tests/test_svg_edit_views.py
new file mode 100644
index 00000000..6d7878b8
--- /dev/null
+++ b/src/hi/apps/location/edit/tests/test_svg_edit_views.py
@@ -0,0 +1,527 @@
+import logging
+import os
+import shutil
+import tempfile
+
+from django.core.files.storage import default_storage
+from django.test import override_settings
+from django.urls import reverse
+
+from hi.apps.location.location_manager import LocationManager
+from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+from hi.enums import ViewMode
+from hi.testing.view_test_base import DualModeViewTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class LocationSvgEditViewTestBase(DualModeViewTestCase):
+ """
+ Shared setup for all SVG editor view tests.
+
+ Creates a location with a real SVG file in an isolated media root
+ and enables edit mode in the session.
+ """
+
+ LIVE_SVG_CONTENT = '<rect width="800" height="600" fill="white"/>'
+
+ def setUp(self):
+ super().setUp()
+ self.setSessionViewMode(ViewMode.EDIT)
+
+ # Set up isolated MEDIA_ROOT
+ self._temp_media_dir = tempfile.mkdtemp()
+ self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
+ self._settings_patcher.enable()
+
+ self.location = LocationSyntheticData.create_test_location(
+ name='Test Location',
+ svg_fragment_filename='location/svg/test-location.svg',
+ svg_view_box_str='0 0 800 600',
+ )
+ self._write_live_svg()
+ self.manager = LocationManager()
+
+ def tearDown(self):
+ if hasattr(self, '_settings_patcher'):
+ self._settings_patcher.disable()
+ if hasattr(self, '_temp_media_dir'):
+ shutil.rmtree(self._temp_media_dir, ignore_errors=True)
+ LocationManager._instance = None
+ super().tearDown()
+
+ def _write_live_svg(self, content=None):
+ """Write the live SVG file into the isolated media root."""
+ if content is None:
+ content = self.LIVE_SVG_CONTENT
+ filepath = self.location.svg_fragment_filename
+ full_dir = os.path.dirname(os.path.join(self._temp_media_dir, filepath))
+ os.makedirs(full_dir, exist_ok=True)
+ with default_storage.open(filepath, 'w') as f:
+ f.write(content)
+
+ def _create_draft(self, content=None):
+ """Create a draft file, optionally with different content."""
+ self.manager.create_draft_svg(self.location)
+ if content is not None:
+ self.manager.save_draft_svg(self.location, content)
+
+
+class TestLocationSvgEditView(LocationSvgEditViewTestBase):
+ """Tests for LocationSvgEditView - GET creates draft and renders editor page."""
+
+ def test_get_creates_draft_and_renders_editor(self):
+ """GET should create a draft file and render the SVG editor page."""
+ url = reverse('location_edit_svg_edit', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, 200)
+ self.assertTemplateRendered(response, 'location/edit/pages/location_svg_edit.html')
+ self.assertTrue(self.manager.draft_svg_exists(self.location))
+
+ def test_get_sets_draft_svg_filename_in_context(self):
+ """GET should include draft_svg_filename in the template context."""
+ url = reverse('location_edit_svg_edit', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertIn('draft_svg_filename', response.context)
+ expected_draft = self.manager.get_draft_svg_filename(self.location)
+ self.assertEqual(response.context['draft_svg_filename'], expected_draft)
+
+ def test_get_preserves_existing_draft(self):
+ """GET should not overwrite an existing draft with changes."""
+ edited_content = '<circle r="50"/>'
+ self._create_draft(edited_content)
+
+ url = reverse('location_edit_svg_edit', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, 200)
+ # draft_resumed should be True since draft differs from live
+ self.assertTrue(response.context['draft_resumed'])
+
+ # Verify draft content was not overwritten
+ draft_filename = self.manager.get_draft_svg_filename(self.location)
+ with default_storage.open(draft_filename, 'r') as f:
+ content = f.read()
+ self.assertEqual(content, edited_content)
+
+ def test_get_sets_viewbox_in_session(self):
+ """GET should store the SVG viewbox in the session."""
+ url = reverse('location_edit_svg_edit', kwargs={'location_id': self.location.id})
+ self.client.get(url)
+
+ session_key = f'svg_edit_viewbox_{self.location.id}'
+ session = self.client.session
+ self.assertEqual(session[session_key], self.location.svg_view_box_str)
+
+ def test_get_nonexistent_location_returns_404(self):
+ """GET with invalid location_id should return 404."""
+ url = reverse('location_edit_svg_edit', kwargs={'location_id': 99999})
+ response = self.client.get(url)
+ self.assertEqual(response.status_code, 404)
+
+
+class TestLocationSvgEditCancelView(LocationSvgEditViewTestBase):
+ """Tests for LocationSvgEditCancelView - cancel editing workflow."""
+
+ def test_get_no_changes_redirects_directly(self):
+ """GET with no draft changes should redirect without showing modal."""
+ self._create_draft() # Draft matches live
+
+ # Set the session viewbox to match the location (as the edit view would)
+ session = self.client.session
+ session_key = f'svg_edit_viewbox_{self.location.id}'
+ session[session_key] = self.location.svg_view_box_str
+ session.save()
+
+ url = reverse('location_svg_edit_cancel', kwargs={'location_id': self.location.id})
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ # Should clean up draft
+ self.assertFalse(self.manager.draft_svg_exists(self.location))
+
+ def test_get_with_changes_shows_modal(self):
+ """GET with draft changes should show confirmation modal."""
+ self._create_draft('<circle r="999"/>')
+
+ url = reverse('location_svg_edit_cancel', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'location/edit/modals/location_svg_edit_cancel.html')
+
+ def test_post_deletes_draft_and_redirects(self):
+ """POST should delete draft and redirect to home."""
+ self._create_draft('<circle r="999"/>')
+
+ url = reverse('location_svg_edit_cancel', kwargs={'location_id': self.location.id})
+ response = self.client.post(url)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ self.assertFalse(self.manager.draft_svg_exists(self.location))
+
+ def test_post_does_not_modify_live_svg(self):
+ """POST cancel should leave the live SVG file unchanged."""
+ self._create_draft('<circle r="999"/>')
+
+ url = reverse('location_svg_edit_cancel', kwargs={'location_id': self.location.id})
+ self.client.post(url)
+
+ with default_storage.open(self.location.svg_fragment_filename, 'r') as f:
+ live_content = f.read()
+ self.assertEqual(live_content, self.LIVE_SVG_CONTENT)
+
+
+class TestLocationSvgEditExitView(LocationSvgEditViewTestBase):
+ """Tests for LocationSvgEditExitView - save and exit workflow."""
+
+ def test_get_no_changes_redirects_directly(self):
+ """GET with no draft changes should redirect without showing modal."""
+ self._create_draft() # Draft matches live
+
+ # Set the session viewbox to match the location (as the edit view would)
+ session = self.client.session
+ session_key = f'svg_edit_viewbox_{self.location.id}'
+ session[session_key] = self.location.svg_view_box_str
+ session.save()
+
+ url = reverse('location_svg_edit_exit', kwargs={'location_id': self.location.id})
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+ def test_get_with_changes_shows_modal(self):
+ """GET with draft changes should show confirmation modal."""
+ self._create_draft('<circle r="999"/>')
+
+ url = reverse('location_svg_edit_exit', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'location/edit/modals/location_svg_edit_exit.html')
+
+ def test_post_commits_draft_to_live(self):
+ """POST should commit draft content to a new SVG file and update the location."""
+ edited_content = '<ellipse rx="100" ry="50"/>'
+ self._create_draft(edited_content)
+ old_filename = self.location.svg_fragment_filename
+
+ url = reverse('location_svg_edit_exit', kwargs={'location_id': self.location.id})
+ self.client.post(url)
+
+ self.location.refresh_from_db()
+ # Commit writes to a new unique filename
+ self.assertNotEqual(self.location.svg_fragment_filename, old_filename)
+ with default_storage.open(self.location.svg_fragment_filename, 'r') as f:
+ live_content = f.read()
+ self.assertEqual(live_content, edited_content)
+
+ def test_post_removes_draft_file(self):
+ """POST should remove the draft file after committing."""
+ self._create_draft('<circle r="50"/>')
+
+ url = reverse('location_svg_edit_exit', kwargs={'location_id': self.location.id})
+ self.client.post(url)
+
+ self.assertFalse(self.manager.draft_svg_exists(self.location))
+
+ def test_post_saves_viewbox_from_session(self):
+ """POST should save the session viewbox to the location model."""
+ self._create_draft('<circle r="50"/>')
+
+ # Set a different viewbox in the session
+ session = self.client.session
+ session_key = f'svg_edit_viewbox_{self.location.id}'
+ session[session_key] = '0 0 1200 900'
+ session.save()
+
+ url = reverse('location_svg_edit_exit', kwargs={'location_id': self.location.id})
+ self.client.post(url)
+
+ self.location.refresh_from_db()
+ self.assertEqual(self.location.svg_view_box_str, '0 0 1200 900')
+
+
+class TestLocationSvgEditRevertView(LocationSvgEditViewTestBase):
+ """Tests for LocationSvgEditRevertView - revert draft to live content."""
+
+ def test_get_no_changes_shows_info_modal(self):
+ """GET with no changes shows informational modal explaining nothing to revert."""
+ self._create_draft() # Draft matches live
+
+ # Set the session viewbox to match the location (as the edit view would)
+ session = self.client.session
+ session_key = f'svg_edit_viewbox_{self.location.id}'
+ session[session_key] = self.location.svg_view_box_str
+ session.save()
+
+ url = reverse('location_svg_edit_revert', kwargs={'location_id': self.location.id})
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+
+ def test_get_with_changes_shows_confirmation_modal(self):
+ """GET with changes should show revert confirmation modal."""
+ self._create_draft('<circle r="999"/>')
+
+ url = reverse('location_svg_edit_revert', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'location/edit/modals/location_svg_edit_revert.html')
+
+ def test_post_copies_live_to_draft(self):
+ """POST should overwrite draft with live SVG content."""
+ self._create_draft('<circle r="999"/>')
+
+ url = reverse('location_svg_edit_revert', kwargs={'location_id': self.location.id})
+ self.client.post(url)
+
+ draft_filename = self.manager.get_draft_svg_filename(self.location)
+ with default_storage.open(draft_filename, 'r') as f:
+ draft_content = f.read()
+ self.assertEqual(draft_content, self.LIVE_SVG_CONTENT)
+
+ def test_post_resets_session_viewbox(self):
+ """POST should reset the session viewbox to the location's original."""
+ self._create_draft('<circle r="999"/>')
+
+ session = self.client.session
+ session_key = f'svg_edit_viewbox_{self.location.id}'
+ session[session_key] = '0 0 9999 9999'
+ session.save()
+
+ url = reverse('location_svg_edit_revert', kwargs={'location_id': self.location.id})
+ self.client.post(url)
+
+ session = self.client.session
+ self.assertEqual(session[session_key], self.location.svg_view_box_str)
+
+
+class TestLocationSvgEditSaveView(LocationSvgEditViewTestBase):
+ """Tests for LocationSvgEditSaveView - save SVG content to draft."""
+
+ def test_post_saves_content_to_draft(self):
+ """POST should write svg_content to the draft file."""
+ new_content = '<g><text>Hello</text></g>'
+ url = reverse('location_svg_edit_save', kwargs={'location_id': self.location.id})
+ response = self.client.post(url, {'svg_content': new_content})
+
+ self.assertEqual(response.status_code, 200)
+
+ draft_filename = self.manager.get_draft_svg_filename(self.location)
+ with default_storage.open(draft_filename, 'r') as f:
+ saved = f.read()
+ self.assertEqual(saved, new_content)
+
+ def test_post_without_content_returns_400(self):
+ """POST without svg_content should return 400 Bad Request."""
+ url = reverse('location_svg_edit_save', kwargs={'location_id': self.location.id})
+ response = self.client.post(url, {})
+
+ self.assertEqual(response.status_code, 400)
+
+ def test_post_does_not_modify_live_svg(self):
+ """POST save should only affect the draft, not the live file."""
+ url = reverse('location_svg_edit_save', kwargs={'location_id': self.location.id})
+ self.client.post(url, {'svg_content': '<circle r="999"/>'})
+
+ with default_storage.open(self.location.svg_fragment_filename, 'r') as f:
+ live_content = f.read()
+ self.assertEqual(live_content, self.LIVE_SVG_CONTENT)
+
+ def test_get_not_allowed(self):
+ """GET should return 405 Method Not Allowed."""
+ url = reverse('location_svg_edit_save', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+ self.assertEqual(response.status_code, 405)
+
+
+class TestLocationSvgEditExportView(LocationSvgEditViewTestBase):
+ """Tests for LocationSvgEditExportView - export draft SVG as download."""
+
+ def test_get_returns_svg_file_download(self):
+ """GET should return an SVG file attachment response."""
+ self._create_draft()
+
+ url = reverse('location_svg_edit_export', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'image/svg+xml')
+ self.assertIn('attachment', response['Content-Disposition'])
+
+ def test_get_includes_viewbox_and_svg_wrapper(self):
+ """GET should wrap draft content in a full SVG document with viewBox."""
+ self._create_draft()
+
+ url = reverse('location_svg_edit_export', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ content = response.content.decode('utf-8')
+ self.assertIn('viewBox="0 0 800 600"', content)
+ self.assertIn('<svg', content)
+ self.assertIn('</svg>', content)
+ self.assertIn(self.LIVE_SVG_CONTENT, content)
+
+ def test_get_uses_session_viewbox_if_available(self):
+ """GET should use session viewbox instead of location's default."""
+ self._create_draft()
+
+ session = self.client.session
+ session_key = f'svg_edit_viewbox_{self.location.id}'
+ session[session_key] = '0 0 1600 1200'
+ session.save()
+
+ url = reverse('location_svg_edit_export', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ content = response.content.decode('utf-8')
+ self.assertIn('viewBox="0 0 1600 1200"', content)
+
+ def test_get_filename_derived_from_location_name(self):
+ """The download filename should be derived from the location name."""
+ self._create_draft()
+
+ url = reverse('location_svg_edit_export', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertIn('background-test-location.svg', response['Content-Disposition'])
+
+ def test_get_without_draft_returns_400(self):
+ """GET without an existing draft should return 400."""
+ url = reverse('location_svg_edit_export', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, 400)
+
+
+class TestLocationSvgEditViewBoxView(LocationSvgEditViewTestBase):
+ """Tests for LocationSvgEditViewBoxView - update session viewbox."""
+
+ def test_post_updates_session_viewbox(self):
+ """POST should store the new viewbox dimensions in the session."""
+ self._create_draft()
+
+ url = reverse('location_svg_edit_viewbox', kwargs={'location_id': self.location.id})
+ response = self.client.post(url, {'width': '1200', 'height': '900'})
+
+ self.assertEqual(response.status_code, 200)
+
+ session = self.client.session
+ session_key = f'svg_edit_viewbox_{self.location.id}'
+ self.assertIn('1200', session[session_key])
+ self.assertIn('900', session[session_key])
+
+ def test_post_returns_canvas_html(self):
+ """POST should return HTML content for the SVG canvas pane."""
+ self._create_draft()
+
+ url = reverse('location_svg_edit_viewbox', kwargs={'location_id': self.location.id})
+ response = self.client.post(url, {'width': '1200', 'height': '900'})
+
+ self.assertEqual(response.status_code, 200)
+ # Response should be HTML (canvas template)
+ content_type = response['Content-Type']
+ self.assertIn('text/html', content_type)
+
+ def test_post_invalid_dimensions_returns_400(self):
+ """POST with non-positive dimensions should return 400."""
+ url = reverse('location_svg_edit_viewbox', kwargs={'location_id': self.location.id})
+ response = self.client.post(url, {'width': '0', 'height': '100'})
+ self.assertEqual(response.status_code, 400)
+
+ def test_post_negative_dimensions_returns_400(self):
+ """POST with negative dimensions should return 400."""
+ url = reverse('location_svg_edit_viewbox', kwargs={'location_id': self.location.id})
+ response = self.client.post(url, {'width': '-100', 'height': '100'})
+ self.assertEqual(response.status_code, 400)
+
+ def test_post_non_numeric_dimensions_returns_400(self):
+ """POST with non-numeric dimensions should return 400."""
+ url = reverse('location_svg_edit_viewbox', kwargs={'location_id': self.location.id})
+ response = self.client.post(url, {'width': 'abc', 'height': '100'})
+ self.assertEqual(response.status_code, 400)
+
+ def test_does_not_change_location_model(self):
+ """POST should only update the session, not the database."""
+ self._create_draft()
+ original_viewbox = self.location.svg_view_box_str
+
+ url = reverse('location_svg_edit_viewbox', kwargs={'location_id': self.location.id})
+ self.client.post(url, {'width': '9999', 'height': '9999'})
+
+ self.location.refresh_from_db()
+ self.assertEqual(self.location.svg_view_box_str, original_viewbox)
+
+
+class TestLocationSvgBackgroundView(LocationSvgEditViewTestBase):
+ """Tests for LocationSvgBackgroundView - background options modal."""
+
+ def test_get_shows_background_modal(self):
+ """GET should render the background options modal."""
+ url = reverse('location_svg_background', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'location/edit/modals/location_svg_background.html')
+
+ def test_get_async_returns_json_with_modal(self):
+ """AJAX GET should return JSON with modal content."""
+ url = reverse('location_svg_background', kwargs={'location_id': self.location.id})
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ data = response.json()
+ self.assertIn('modal', data)
+
+ def test_get_includes_location_in_context(self):
+ """GET should include the location object in template context."""
+ url = reverse('location_svg_background', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertEqual(response.context['location'], self.location)
+
+
+class TestLocationSvgTemplateSelectView(LocationSvgEditViewTestBase):
+ """Tests for LocationSvgTemplateSelectView - SVG template selection."""
+
+ def test_get_shows_template_selection_modal(self):
+ """GET should render the template selection modal."""
+ url = reverse('location_svg_template_select', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'location/edit/modals/location_svg_template_select.html')
+
+ def test_get_includes_templates_in_context(self):
+ """GET should include available templates in context."""
+ url = reverse('location_svg_template_select', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertIn('svg_templates', response.context)
+ self.assertIsInstance(response.context['svg_templates'], list)
+
+ def test_post_without_template_name_returns_400(self):
+ """POST without a template_name should return 400."""
+ url = reverse('location_svg_template_select', kwargs={'location_id': self.location.id})
+ response = self.client.post(url, {})
+
+ self.assertEqual(response.status_code, 400)
+
+ def test_get_nonexistent_location_returns_404(self):
+ """GET with invalid location_id should return 404."""
+ url = reverse('location_svg_template_select', kwargs={'location_id': 99999})
+ response = self.client.get(url)
+ self.assertEqual(response.status_code, 404)
diff --git a/src/hi/apps/location/edit/tests/test_views.py b/src/hi/apps/location/edit/tests/test_views.py
index 3686c5db..38d6a1ff 100644
--- a/src/hi/apps/location/edit/tests/test_views.py
+++ b/src/hi/apps/location/edit/tests/test_views.py
@@ -125,7 +125,7 @@ class TestLocationAddView(DualModeViewTestCase):
data = response.json()
home_url = reverse('home')
- self.assertEqual(data['location'], home_url)
+ self.assertTrue(data['location'].startswith(home_url))
# Test that new Location was created
self.assertEqual(Location.objects.count(), initial_location_count + 1)
diff --git a/src/hi/apps/location/edit/urls.py b/src/hi/apps/location/edit/urls.py
index 669596f2..309ab33b 100644
--- a/src/hi/apps/location/edit/urls.py
+++ b/src/hi/apps/location/edit/urls.py
@@ -65,4 +65,44 @@ urlpatterns = [
views.LocationItemPathView.as_view(),
name='location_edit_location_item_path' ),
+ re_path( r'^svg/background/(?P<location_id>\d+)$',
+ views.LocationSvgBackgroundView.as_view(),
+ name='location_svg_background'),
+
+ re_path( r'^svg/template/(?P<location_id>\d+)$',
+ views.LocationSvgTemplateSelectView.as_view(),
+ name='location_svg_template_select'),
+
+ re_path( r'^svg/edit/(?P<location_id>\d+)$',
+ views.LocationSvgEditView.as_view(),
+ name='location_edit_svg_edit'),
+
+ re_path( r'^svg/edit/cancel/(?P<location_id>\d+)$',
+ views.LocationSvgEditCancelView.as_view(),
+ name='location_svg_edit_cancel'),
+
+ re_path( r'^svg/edit/exit/(?P<location_id>\d+)$',
+ views.LocationSvgEditExitView.as_view(),
+ name='location_svg_edit_exit'),
+
+ re_path( r'^svg/edit/viewbox/(?P<location_id>\d+)$',
+ views.LocationSvgEditViewBoxView.as_view(),
+ name='location_svg_edit_viewbox'),
+
+ re_path( r'^svg/edit/revert/(?P<location_id>\d+)$',
+ views.LocationSvgEditRevertView.as_view(),
+ name='location_svg_edit_revert'),
+
+ re_path( r'^svg/edit/save/(?P<location_id>\d+)$',
+ views.LocationSvgEditSaveView.as_view(),
+ name='location_svg_edit_save'),
+
+ re_path( r'^svg/edit/export/(?P<location_id>\d+)$',
+ views.LocationSvgEditExportView.as_view(),
+ name='location_svg_edit_export'),
+
+ re_path( r'^svg/edit/help$',
+ views.LocationSvgEditHelpView.as_view(),
+ name='location_svg_edit_help'),
+
]
diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.py
index 4f717eea..576346a6 100644
--- a/src/hi/apps/location/edit/views.py
+++ b/src/hi/apps/location/edit/views.py
@@ -1,9 +1,14 @@
import json
import logging
+import os
+import re
+import urllib.parse
from django.core.exceptions import BadRequest
+from django.core.files.storage import default_storage
from django.db import transaction
-from django.http import Http404, HttpResponseNotAllowed, HttpResponseRedirect
+from django.http import Http404, HttpResponse, HttpResponseNotAllowed, HttpResponseRedirect
+from django.shortcuts import render
from django.template.loader import get_template
from django.urls import reverse
from django.utils.decorators import method_decorator
@@ -13,6 +18,7 @@ from hi.apps.collection.collection_manager import CollectionManager
from hi.apps.collection.edit.views import CollectionPositionEditView
from hi.apps.collection.models import Collection
import hi.apps.common.antinode as antinode
+from hi.apps.common.svg_models import SvgViewBox
from hi.apps.entity.edit.views import EntityPositionEditView
from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.models import Entity
@@ -145,17 +151,40 @@ class LocationAddView( HiModalView ):
request.view_parameters.view_type = ViewType.LOCATION_VIEW
request.view_parameters.update_location_view( location_view )
request.view_parameters.to_session( request )
-
- redirect_url = reverse('home')
+
+ return self.post_create_redirect( request, location, location_view )
+
+ def post_create_redirect( self, request, location, location_view ):
+ side_url = reverse( 'location_edit_mode', kwargs={ 'location_id': location.id } )
+ redirect_url = (
+ reverse( 'home' )
+ + '?' + urllib.parse.urlencode({ HiSideView.SIDE_URL_PARAM_NAME: side_url })
+ )
return antinode.redirect_response( redirect_url )
-
+
class LocationAddFirstView( LocationAddView ):
def get_template_name( self ) -> str:
return 'location/edit/modals/location_add_first.html'
+ def post_create_redirect( self, request, location, location_view ):
+ redirect_url = reverse( 'home' )
+ return antinode.redirect_response( redirect_url )
+
+@method_decorator( edit_required, name='dispatch' )
+class LocationSvgBackgroundView( HiModalView, LocationViewMixin ):
+
+ def get_template_name( self ) -> str:
+ return 'location/edit/modals/location_svg_background.html'
+
+ def get( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ context = { 'location': location }
+ return self.modal_response( request, context )
+
+
@method_decorator( edit_required, name='dispatch' )
class LocationSvgReplaceView( HiModalView, LocationViewMixin ):
@@ -589,3 +618,322 @@ class LocationItemPathView( View ):
return antinode.response(
main_content = 'OK',
)
+
+
+@method_decorator( edit_required, name='dispatch' )
+class LocationSvgEditView( View, LocationViewMixin ):
+
+ SVG_EDIT_VIEWBOX_SESSION_PREFIX = 'svg_edit_viewbox_'
+
+ def get( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ manager = LocationManager()
+
+ draft_resumed = manager.draft_has_changes( location )
+ if not manager.draft_svg_exists( location ):
+ manager.create_draft_svg( location )
+
+ session_key = f'{self.SVG_EDIT_VIEWBOX_SESSION_PREFIX}{location.id}'
+ if session_key not in request.session:
+ request.session[session_key] = location.svg_view_box_str
+ svg_view_box = SvgViewBox.from_attribute_value( request.session[session_key] )
+
+ draft_svg_filename = manager.get_draft_svg_filename( location )
+
+ context = {
+ 'location': location,
+ 'draft_resumed': draft_resumed,
+ 'draft_svg_filename': draft_svg_filename,
+ 'svg_view_box': svg_view_box,
+ }
+ return render( request, 'location/edit/pages/location_svg_edit.html', context )
+
+
+@method_decorator( edit_required, name='dispatch' )
+class LocationSvgEditCancelView( HiModalView, LocationViewMixin ):
+
+ def get_template_name( self ) -> str:
+ return 'location/edit/modals/location_svg_edit_cancel.html'
+
+ def get( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ manager = LocationManager()
+
+ session_key = f'{LocationSvgEditView.SVG_EDIT_VIEWBOX_SESSION_PREFIX}{location.id}'
+ viewbox_changed = ( request.session.get( session_key ) != location.svg_view_box_str )
+ has_changes = manager.draft_has_changes( location ) or viewbox_changed
+
+ if not has_changes:
+ request.session.pop( session_key, None )
+ manager.delete_draft_svg( location )
+ redirect_url = reverse('home')
+ return antinode.redirect_response( redirect_url )
+
+ context = { 'location': location }
+ return self.modal_response( request, context )
+
+ def post( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ session_key = f'{LocationSvgEditView.SVG_EDIT_VIEWBOX_SESSION_PREFIX}{location.id}'
+ request.session.pop( session_key, None )
+ LocationManager().delete_draft_svg( location )
+ redirect_url = reverse('home')
+ return antinode.redirect_response( redirect_url )
+
+
+@method_decorator( edit_required, name='dispatch' )
+class LocationSvgEditExitView( HiModalView, LocationViewMixin ):
+
+ def get_template_name( self ) -> str:
+ return 'location/edit/modals/location_svg_edit_exit.html'
+
+ def get( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ manager = LocationManager()
+
+ session_key = f'{LocationSvgEditView.SVG_EDIT_VIEWBOX_SESSION_PREFIX}{location.id}'
+ viewbox_changed = ( request.session.get( session_key ) != location.svg_view_box_str )
+ has_changes = manager.draft_has_changes( location ) or viewbox_changed
+
+ if not has_changes:
+ request.session.pop( session_key, None )
+ manager.delete_draft_svg( location )
+ redirect_url = reverse('home')
+ return antinode.redirect_response( redirect_url )
+
+ context = { 'location': location }
+ return self.modal_response( request, context )
+
+ def post( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ manager = LocationManager()
+
+ manager.commit_draft_svg( location )
+
+ session_key = f'{LocationSvgEditView.SVG_EDIT_VIEWBOX_SESSION_PREFIX}{location.id}'
+ viewbox_str = request.session.pop( session_key, None )
+ if viewbox_str:
+ location.svg_view_box_str = viewbox_str
+ location.save()
+
+ redirect_url = reverse('home')
+ return antinode.redirect_response( redirect_url )
+
+
+@method_decorator( edit_required, name='dispatch' )
+class LocationSvgEditViewBoxView( View, LocationViewMixin ):
+
+ def post( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+
+ try:
+ width = float( request.POST.get( 'width', 0 ) )
+ height = float( request.POST.get( 'height', 0 ) )
+ except (TypeError, ValueError):
+ raise BadRequest( 'Invalid viewbox dimensions.' )
+
+ if width <= 0 or height <= 0:
+ raise BadRequest( 'Viewbox dimensions must be positive.' )
+
+ svg_view_box = SvgViewBox( x=0, y=0, width=width, height=height )
+ session_key = f'{LocationSvgEditView.SVG_EDIT_VIEWBOX_SESSION_PREFIX}{location.id}'
+ request.session[session_key] = str( svg_view_box )
+
+ manager = LocationManager()
+ draft_svg_filename = manager.get_draft_svg_filename( location )
+ context = {
+ 'location': location,
+ 'draft_svg_filename': draft_svg_filename,
+ 'svg_view_box': svg_view_box,
+ }
+ template = get_template( 'location/edit/panes/location_svg_edit_canvas.html' )
+ canvas_html = template.render( context, request=request )
+ return HttpResponse( canvas_html )
+
+
+@method_decorator( edit_required, name='dispatch' )
+class LocationSvgEditSaveView( View, LocationViewMixin ):
+
+ def post( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ svg_content = request.POST.get( 'svg_content', '' )
+ if not svg_content:
+ raise BadRequest( 'No SVG content provided.' )
+
+ LocationManager().save_draft_svg( location, svg_content )
+ return HttpResponse( 'OK' )
+
+
+@method_decorator( edit_required, name='dispatch' )
+class LocationSvgEditExportView( View, LocationViewMixin ):
+
+ def get( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ manager = LocationManager()
+
+ draft_filename = manager.get_draft_svg_filename( location )
+ if not default_storage.exists( draft_filename ):
+ raise BadRequest( 'No draft to export.' )
+
+ with default_storage.open( draft_filename, 'r' ) as f:
+ draft_content = f.read()
+
+ session_key = f'{LocationSvgEditView.SVG_EDIT_VIEWBOX_SESSION_PREFIX}{location.id}'
+ viewbox_str = request.session.get( session_key, location.svg_view_box_str )
+
+ svg_content = (
+ '<?xml version="1.0" encoding="utf-8"?>\n'
+ f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{viewbox_str}">\n'
+ f'{draft_content}\n'
+ '</svg>\n'
+ )
+
+ safe_name = location.name.lower().replace( ' ', '-' )
+ filename = f'background-{safe_name}.svg'
+
+ response = HttpResponse( svg_content, content_type='image/svg+xml' )
+ response['Content-Disposition'] = f'attachment; filename="{filename}"'
+ return response
+
+
+@method_decorator( edit_required, name='dispatch' )
+class LocationSvgEditRevertView( HiModalView, LocationViewMixin ):
+
+ def get_template_name( self ) -> str:
+ return 'location/edit/modals/location_svg_edit_revert.html'
+
+ def get( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ manager = LocationManager()
+
+ session_key = f'{LocationSvgEditView.SVG_EDIT_VIEWBOX_SESSION_PREFIX}{location.id}'
+ viewbox_changed = ( request.session.get( session_key ) != location.svg_view_box_str )
+ has_changes = manager.draft_has_changes( location ) or viewbox_changed
+
+ if not has_changes:
+ return self.modal_response(
+ request,
+ template_name='location/edit/modals/location_svg_edit_revert_no_changes.html',
+ )
+
+ context = { 'location': location }
+ return self.modal_response( request, context )
+
+ def post( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ manager = LocationManager()
+
+ manager.create_draft_svg( location )
+
+ session_key = f'{LocationSvgEditView.SVG_EDIT_VIEWBOX_SESSION_PREFIX}{location.id}'
+ request.session[session_key] = location.svg_view_box_str
+
+ redirect_url = reverse( 'location_edit_svg_edit', kwargs={ 'location_id': location.id } )
+ return antinode.redirect_response( redirect_url )
+
+
+@method_decorator( edit_required, name='dispatch' )
+class LocationSvgTemplateSelectView( HiModalView, LocationViewMixin ):
+
+ def get_template_name( self ) -> str:
+ return 'location/edit/modals/location_svg_template_select.html'
+
+ def get( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ templates = self._scan_templates()
+ context = {
+ 'location': location,
+ 'svg_templates': templates,
+ }
+ return self.modal_response( request, context )
+
+ def post( self, request, *args, **kwargs ):
+ location = self.get_location( request, *args, **kwargs )
+ template_name = request.POST.get( 'template_name', '' )
+ if not template_name:
+ raise BadRequest( 'No template selected.' )
+
+ template_path = os.path.join(
+ forms.LocationSvgFileForm.BACKGROUNDS_TEMPLATE_DIR, template_name,
+ )
+ LocationManager().update_location_svg_from_template(
+ location = location,
+ svg_template_name = template_path,
+ )
+
+ redirect_url = reverse('home')
+ return antinode.redirect_response( redirect_url )
+
+ def _scan_templates( self ):
+ from hi.apps.profiles import apps as profiles_apps
+ template_dir = os.path.join(
+ os.path.dirname( profiles_apps.__file__ ),
+ 'templates', 'profiles', 'svg', 'backgrounds',
+ )
+ templates = []
+ if not os.path.isdir( template_dir ):
+ return templates
+
+ for filename in sorted( os.listdir( template_dir ) ):
+ if not filename.endswith( '.svg' ):
+ continue
+
+ filepath = os.path.join( template_dir, filename )
+ location_name = self._read_svg_hi_name( filepath )
+ profile_name = self._derive_profile_name( filename )
+
+ if location_name and profile_name:
+ name = f'{profile_name} \u2014 {location_name}'
+ elif location_name:
+ name = location_name
+ else:
+ name = profile_name or filename
+
+ template_path = os.path.join(
+ forms.LocationSvgFileForm.BACKGROUNDS_TEMPLATE_DIR, filename,
+ )
+ templates.append({
+ 'template_name': filename,
+ 'template_path': template_path,
+ 'name': name,
+ })
+ return templates
+
+ def _read_svg_hi_name( self, filepath ):
+ """Read the data-hi-name attribute from the SVG file."""
+ try:
+ with open( filepath, 'r' ) as f:
+ # Only need to check the first few lines
+ for _ in range( 5 ):
+ line = f.readline()
+ if not line:
+ break
+ match = re.search( r'data-hi-name="([^"]*)"', line )
+ if match:
+ return match.group( 1 )
+ except OSError:
+ pass
+ return None
+
+ def _derive_profile_name( self, filename ):
+ """
+ Derive a display-friendly profile name from the filename.
+ e.g., 'single_story-0.svg' -> 'Single Story',
+ 'blank.svg' -> None (no profile prefix).
+ """
+ stem = filename.replace( '.svg', '' )
+ # Match profile-type prefix before the final '-N' index
+ parts = stem.rsplit( '-', 1 )
+ if len( parts ) == 2 and parts[1].isdigit():
+ return parts[0].replace( '_', ' ' ).replace( '-', ' ' ).title()
+ return None
+
+
+class LocationSvgEditHelpView( HiModalView ):
+
+ def get_template_name( self ) -> str:
+ return 'location/edit/modals/location_svg_edit_help.html'
+
+ def get( self, request, *args, **kwargs ):
+ return self.modal_response( request )
+
diff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.py
index 4adee6bd..445650e5 100644
--- a/src/hi/apps/location/location_manager.py
+++ b/src/hi/apps/location/location_manager.py
@@ -5,9 +5,12 @@ from typing import List
from django.core.files.storage import default_storage, FileSystemStorage
from django.db import transaction
from django.http import HttpRequest
+from django.template.loader import render_to_string
+from hi.apps.common.file_utils import derive_new_unique_filename
from hi.apps.common.singleton import Singleton
from hi.apps.common.svg_models import SvgViewBox
+from hi.apps.common.svg_utils import process_svg_content
from hi.apps.monitor.status_display_manager import StatusDisplayManager
from .enums import LocationViewType, SvgStyleName
@@ -93,9 +96,100 @@ class LocationManager(Singleton):
location.svg_fragment_filename = svg_fragment_filename
location.svg_view_box_str = str( svg_viewbox )
location.save()
-
+
return
-
+
+ def render_svg_template_to_media( self, svg_template_name ):
+ """
+ Render an SVG template, process it, and write to MEDIA_ROOT.
+ Returns the result dict from process_svg_content (includes
+ svg_fragment_filename, svg_fragment_content, svg_viewbox).
+ Does NOT update any Location model.
+ """
+ svg_content = render_to_string( svg_template_name )
+ source_filename = os.path.basename( svg_template_name )
+ result = process_svg_content(
+ svg_content = svg_content,
+ media_destination_directory = 'location/svg',
+ source_filename = source_filename,
+ )
+ self._ensure_directory_exists( result['svg_fragment_filename'] )
+ with default_storage.open( result['svg_fragment_filename'], 'w' ) as dest:
+ dest.write( result['svg_fragment_content'] )
+ return result
+
+ def update_location_svg_from_template( self, location, svg_template_name ):
+ """
+ Render an SVG template, process it, write to MEDIA_ROOT, and update
+ the Location model.
+ """
+ result = self.render_svg_template_to_media( svg_template_name )
+ self.update_location_svg(
+ location = location,
+ svg_fragment_filename = result['svg_fragment_filename'],
+ svg_fragment_content = result['svg_fragment_content'],
+ svg_viewbox = result['svg_viewbox'],
+ )
+ return result
+
+ def get_draft_svg_filename( self, location : Location ) -> str:
+ base, ext = os.path.splitext( location.svg_fragment_filename )
+ return f'{base}.draft{ext}'
+
+ def draft_svg_exists( self, location : Location ) -> bool:
+ return default_storage.exists( self.get_draft_svg_filename( location ) )
+
+ def draft_has_changes( self, location : Location ) -> bool:
+ draft_filename = self.get_draft_svg_filename( location )
+ if not default_storage.exists( draft_filename ):
+ return False
+ with default_storage.open( location.svg_fragment_filename, 'r' ) as f:
+ live_content = f.read()
+ with default_storage.open( draft_filename, 'r' ) as f:
+ draft_content = f.read()
+ return bool( live_content != draft_content )
+
+ def delete_draft_svg( self, location : Location ) -> None:
+ draft_filename = self.get_draft_svg_filename( location )
+ if default_storage.exists( draft_filename ):
+ default_storage.delete( draft_filename )
+ return
+
+ def create_draft_svg( self, location : Location ) -> str:
+ draft_filename = self.get_draft_svg_filename( location )
+ self._ensure_directory_exists( draft_filename )
+ with default_storage.open( location.svg_fragment_filename, 'r' ) as source:
+ content = source.read()
+ with default_storage.open( draft_filename, 'w' ) as dest:
+ dest.write( content )
+ return draft_filename
+
+ def save_draft_svg( self, location : Location, content : str ) -> None:
+ draft_filename = self.get_draft_svg_filename( location )
+ self._ensure_directory_exists( draft_filename )
+ with default_storage.open( draft_filename, 'w' ) as dest:
+ dest.write( content )
+ return
+
+ def commit_draft_svg( self, location : Location ) -> None:
+ draft_filename = self.get_draft_svg_filename( location )
+ with default_storage.open( draft_filename, 'r' ) as source:
+ content = source.read()
+
+ # Write to a new unique filename rather than overwriting the original.
+ # This leaves the previous version as an orphan in MEDIA_ROOT,
+ # providing a natural backup in case of accidental changes.
+ new_filename = derive_new_unique_filename( location.svg_fragment_filename )
+ self._ensure_directory_exists( new_filename )
+ with default_storage.open( new_filename, 'w' ) as dest:
+ dest.write( content )
+
+ location.svg_fragment_filename = new_filename
+ location.save()
+
+ default_storage.delete( draft_filename )
+ return
+
def _ensure_directory_exists( self, filepath ):
if isinstance( default_storage, FileSystemStorage ):
directory = os.path.dirname( default_storage.path( filepath ))
diff --git a/src/hi/apps/location/templates/location/edit/modals/location_svg_background.html b/src/hi/apps/location/templates/location/edit/modals/location_svg_background.html
new file mode 100644
index 00000000..ce701fed
--- /dev/null
+++ b/src/hi/apps/location/templates/location/edit/modals/location_svg_background.html
@@ -0,0 +1,49 @@
+{% extends "modals/action_done.html" %}
+{% load icons %}
+
+{% block modal_dialog_class %}hi-modal-dialog-500{% endblock %}
+
+{% block title_text %}
+Background Image
+{% endblock %}
+
+{% block body %}
+<div class="d-flex flex-column gap-3 py-2">
+
+ <a href="{% url 'location_edit_svg_edit' location_id=location.id %}"
+ class="btn btn-outline-primary btn-block text-start p-3">
+ <div class="d-flex align-items-center">
+ {% icon "edit" size="xl" %}
+ <div class="pl-3 text-left">
+ <div class="font-weight-bold">Edit Current</div>
+ <div><small class="text-muted"">Open the background editor</small></div>
+ </div>
+ </div>
+ </a>
+
+ <a href="{% url 'location_svg_template_select' location_id=location.id %}"
+ class="btn btn-outline-primary btn-block text-start p-3" role="button"
+ data-async="true">
+ <div class="d-flex align-items-center">
+ {% icon "layers" size="xl" %}
+ <div class="pl-3 text-left">
+ <div class="font-weight-bold">Choose a Template</div>
+ <div><small class="text-muted"">Start from a built-in floor plan</small></div>
+ </div>
+ </div>
+ </a>
+
+ <a href="{% url 'location_edit_svg_replace' location_id=location.id %}"
+ class="btn btn-outline-primary btn-block text-start p-3" role="button"
+ data-async="true">
+ <div class="d-flex align-items-center">
+ {% icon "upload" size="xl" %}
+ <div class="pl-3 text-left">
+ <div class="font-weight-bold">Upload SVG</div>
+ <div><small class="text-muted">Use your own SVG file</small></div>
+ </div>
+ </div>
+ </a>
+
+</div>
+{% endblock %}
diff --git a/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_cancel.html b/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_cancel.html
new file mode 100644
index 00000000..bfc6227d
--- /dev/null
+++ b/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_cancel.html
@@ -0,0 +1,30 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% block preamble %}
+<form action="{% url 'location_svg_edit_cancel' location_id=location.id %}"
+ method="post" enctype="multipart/form-data"
+ class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Discard Changes?
+{% endblock %}
+
+{% block body %}
+<div>
+ <p>Any changes you made to the background image for <strong>{{ location.name }}</strong> will be discarded.</p>
+ <p>This cannot be undone.</p>
+</div>
+{% endblock %}
+
+{% block action_right %}
+<button id="hi-location-svg-edit-cancel-button" type="submit" class="btn btn-danger">
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}DISCARD CHANGES
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_exit.html b/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_exit.html
new file mode 100644
index 00000000..2c96665a
--- /dev/null
+++ b/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_exit.html
@@ -0,0 +1,30 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% block preamble %}
+<form action="{% url 'location_svg_edit_exit' location_id=location.id %}"
+ method="post" enctype="multipart/form-data"
+ class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Save Space Background?
+{% endblock %}
+
+{% block body %}
+<div>
+ <p>Save your changes to the background image for <strong>{{ location.name }}</strong>?</p>
+ <p>This will replace the current background with your edited version.</p>
+</div>
+{% endblock %}
+
+{% block action_right %}
+<button id="hi-location-svg-edit-exit-button" type="submit" class="btn btn-primary">
+ {% icon "save" size="sm" css_class="hi-icon-left" %}SAVE CHANGES
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_help.html b/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_help.html
new file mode 100644
index 00000000..a479bab4
--- /dev/null
+++ b/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_help.html
@@ -0,0 +1,146 @@
+{% extends "modals/action_done.html" %}
+{% load icons %}
+
+{% block modal_dialog_class %}hi-modal-dialog-700{% endblock %}
+
+{% block title_text %}
+Background Editor Help
+{% endblock %}
+
+{% block body %}
+
+<div class="editing-help-guide">
+ <div class="guide-header">
+ {% icon "edit" size="lg" color="primary" %}
+ <h5>Quick Reference Guide</h5>
+ </div>
+
+ <div class="editing-help-categories">
+ <!-- General -->
+ <div class="help-category">
+ <div class="category-header">
+ <div class="category-icon">
+ {% icon "move" size="sm" color="primary" %}
+ </div>
+ <h6 class="category-title">General</h6>
+ </div>
+ <ul class="help-actions">
+ <li>
+ <span class="action-method">Drag from Palette</span>
+ <span class="action-description">Drop onto canvas to add element</span>
+ </li>
+ <li>
+ <span class="action-method">Click & Drag</span>
+ <span class="action-description">Pan the canvas</span>
+ </li>
+ <li>
+ <span class="action-method">Mouse Wheel / + / -</span>
+ <span class="action-description">Zoom in/out</span>
+ </li>
+ <li>
+ <span class="action-method">CTRL + Z</span>
+ <span class="action-description">Undo last change</span>
+ </li>
+ <li>
+ <span class="action-method">SHIFT + Drag</span>
+ <span class="action-description">Fine positioning (bypass snap)</span>
+ </li>
+ <li>
+ <span class="action-method">Snap (footer)</span>
+ <span class="action-description">Set grid size, 0 to disable</span>
+ </li>
+ </ul>
+ </div>
+
+ <!-- Icon Editing (Doors, Windows) -->
+ <div class="help-category">
+ <div class="category-header">
+ <div class="category-icon">
+ {% icon "zoom" size="sm" color="primary" %}
+ </div>
+ <h6 class="category-title">Icon Editing</h6>
+ </div>
+ <ul class="help-actions">
+ <li>
+ <span class="action-method">Click</span>
+ <span class="action-description">Select icon</span>
+ </li>
+ <li>
+ <span class="action-method">Drag</span>
+ <span class="action-description">Move icon</span>
+ </li>
+ <li>
+ <span class="action-method">S + Drag/Wheel/+/-</span>
+ <span class="action-description">Scale icon</span>
+ </li>
+ <li>
+ <span class="action-method">R + Drag/Wheel/+/-</span>
+ <span class="action-description">Rotate icon</span>
+ </li>
+ <li>
+ <span class="action-method">M</span>
+ <span class="action-description">Mirror horizontally</span>
+ </li>
+ <li>
+ <span class="action-method">X / DEL</span>
+ <span class="action-description">Delete selected icon</span>
+ </li>
+ <li>
+ <span class="action-method">ESC</span>
+ <span class="action-description">Deselect</span>
+ </li>
+ </ul>
+ </div>
+
+ <!-- Path Editing (Walls, Floors, Areas) -->
+ <div class="help-category help-category-wide">
+ <div class="category-header">
+ <div class="category-icon">
+ {% icon "path" size="sm" color="primary" %}
+ </div>
+ <h6 class="category-title">Path Editing</h6>
+ </div>
+ <div class="help-actions-columns">
+ <ul class="help-actions">
+ <li>
+ <span class="action-method">Click</span>
+ <span class="action-description">Select path to edit vertices</span>
+ </li>
+ <li>
+ <span class="action-method">Drag Point</span>
+ <span class="action-description">Move single vertex</span>
+ </li>
+ <li>
+ <span class="action-method">CTRL + Drag</span>
+ <span class="action-description">Move entire path</span>
+ </li>
+ <li>
+ <span class="action-method">I / INSERT</span>
+ <span class="action-description">Insert vertex</span>
+ </li>
+ </ul>
+ <ul class="help-actions">
+ <li>
+ <span class="action-method">X / DEL</span>
+ <span class="action-description">Delete vertex</span>
+ </li>
+ <li>
+ <span class="action-method">A / +</span>
+ <span class="action-description">Add new path segment</span>
+ </li>
+ <li>
+ <span class="action-method">CTRL + X</span>
+ <span class="action-description">Delete entire path</span>
+ </li>
+ <li>
+ <span class="action-method">ESC</span>
+ <span class="action-description">Finish path editing</span>
+ </li>
+ </ul>
+ </div>
+ </div>
+
+ </div>
+</div>
+
+{% endblock %}
diff --git a/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_revert.html b/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_revert.html
new file mode 100644
index 00000000..73619ab2
--- /dev/null
+++ b/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_revert.html
@@ -0,0 +1,29 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% block preamble %}
+<form action="{% url 'location_svg_edit_revert' location_id=location.id %}"
+ method="post" class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Revert All Changes?
+{% endblock %}
+
+{% block body %}
+<div>
+ <p>This will discard all edits and restore the background to the state it was in when you entered the editor.</p>
+ <p>This cannot be undone.</p>
+</div>
+{% endblock %}
+
+{% block action_right %}
+<button id="hi-location-svg-edit-revert-button" type="submit" class="btn btn-danger">
+ {% icon "undo" size="sm" css_class="hi-icon-left" %}REVERT
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_revert_no_changes.html b/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_revert_no_changes.html
new file mode 100644
index 00000000..91c037de
--- /dev/null
+++ b/src/hi/apps/location/templates/location/edit/modals/location_svg_edit_revert_no_changes.html
@@ -0,0 +1,12 @@
+{% extends "modals/action_ok.html" %}
+{% load icons %}
+
+{% block title_text %}
+Nothing to Revert
+{% endblock %}
+
+{% block body %}
+<div>
+ <p>No changes have been made since the last save. There is nothing to revert.</p>
+</div>
+{% endblock %}
diff --git a/src/hi/apps/location/templates/location/edit/modals/location_svg_replace.html b/src/hi/apps/location/templates/location/edit/modals/location_svg_replace.html
index 1909bd12..c6ee66bd 100644
--- a/src/hi/apps/location/templates/location/edit/modals/location_svg_replace.html
+++ b/src/hi/apps/location/templates/location/edit/modals/location_svg_replace.html
@@ -9,7 +9,7 @@
{% endblock %}
{% block title_text %}
-Replace Space Background Image
+Replace Space Background
{% endblock %}
{% block body %}
diff --git a/src/hi/apps/location/templates/location/edit/modals/location_svg_template_select.html b/src/hi/apps/location/templates/location/edit/modals/location_svg_template_select.html
new file mode 100644
index 00000000..26c26304
--- /dev/null
+++ b/src/hi/apps/location/templates/location/edit/modals/location_svg_template_select.html
@@ -0,0 +1,38 @@
+{% extends "modals/action_cancel.html" %}
+{% load icons %}
+
+{% block modal_dialog_class %}hi-modal-dialog-700{% endblock %}
+
+{% block title_text %}
+Choose a Template
+{% endblock %}
+
+{% block body %}
+<p class="text-muted text-center">
+ Select a starting template for your background.
+</p>
+
+<div class="d-flex flex-wrap gap-3 justify-content-center py-2">
+ {% for tmpl in svg_templates %}
+ <form action="{% url 'location_svg_template_select' location_id=location.id %}"
+ method="post" class="form" data-async="modal" style="display: inline;">
+ {% csrf_token %}
+ <input type="hidden" name="template_name" value="{{ tmpl.template_name }}">
+ <button type="submit" class="btn btn-outline-secondary p-2 hi-svg-template-card"
+ title="{{ tmpl.name }}">
+ <div class="hi-svg-template-thumbnail">
+ <svg viewBox="0 0 2000 2000" class="hi-location-view-svg"
+ width="100%" height="100%" preserveAspectRatio="xMidYMid meet">
+ {% include tmpl.template_path %}
+ </svg>
+ </div>
+ <div class="hi-svg-template-name">{{ tmpl.name }}</div>
+ </button>
+ </form>
+ {% endfor %}
+</div>
+
+<p class="text-muted text-center pt-2">
+ This will replace the current background image.
+</p>
+{% endblock %}
diff --git a/src/hi/apps/location/templates/location/edit/pages/location_svg_edit.html b/src/hi/apps/location/templates/location/edit/pages/location_svg_edit.html
new file mode 100644
index 00000000..8b2c480e
--- /dev/null
+++ b/src/hi/apps/location/templates/location/edit/pages/location_svg_edit.html
@@ -0,0 +1,109 @@
+{% extends "pages/base.html" %}
+{% load pipeline %}
+{% load icons %}
+
+{% block head_title %}Background Editor — Home Information{% endblock %}
+
+{% block head_css %}
+{% stylesheet 'css_location_svg_edit' %}
+{% endblock %}
+
+{% block content %}
+<div id="{{ DIVID.LOCATION_SVG_EDIT_TOP }}" class="fixed-top">
+ <div class="d-flex align-items-center">
+ <div id="{{ DIVID.LOCATION_SVG_EDIT_PALETTE }}" class="hi-palette-container flex-grow-1">
+ </div>
+
+ <div class="hi-svg-edit-buttons d-flex flex-nowrap align-items-center">
+ <a href="{% url 'location_svg_edit_cancel' location_id=location.id %}"
+ id="hi-location-svg-edit-cancel-link" class="btn btn-outline-tertiary mx-1" role="button"
+ data-async="true">
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}DISCARD
+ </a>
+ <a href="{% url 'location_svg_edit_exit' location_id=location.id %}"
+ id="hi-location-svg-edit-exit-link" class="btn btn-primary mx-1" role="button"
+ data-async="true">
+ {% icon "save" size="sm" css_class="hi-icon-left" %}DONE
+ </a>
+ </div>
+ </div>
+</div>
+
+<div id="{{ DIVID.LOCATION_SVG_EDIT_BOTTOM }}" class="fixed-bottom">
+ <div class="d-flex justify-content-between align-items-center px-3 h-100">
+ <div class="d-flex align-items-center">
+ <span class="mr-3" style="line-height: 1.2;">
+ <span class="d-block text-muted" style="font-size: 0.7rem; font-weight: 600; letter-spacing: 0.03em;">BACKGROUND EDITOR</span>
+ <span class="d-block" style="font-size: 1rem; font-weight: 600; color: var(--svg-editor-border-color);">{{ location.name }}</span>
+ </span>
+ <span class="text-muted mx-2" style="font-size: 0.85rem;">|</span>
+ <form action="{% url 'location_svg_edit_viewbox' location_id=location.id %}"
+ method="post" class="form d-flex align-items-center"
+ data-async="#{{ DIVID.LOCATION_SVG_EDIT_CANVAS_CONTAINER }}">
+ {% csrf_token %}
+ <label class="me-2 mb-0 mx-1" style="font-size: 0.85rem;"><b>Canvas Size:</b></label>
+ <label class="me-1 mb-0 mx-1" style="font-size: 0.85rem;">W</label>
+ <input type="number" name="width" class="form-control form-control-sm"
+ style="width: 6rem;" value="{{ svg_view_box.width|floatformat:0 }}" min="100" step="50">
+ <label class="ms-2 me-1 mb-0 mx-1" style="font-size: 0.85rem;">H</label>
+ <input type="number" name="height" class="form-control form-control-sm"
+ style="width: 6rem;" value="{{ svg_view_box.height|floatformat:0 }}" min="100" step="50">
+ <button type="submit" class="btn btn-sm btn-outline-primary ms-2 mx-1">Apply</button>
+ </form>
+ <span class="text-muted mx-2" style="font-size: 0.85rem;">|</span>
+ <label class="me-1 mb-0 mx-1" style="font-size: 0.85rem;"><b>Snap:</b></label>
+ <input type="number" id="hi-svg-edit-snap-grid" class="form-control form-control-sm"
+ style="width: 4rem;" value="5" min="0" max="50" step="1"
+ title="Snap grid in screen pixels (0 to disable, hold Shift for fine mode)">
+ <label class="ms-1 mb-0" style="font-size: 0.85rem;">px</label>
+ </div>
+ <div class="d-flex flex-nowrap gap-2 align-items-center">
+ <a href="{% url 'location_svg_edit_revert' location_id=location.id %}"
+ id="hi-location-svg-edit-revert-link" class="btn btn-sm btn-outline-secondary text-nowrap mx-1" role="button"
+ data-async="true">
+ {% icon "undo" size="sm" css_class="hi-icon-left" %}REVERT
+ </a>
+ <a href="{% url 'location_svg_edit_export' location_id=location.id %}"
+ class="btn btn-sm btn-outline-primary text-nowrap mx-1" role="button">
+ {% icon "download" size="sm" css_class="hi-icon-left" %}EXPORT
+ </a>
+ <a href="{% url 'location_svg_edit_help' %}"
+ class="btn btn-tertiary text-nowrap mx-1" role="button"
+ data-async="true">
+ {% icon "question-circle" size="sm" css_class="hi-icon-left" %}HELP
+ </a>
+ </div>
+ </div>
+</div>
+
+<div id="hi-svg-edit-warnings" class="hi-svg-edit-warnings"
+ style="margin-top: var(--svg-editor-top-height);">
+ {% if draft_resumed %}
+ <div class="alert alert-info alert-dismissible fade show m-0 py-1 px-3 rounded-0" role="alert" style="font-size: 0.85rem;">
+ {% icon "info-circle" size="sm" css_class="hi-icon-left" %}
+ Resumed draft from previous session. Use CANCEL to discard.
+ <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
+ </div>
+ {% endif %}
+ <div id="{{ DIVID.LOCATION_SVG_EDIT_CONFORMANCE_WARNING }}" class="alert alert-warning alert-dismissible fade show m-0 py-1 px-3 rounded-0" role="alert" style="font-size: 0.85rem; display: none;">
+ {% icon "warning" size="sm" css_class="hi-icon-left" %}
+ Not all elements in this background are editable. It contains some imported content. Only elements added in this editor are editable.
+ <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
+ </div>
+</div>
+
+<div id="{{ DIVID.LOCATION_SVG_EDIT_MAIN }}" class="container-fluid"
+ style="margin-bottom: var(--svg-editor-bottom-height);">
+ <div id="{{ DIVID.LOCATION_SVG_EDIT_CANVAS_CONTAINER }}">
+ {% include "location/edit/panes/location_svg_edit_canvas.html" %}
+ </div>
+</div>
+{% endblock %}
+
+{% block footer_post_javascript %}
+{% javascript 'js_location_svg_edit' %}
+<script>
+ Hi.SvgEdit.saveUrl = "{% url 'location_svg_edit_save' location_id=location.id %}";
+ Hi.SvgEdit.csrfToken = "{{ csrf_token }}";
+</script>
+{% endblock %}
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_add_form.html b/src/hi/apps/location/templates/location/edit/panes/location_add_form.html
index 563bf431..73f06c92 100644
--- a/src/hi/apps/location/templates/location/edit/panes/location_add_form.html
+++ b/src/hi/apps/location/templates/location/edit/panes/location_add_form.html
@@ -18,11 +18,3 @@
{{ location_add_form.name }}
<small class="form-error text-danger">{{ location_add_form.name.errors }}</small>
</div>
-
-<p class="my-3">
- You may optionally add an image (SVG format) showing your property and/or house layout.
-</p>
-{% include "common/panes/svg_file_form.html" with svg_file_form=location_add_form %}
-<p class="my-2 text-muted">
- If you skip adding an image now, we'll uses a predefined image for you. You can update the location's image at any time.
-</p>
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_properties_edit.html b/src/hi/apps/location/templates/location/edit/panes/location_properties_edit.html
index a9d614ef..8651e070 100644
--- a/src/hi/apps/location/templates/location/edit/panes/location_properties_edit.html
+++ b/src/hi/apps/location/templates/location/edit/panes/location_properties_edit.html
@@ -1,4 +1,5 @@
{% load icons %}
+
<form action="{% url 'location_properties_edit' location_id=location.id %}"
method="post"
class="form" data-async="true">
@@ -15,16 +16,17 @@
</div>
</form>
+<hr />
{% if request.view_parameters.is_editing %}
<div class="sidebar-form-actions">
- <a href="{% url 'location_edit_svg_replace' location_id=location.id %}"
- id="hi-svg-replace-link" class="btn btn-sm btn-secondary btn-block btn-control" role="button"
+ <a href="{% url 'location_svg_background' location_id=location.id %}"
+ id="hi-svg-background-link" class="btn btn-tertiary btn-block" role="button"
data-async="true">
- {% icon "upload" size="sm" css_class="hi-icon-left" %}REPLACE BACKGROUND IMAGE
+ {% icon "layers" size="sm" css_class="hi-icon-left" %}BACKGROUND IMAGE
</a>
</div>
-<div class="sidebar-form-actions">
+<div class="sidebar-form-actions pt-4">
<a href="{% url 'location_edit_location_delete' location_id=location.id %}"
id="hi-delete-location-link" class="btn btn-sm btn-danger btn-block btn-control" role="button"
data-async="true">
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_svg_edit_canvas.html b/src/hi/apps/location/templates/location/edit/panes/location_svg_edit_canvas.html
new file mode 100644
index 00000000..79485199
--- /dev/null
+++ b/src/hi/apps/location/templates/location/edit/panes/location_svg_edit_canvas.html
@@ -0,0 +1,22 @@
+{% load static %}
+{% load common_tags %}
+<link rel="stylesheet" href="{% static 'css/svg-location-color.css' %}">
+<div id="{{ DIVID.LOCATION_SVG_EDIT_CANVAS }}" class="hi-location-view">
+ <svg id="{{ DIVID.LOCATION_SVG_EDIT_SVG }}"
+ class="hi-location-view-svg"
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="{{ svg_view_box }}"
+ extents="{{ svg_view_box }}"
+ width="100%" height="100%" preserveAspectRatio="xMidYMid meet">
+ <defs>
+ {% include "location/panes/svg_fill_patterns_color.html" %}
+ </defs>
+ {% include "location/edit/svg/svg_edit_palette.svg" %}
+ <rect class="hi-svg-edit-boundary" x="{{ svg_view_box.x }}" y="{{ svg_view_box.y }}"
+ width="{{ svg_view_box.width }}" height="{{ svg_view_box.height }}"
+ pointer-events="none" />
+ <g class="hi-location-view-base">
+ {% include_media_template draft_svg_filename %}
+ </g>
+ </svg>
+</div>
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_form.html b/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_form.html
index 06eac803..fba410e3 100644
--- a/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_form.html
+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_form.html
@@ -60,7 +60,7 @@
<div class="sidebar-form-field">
<label for="{{ location_view_edit_form.svg_rotate.id_for_label }}" class="sidebar-form-label">{{ location_view_edit_form.svg_rotate.label }}</label>
- <input type="number" id="{{ location_view_edit_form.svg_rotate.id_for_label }}" name="{{ location_view_edit_form.svg_rotate.name }}" value="{{ location_view_edit_form.svg_rotate.value }}" class="sidebar-form-input">
+ <input type="number" step="any" id="{{ location_view_edit_form.svg_rotate.id_for_label }}" name="{{ location_view_edit_form.svg_rotate.name }}" value="{{ location_view_edit_form.svg_rotate.value }}" class="sidebar-form-input">
{% if location_view_edit_form.svg_rotate.errors %}
<div class="sidebar-form-error">{{ location_view_edit_form.svg_rotate.errors }}</div>
{% endif %}
diff --git a/src/hi/apps/location/templates/location/edit/svg/svg_edit_palette.svg b/src/hi/apps/location/templates/location/edit/svg/svg_edit_palette.svg
new file mode 100644
index 00000000..a3f1f86a
--- /dev/null
+++ b/src/hi/apps/location/templates/location/edit/svg/svg_edit_palette.svg
@@ -0,0 +1,89 @@
+<defs>
+ <!-- Structural: Icons -->
+ <g id="hi-door-standard" data-bg-edit-type="icon" data-bg-label="Door" data-bg-category="structural" data-bg-layer="240">
+ <path class="doors" d="M 0,0 L 70.71,70.71" />
+ <path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" />
+ </g>
+ <g id="hi-window-standard" data-bg-edit-type="icon" data-bg-label="Window" data-bg-category="structural" data-bg-layer="250">
+ <path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" />
+ </g>
+ <g id="hi-sliding-door" data-bg-edit-type="icon" data-bg-label="Door (alt)" data-bg-category="structural" data-bg-layer="260">
+ <path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" />
+ <line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" />
+ </g>
+
+ <!-- Structural: Paths -->
+ <g id="hi-dead-space" data-bg-edit-type="closed" data-bg-label="Dead Space" data-bg-category="structural" data-bg-layer="135">
+ <path class="dead-space" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-exterior-walls" data-bg-edit-type="open" data-bg-label="Ext. Wall" data-bg-category="structural" data-bg-layer="220">
+ <path class="exterior-wall-stroke" d="M 0,0 L 200,0" />
+ </g>
+ <g id="hi-interior-walls" data-bg-edit-type="open" data-bg-label="Int. Wall" data-bg-category="structural" data-bg-layer="210">
+ <path class="interior-wall-stroke" d="M 0,0 L 200,0" />
+ </g>
+ <g id="hi-interior-floors" data-bg-edit-type="closed" data-bg-label="Floor" data-bg-category="structural" data-bg-layer="130">
+ <path class="interior-floors" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-transitions" data-bg-edit-type="open" data-bg-label="Transition" data-bg-category="structural" data-bg-layer="190">
+ <path class="transitions" d="M 0,0 L 200,0" />
+ </g>
+
+ <!-- Features -->
+ <g id="hi-countertops" data-bg-edit-type="closed" data-bg-label="Counter" data-bg-category="features" data-bg-layer="150">
+ <path class="countertops" d="M 0,0 L 80,0 L 80,30 L 0,30 Z" />
+ </g>
+ <g id="hi-fireplaces" data-bg-edit-type="closed" data-bg-label="Fireplace" data-bg-category="features" data-bg-layer="180">
+ <path class="fireplaces" d="M 0,0 L 60,0 L 60,40 L 0,40 Z" />
+ </g>
+ <g id="hi-stairs" data-bg-edit-type="icon" data-bg-label="Stairs" data-bg-category="features" data-bg-layer="200">
+ <path class="stairs" d="M 0,0 L 60,0 L 60,10 L 0,10 Z M 0,10 L 60,10 L 60,20 L 0,20 Z M 0,20 L 60,20 L 60,30 L 0,30 Z M 0,30 L 60,30 L 60,40 L 0,40 Z M 0,40 L 60,40 L 60,50 L 0,50 Z M 0,50 L 60,50 L 60,60 L 0,60 Z M 0,60 L 60,60 L 60,70 L 0,70 Z M 0,70 L 60,70 L 60,80 L 0,80 Z" />
+ </g>
+ <g id="hi-shelves" data-bg-edit-type="closed" data-bg-label="Shelves" data-bg-category="features" data-bg-layer="160">
+ <path class="shelves" d="M 0,0 L 80,0 L 80,20 L 0,20 Z" />
+ </g>
+ <g id="hi-cabinets" data-bg-edit-type="closed" data-bg-label="Cabinet" data-bg-category="features" data-bg-layer="170">
+ <path class="cabinets" d="M 0,0 L 80,0 L 80,20 L 0,20 Z" />
+ </g>
+ <g id="hi-tiles" data-bg-edit-type="closed" data-bg-label="Tile" data-bg-category="features" data-bg-layer="140">
+ <path class="tiles" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+
+ <!-- Exterior -->
+ <g id="hi-grass" data-bg-edit-type="closed" data-bg-label="Grass" data-bg-category="exterior" data-bg-layer="20">
+ <path class="grass" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-ground" data-bg-edit-type="closed" data-bg-label="Ground" data-bg-category="exterior" data-bg-layer="30">
+ <path class="ground" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-pavement" data-bg-edit-type="closed" data-bg-label="Pavement" data-bg-category="exterior" data-bg-layer="40">
+ <path class="pavement" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-asphalt" data-bg-edit-type="closed" data-bg-label="Asphalt" data-bg-category="exterior" data-bg-layer="50">
+ <path class="asphalt" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-mulch" data-bg-edit-type="closed" data-bg-label="Mulch" data-bg-category="exterior" data-bg-layer="60">
+ <path class="mulch" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-rock-beds" data-bg-edit-type="closed" data-bg-label="Rock Bed" data-bg-category="exterior" data-bg-layer="70">
+ <path class="rock-beds" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-stone" data-bg-edit-type="closed" data-bg-label="Stone" data-bg-category="exterior" data-bg-layer="80">
+ <path class="stone" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-brick" data-bg-edit-type="closed" data-bg-label="Brick" data-bg-category="exterior" data-bg-layer="90">
+ <path class="brick" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-gravel" data-bg-edit-type="closed" data-bg-label="Gravel" data-bg-category="exterior" data-bg-layer="100">
+ <path class="gravel" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-wood-decks" data-bg-edit-type="closed" data-bg-label="Deck" data-bg-category="exterior" data-bg-layer="110">
+ <path class="wood-decks" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+ <g id="hi-fencing" data-bg-edit-type="open" data-bg-label="Fence" data-bg-category="exterior" data-bg-layer="230">
+ <path class="fencing" d="M 0,0 L 200,0" />
+ </g>
+ <g id="hi-property-lines" data-bg-edit-type="closed" data-bg-label="Property" data-bg-category="exterior" data-bg-layer="10">
+ <path class="property-lines" d="M 0,0 L 100,0 L 100,100 L 0,100 Z" />
+ </g>
+</defs>
diff --git a/src/hi/apps/location/templates/location/panes/svg_fill_patterns_color.html b/src/hi/apps/location/templates/location/panes/svg_fill_patterns_color.html
index 420620fc..cecb035f 100644
--- a/src/hi/apps/location/templates/location/panes/svg_fill_patterns_color.html
+++ b/src/hi/apps/location/templates/location/panes/svg_fill_patterns_color.html
@@ -56,8 +56,8 @@
<path d="M 0 15 Q 5 10, 10 15 T 20 15" stroke="#87CEEB" stroke-width="1" fill="none" />
</pattern>
<pattern id="brick-pattern" width="20" height="10" patternUnits="userSpaceOnUse">
- <rect width="20" height="10" fill="#B22222" />
- <path d="M 0 5 H 20 M 10 0 V 10" stroke="#8B0000" stroke-width="1" />
+ <rect width="20" height="10" fill="#A0522D" />
+ <path d="M 0 5 H 20 M 10 0 V 10" stroke="#6B3A1F" stroke-width="1" />
</pattern>
<pattern id="tiles-pattern" width="15" height="15" patternUnits="userSpaceOnUse">
<rect x="0" y="0" width="100%" height="100%" fill="#f5f5f5" />
diff --git a/src/hi/apps/location/tests/test_location_manager_draft.py b/src/hi/apps/location/tests/test_location_manager_draft.py
new file mode 100644
index 00000000..b7a5b2f1
--- /dev/null
+++ b/src/hi/apps/location/tests/test_location_manager_draft.py
@@ -0,0 +1,217 @@
+import logging
+import os
+
+from django.core.files.storage import default_storage
+
+from hi.apps.location.location_manager import LocationManager
+from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestLocationManagerDraftSvgHelpers(BaseTestCase):
+ """
+ Tests for LocationManager draft SVG file operations.
+
+ These methods manage a draft copy of a location's SVG file for
+ in-place editing, allowing save/revert/commit workflows.
+ """
+
+ def setUp(self):
+ super().setUp()
+ self.manager = LocationManager()
+ self.location = LocationSyntheticData.create_test_location(
+ svg_fragment_filename='location/svg/my-location-12345.svg',
+ svg_view_box_str='0 0 800 600',
+ )
+ self.live_svg_content = '<rect width="800" height="600" fill="white"/>'
+
+ def _write_live_svg(self, temp_media, content=None):
+ """Helper to write the live SVG file into the isolated media root."""
+ if content is None:
+ content = self.live_svg_content
+ filepath = self.location.svg_fragment_filename
+ full_dir = os.path.dirname(os.path.join(temp_media, filepath))
+ os.makedirs(full_dir, exist_ok=True)
+ with default_storage.open(filepath, 'w') as f:
+ f.write(content)
+
+ def test_get_draft_svg_filename_inserts_draft_before_extension(self):
+ """Draft filename should insert '.draft' before the '.svg' extension."""
+ result = self.manager.get_draft_svg_filename(self.location)
+ self.assertEqual(result, 'location/svg/my-location-12345.draft.svg')
+
+ def test_get_draft_svg_filename_handles_no_extension(self):
+ """Draft filename derivation should work even without an extension."""
+ self.location.svg_fragment_filename = 'location/svg/noext'
+ result = self.manager.get_draft_svg_filename(self.location)
+ self.assertEqual(result, 'location/svg/noext.draft')
+
+ def test_draft_svg_exists_returns_false_when_no_draft(self):
+ """draft_svg_exists returns False when no draft file has been created."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ self.assertFalse(self.manager.draft_svg_exists(self.location))
+
+ def test_draft_svg_exists_returns_true_after_create(self):
+ """draft_svg_exists returns True after create_draft_svg is called."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ self.manager.create_draft_svg(self.location)
+ self.assertTrue(self.manager.draft_svg_exists(self.location))
+
+ def test_create_draft_svg_copies_live_content(self):
+ """create_draft_svg should copy the live SVG content to the draft file."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ draft_filename = self.manager.create_draft_svg(self.location)
+
+ with default_storage.open(draft_filename, 'r') as f:
+ draft_content = f.read()
+ self.assertEqual(draft_content, self.live_svg_content)
+
+ def test_create_draft_svg_returns_draft_filename(self):
+ """create_draft_svg should return the draft filename path."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ draft_filename = self.manager.create_draft_svg(self.location)
+ expected = self.manager.get_draft_svg_filename(self.location)
+ self.assertEqual(draft_filename, expected)
+
+ def test_draft_has_changes_returns_false_when_no_draft(self):
+ """draft_has_changes returns False when no draft file exists."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ self.assertFalse(self.manager.draft_has_changes(self.location))
+
+ def test_draft_has_changes_returns_false_when_identical(self):
+ """draft_has_changes returns False when draft matches live content."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ self.manager.create_draft_svg(self.location)
+ self.assertFalse(self.manager.draft_has_changes(self.location))
+
+ def test_draft_has_changes_returns_true_when_different(self):
+ """draft_has_changes returns True when draft content differs from live."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ self.manager.create_draft_svg(self.location)
+ self.manager.save_draft_svg(self.location, '<circle r="50"/>')
+ self.assertTrue(self.manager.draft_has_changes(self.location))
+
+ def test_save_draft_svg_writes_content(self):
+ """save_draft_svg writes the given content to the draft file."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ new_content = '<circle cx="100" cy="100" r="50"/>'
+ self.manager.save_draft_svg(self.location, new_content)
+
+ draft_filename = self.manager.get_draft_svg_filename(self.location)
+ with default_storage.open(draft_filename, 'r') as f:
+ saved_content = f.read()
+ self.assertEqual(saved_content, new_content)
+
+ def test_save_draft_svg_overwrites_existing_draft(self):
+ """save_draft_svg overwrites previous draft content."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ self.manager.save_draft_svg(self.location, 'first version')
+ self.manager.save_draft_svg(self.location, 'second version')
+
+ draft_filename = self.manager.get_draft_svg_filename(self.location)
+ with default_storage.open(draft_filename, 'r') as f:
+ saved_content = f.read()
+ self.assertEqual(saved_content, 'second version')
+
+ def test_delete_draft_svg_removes_file(self):
+ """delete_draft_svg removes the draft file."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ self.manager.create_draft_svg(self.location)
+ self.assertTrue(self.manager.draft_svg_exists(self.location))
+
+ self.manager.delete_draft_svg(self.location)
+ self.assertFalse(self.manager.draft_svg_exists(self.location))
+
+ def test_delete_draft_svg_is_safe_when_no_draft(self):
+ """delete_draft_svg should not raise when no draft file exists."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ # Should not raise
+ self.manager.delete_draft_svg(self.location)
+
+ def test_commit_draft_svg_copies_draft_to_live(self):
+ """commit_draft_svg should overwrite live file with draft content."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ self.manager.create_draft_svg(self.location)
+
+ edited_content = '<ellipse cx="400" cy="300" rx="200" ry="100"/>'
+ self.manager.save_draft_svg(self.location, edited_content)
+ self.manager.commit_draft_svg(self.location)
+
+ with default_storage.open(self.location.svg_fragment_filename, 'r') as f:
+ live_content = f.read()
+ self.assertEqual(live_content, edited_content)
+
+ def test_commit_draft_svg_removes_draft_file(self):
+ """commit_draft_svg should delete the draft file after copying."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ self.manager.create_draft_svg(self.location)
+ self.manager.commit_draft_svg(self.location)
+ self.assertFalse(self.manager.draft_svg_exists(self.location))
+
+ def test_commit_draft_svg_leaves_live_unchanged_if_draft_matches(self):
+ """commit_draft_svg with unmodified draft preserves original live content."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+ self.manager.create_draft_svg(self.location)
+ self.manager.commit_draft_svg(self.location)
+
+ with default_storage.open(self.location.svg_fragment_filename, 'r') as f:
+ live_content = f.read()
+ self.assertEqual(live_content, self.live_svg_content)
+
+ def test_full_edit_workflow(self):
+ """End-to-end: create draft, edit, save, commit, verify live updated."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+
+ # Step 1: Create draft
+ self.manager.create_draft_svg(self.location)
+ self.assertTrue(self.manager.draft_svg_exists(self.location))
+ self.assertFalse(self.manager.draft_has_changes(self.location))
+
+ # Step 2: Edit draft
+ edited = '<g><text>Edited</text></g>'
+ self.manager.save_draft_svg(self.location, edited)
+ self.assertTrue(self.manager.draft_has_changes(self.location))
+
+ # Step 3: Commit
+ self.manager.commit_draft_svg(self.location)
+ self.assertFalse(self.manager.draft_svg_exists(self.location))
+
+ # Step 4: Verify live content updated
+ with default_storage.open(self.location.svg_fragment_filename, 'r') as f:
+ live_content = f.read()
+ self.assertEqual(live_content, edited)
+
+ def test_cancel_workflow_discards_changes(self):
+ """End-to-end: create draft, edit, delete draft, verify live unchanged."""
+ with self.isolated_media_root() as temp_media:
+ self._write_live_svg(temp_media)
+
+ self.manager.create_draft_svg(self.location)
+ self.manager.save_draft_svg(self.location, '<g>CHANGED</g>')
+ self.assertTrue(self.manager.draft_has_changes(self.location))
+
+ # Cancel: delete draft
+ self.manager.delete_draft_svg(self.location)
+ self.assertFalse(self.manager.draft_svg_exists(self.location))
+
+ # Live content should be unchanged
+ with default_storage.open(self.location.svg_fragment_filename, 'r') as f:
+ live_content = f.read()
+ self.assertEqual(live_content, self.live_svg_content)
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index ca2596c8..9fcfd7be 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -48,7 +48,10 @@ class LocationViewDefaultView( View ):
)
except LocationView.DoesNotExist:
redirect_url = reverse( 'start' )
-
+
+ query_string = request.META.get( 'QUERY_STRING', '' )
+ if query_string:
+ redirect_url = redirect_url + '?' + query_string
return HttpResponseRedirect( redirect_url )
diff --git a/src/hi/apps/profiles/assets/profiles/apartment.json b/src/hi/apps/profiles/assets/profiles/apartment.json
index 72691f5e..b8ba014b 100644
--- a/src/hi/apps/profiles/assets/profiles/apartment.json
+++ b/src/hi/apps/profiles/assets/profiles/apartment.json
@@ -4,14 +4,12 @@
"locations": [
{
"name": "My Home",
- "svg_fragment_filename": "location/svg/apartment-0.svg",
- "svg_view_box_str": "0.0 0.0 2000.0 2000.0",
"order_id": 0,
"views": [
{
"name": "All",
"location_view_type_str": "default",
- "svg_view_box_str": "113.22166091814749 449.0580103532524 1775.3292954434396 1342.0739711557344",
+ "svg_view_box_str": "0 0 2000 2000",
"svg_style_name_str": "color",
"svg_rotate": 0.0,
"order_id": 2
@@ -24,7 +22,8 @@
"svg_rotate": 0.0,
"order_id": 4
}
- ]
+ ],
+ "svg_template_name": "profiles/svg/backgrounds/apartment-0.svg"
}
],
"collections": [
@@ -42,7 +41,7 @@
"paths": [
{
"location_name": "My Home",
- "svg_path": " M 1226.2400978455232,643.139246764765 L 1383.0349608404613,642.1058605342962 L 1381.3716307623363,734.2256108201307 L 1225.131394232242,734.7047367966932 Z"
+ "svg_path": " M 1535.784470404117,1516.7419078975774 L 1651.3066893560863,1513.4157360225774 L 1651.9360838873363,1619.2929936326307 L 1534.6757667908357,1619.7719365037244 Z"
}
],
"visible_in_views": [
@@ -62,7 +61,7 @@
"paths": [
{
"location_name": "My Home",
- "svg_path": "M 823.3533790955232,985.8875988155462 L 1178.4192381842113,985.8875988155462 L 1178.4192381842113,1254.3023930466932 L 823.3533790955232,1254.3023930466932 Z"
+ "svg_path": " M 279.93116840216385,1758.6019542842962 L 715.249255274055,1758.6018322139837 L 717.542224024055,1841.2900639451307 L 279.931198919742,1836.7042485154432 Z"
}
],
"visible_in_views": [
@@ -78,8 +77,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 278.080048,
- "svg_y": 961.716675,
+ "svg_x": 344.568634,
+ "svg_y": 1080.940186,
"svg_scale": 1.673368
}
],
@@ -87,6 +86,21 @@
"All"
]
},
+ {
+ "name": "Bathroom Sink",
+ "entity_type_str": "sink",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1288.621338,
+ "svg_y": 205.063538,
+ "svg_scale": 2.327722
+ }
+ ],
+ "visible_in_views": [
+ "All"
+ ]
+ },
{
"name": "Blender",
"entity_type_str": "appliance",
@@ -98,10 +112,10 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1465.060425,
- "svg_y": 1752.144287,
+ "svg_x": 1852.565186,
+ "svg_y": 456.639404,
"svg_scale": 1.330223,
- "svg_rotate": 269.918069
+ "svg_rotate": 359.425448
}
],
"visible_in_views": [
@@ -114,8 +128,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1747.110962,
- "svg_y": 711.662842,
+ "svg_x": 1054.647949,
+ "svg_y": 1754.944092,
"svg_scale": 2.99799
}
],
@@ -123,14 +137,30 @@
"All"
]
},
+ {
+ "name": "Cooktop/Stove",
+ "entity_type_str": "cooktop",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1305.283203,
+ "svg_y": 1761.574463,
+ "svg_scale": 2.418551,
+ "svg_rotate": 179.907031
+ }
+ ],
+ "visible_in_views": [
+ "All"
+ ]
+ },
{
"name": "Dryer",
"entity_type_str": "clothes_dryer",
"positions": [
{
"location_name": "My Home",
- "svg_x": 1766.678955,
- "svg_y": 1381.208496,
+ "svg_x": 1564.899292,
+ "svg_y": 842.380737,
"svg_scale": 2.397479
}
],
@@ -146,6 +176,22 @@
"name": "Gaming System",
"entity_type_str": "other"
},
+ {
+ "name": "Kitchen Sink",
+ "entity_type_str": "sink",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1000.171997,
+ "svg_y": 1522.862305,
+ "svg_scale": 2.48603,
+ "svg_rotate": 270.224076
+ }
+ ],
+ "visible_in_views": [
+ "All"
+ ]
+ },
{
"name": "Laptop",
"entity_type_str": "computer"
@@ -156,8 +202,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1582.65979,
- "svg_y": 703.361755,
+ "svg_x": 1543.670532,
+ "svg_y": 1765.032959,
"svg_scale": 2.208718
}
],
@@ -175,8 +221,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1759.571411,
- "svg_y": 913.085083,
+ "svg_x": 1592.185059,
+ "svg_y": 1387.713745,
"svg_scale": 3.580818
}
],
@@ -188,14 +234,29 @@
"name": "Rice Cooker",
"entity_type_str": "appliance"
},
+ {
+ "name": "Shower",
+ "entity_type_str": "shower",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1567.708008,
+ "svg_y": 299.34079,
+ "svg_scale": 2.378895
+ }
+ ],
+ "visible_in_views": [
+ "All"
+ ]
+ },
{
"name": "Television",
"entity_type_str": "television",
"positions": [
{
"location_name": "My Home",
- "svg_x": 284.881439,
- "svg_y": 820.065247,
+ "svg_x": 530.237915,
+ "svg_y": 1097.506348,
"svg_scale": 3.494066
}
],
@@ -203,14 +264,29 @@
"All"
]
},
+ {
+ "name": "Toilet",
+ "entity_type_str": "toilet",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 999.789795,
+ "svg_y": 246.871094,
+ "svg_scale": 2.733936
+ }
+ ],
+ "visible_in_views": [
+ "All"
+ ]
+ },
{
"name": "Washer",
"entity_type_str": "clothes_washer",
"positions": [
{
"location_name": "My Home",
- "svg_x": 1771.391724,
- "svg_y": 1208.834717,
+ "svg_x": 1560.447021,
+ "svg_y": 608.101624,
"svg_scale": 2.375069
}
],
@@ -239,8 +315,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 788.435913,
- "svg_y": 705.137451,
+ "svg_x": 815.954895,
+ "svg_y": 1773.63147,
"svg_scale": 1.95791
}
],
diff --git a/src/hi/apps/profiles/assets/profiles/single_story.json b/src/hi/apps/profiles/assets/profiles/single_story.json
index 9ae15272..a0da6d0e 100644
--- a/src/hi/apps/profiles/assets/profiles/single_story.json
+++ b/src/hi/apps/profiles/assets/profiles/single_story.json
@@ -4,22 +4,20 @@
"locations": [
{
"name": "My Home",
- "svg_fragment_filename": "location/svg/single_story-0.svg",
- "svg_view_box_str": "0.0 0.0 2415.0 2990.0",
"order_id": 0,
"views": [
{
"name": "Interior",
"location_view_type_str": "default",
- "svg_view_box_str": "246.52162151229965 952.1133788186053 1457.8421547636262 1102.0671010068318",
+ "svg_view_box_str": "72.22613905368665 61.245055889939636 1782.0000000000002 1877.5098882201207",
"svg_style_name_str": "color",
- "svg_rotate": 2.404911,
+ "svg_rotate": 0.0,
"order_id": 2
},
{
"name": "Exterior",
"location_view_type_str": "default",
- "svg_view_box_str": "0 318.06855973518157 2415 2569.8468517796878",
+ "svg_view_box_str": "0 0 2000 2000",
"svg_style_name_str": "color",
"svg_rotate": 0.0,
"order_id": 4
@@ -27,28 +25,28 @@
{
"name": "Kitchen",
"location_view_type_str": "default",
- "svg_view_box_str": "1306.600124210383 1123.4106735238893 380.2709457832736 287.4687753040373",
+ "svg_view_box_str": "581.293171643817 482.8920762002401 591.1623754328793 622.8469166211707",
"svg_style_name_str": "color",
- "svg_rotate": 2.621785,
+ "svg_rotate": 0.0,
"order_id": 6
}
- ]
+ ],
+ "svg_template_name": "profiles/svg/backgrounds/single_story-0.svg"
},
{
"name": "Attic",
- "svg_fragment_filename": "location/svg/single_story-1.svg",
- "svg_view_box_str": "0.0 0.0 1839.0 1281.0",
"order_id": 1,
"views": [
{
"name": "All",
"location_view_type_str": "default",
- "svg_view_box_str": "0.0 0.0 1839.0 1281.0",
+ "svg_view_box_str": "0 0 2000 2000",
"svg_style_name_str": "color",
"svg_rotate": 0.0,
"order_id": 0
}
- ]
+ ],
+ "svg_template_name": "profiles/svg/backgrounds/single_story-1.svg"
}
],
"collections": [
@@ -94,9 +92,56 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1103.769897,
- "svg_y": 1247.570923,
- "svg_rotate": 356.876492
+ "svg_x": 1292.848755,
+ "svg_y": 1142.696655,
+ "svg_rotate": 359.903916
+ }
+ ],
+ "visible_in_views": [
+ "Interior"
+ ]
+ },
+ {
+ "name": "Attic Fan",
+ "entity_type_str": "exhaust_fan",
+ "positions": [
+ {
+ "location_name": "Attic",
+ "svg_x": 1599.961792,
+ "svg_y": 639.228027,
+ "svg_scale": 2.383946
+ }
+ ],
+ "visible_in_views": [
+ "All"
+ ]
+ },
+ {
+ "name": "Bath Sink",
+ "entity_type_str": "sink",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1177.604248,
+ "svg_y": 776.905273,
+ "svg_scale": 1.553662,
+ "svg_rotate": 269.788067
+ }
+ ],
+ "visible_in_views": [
+ "Interior"
+ ]
+ },
+ {
+ "name": "Bath Toilet",
+ "entity_type_str": "toilet",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1201.610474,
+ "svg_y": 656.969177,
+ "svg_scale": 1.75379,
+ "svg_rotate": 270.114395
}
],
"visible_in_views": [
@@ -114,10 +159,10 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1577.993042,
- "svg_y": 1706.071655,
+ "svg_x": 471.975281,
+ "svg_y": 951.369995,
"svg_scale": 1.519867,
- "svg_rotate": 357.513085
+ "svg_rotate": 0.366846
}
],
"visible_in_views": [
@@ -132,7 +177,7 @@
"paths": [
{
"location_name": "My Home",
- "svg_path": " M 2179.982431137094,196.57792663574173 L 1657.2027116470472,1139.6352539062495"
+ "svg_path": " M 89.99554606629317,143.90995788574173 L 290.6220536880628,511.37503051757767"
}
],
"visible_in_views": [
@@ -145,9 +190,9 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1493.880981,
- "svg_y": 1879.286499,
- "svg_rotate": 267.210213
+ "svg_x": 1001.733093,
+ "svg_y": 1901.645508,
+ "svg_rotate": 268.804079
}
],
"visible_in_views": [
@@ -160,9 +205,9 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1619.84021,
- "svg_y": 1196.970825,
- "svg_rotate": 357.022144
+ "svg_x": 1080.161011,
+ "svg_y": 701.786194,
+ "svg_rotate": 0.085934
}
],
"visible_in_views": [
@@ -175,10 +220,10 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1579.261597,
- "svg_y": 1170.589233,
- "svg_scale": 0.816165,
- "svg_rotate": 357.118781
+ "svg_x": 1083.258545,
+ "svg_y": 794.523315,
+ "svg_scale": 1.616418,
+ "svg_rotate": 0.124105
}
],
"visible_in_views": [
@@ -192,9 +237,9 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1457.395508,
- "svg_y": 1630.974976,
- "svg_rotate": 357.39619
+ "svg_x": 470.643372,
+ "svg_y": 736.153259,
+ "svg_rotate": 359.445004
}
],
"visible_in_views": [
@@ -207,8 +252,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1680.064087,
- "svg_y": 1206.299316,
+ "svg_x": 302.015869,
+ "svg_y": 545.944397,
"svg_scale": 1.226173
}
],
@@ -222,7 +267,7 @@
"paths": [
{
"location_name": "My Home",
- "svg_path": " M 2215.5436493988127,196.55610656738236 L 1690.0055680923597,1183.372436523437"
+ "svg_path": " M 77.15161296082442,176.0466918945308 L 263.80897385407843,511.54675292968705"
}
],
"visible_in_views": [
@@ -235,8 +280,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 317.453674,
- "svg_y": 356.626373,
+ "svg_x": 1718.429321,
+ "svg_y": 260.322906,
"svg_scale": 3.87844
}
],
@@ -254,8 +299,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1477.062256,
- "svg_y": 1171.971313,
+ "svg_x": 880.899353,
+ "svg_y": 643.733276,
"svg_scale": 0.558648
}
],
@@ -269,8 +314,8 @@
"positions": [
{
"location_name": "Attic",
- "svg_x": 372.660858,
- "svg_y": 616.275818,
+ "svg_x": 796.942749,
+ "svg_y": 641.63562,
"svg_scale": 2.455155
}
],
@@ -288,9 +333,10 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1518.010132,
- "svg_y": 1170.174805,
- "svg_rotate": 357.644401
+ "svg_x": 944.805176,
+ "svg_y": 645.489807,
+ "svg_scale": 1.695536,
+ "svg_rotate": 359.754442
}
],
"visible_in_views": [
@@ -307,30 +353,61 @@
"entity_type_str": "leaf_blower"
},
{
- "name": "Microwave",
- "entity_type_str": "microwave_oven",
+ "name": "Master Shower",
+ "entity_type_str": "shower",
"positions": [
{
"location_name": "My Home",
- "svg_x": 1618.635742,
- "svg_y": 1323.021484,
- "svg_rotate": 356.958075
+ "svg_x": 363.080139,
+ "svg_y": 659.092651,
+ "svg_scale": 1.52277
}
],
"visible_in_views": [
- "Kitchen",
"Interior"
]
},
{
- "name": "Oven",
- "entity_type_str": "oven",
+ "name": "Master Sink",
+ "entity_type_str": "sink",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 367.523621,
+ "svg_y": 852.989746,
+ "svg_scale": 1.786925,
+ "svg_rotate": 89.83115
+ }
+ ],
+ "visible_in_views": [
+ "Interior"
+ ]
+ },
+ {
+ "name": "Master Toilet",
+ "entity_type_str": "toilet",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 270.147614,
+ "svg_y": 658.43573,
+ "svg_scale": 1.943179
+ }
+ ],
+ "visible_in_views": [
+ "Interior"
+ ]
+ },
+ {
+ "name": "Microwave",
+ "entity_type_str": "microwave_oven",
"positions": [
{
"location_name": "My Home",
- "svg_x": 1435.592529,
- "svg_y": 1251.123779,
- "svg_rotate": 358.034397
+ "svg_x": 1063.756592,
+ "svg_y": 895.480164,
+ "svg_scale": 1.839248,
+ "svg_rotate": 0.29064
}
],
"visible_in_views": [
@@ -339,16 +416,20 @@
]
},
{
- "name": "Pool",
- "entity_type_str": "area",
- "paths": [
+ "name": "Oven",
+ "entity_type_str": "oven",
+ "positions": [
{
"location_name": "My Home",
- "svg_path": " M 1163.5799560546875,438.1481018066406 L 1203.5973815917969,459.5443878173828 L 1249.109634399414,474.16614532470703 L 1348.2446899414062,461.3225402832031 L 1466.0805358886719,465.0625457763672 L 1606.7405242919922,480.66519927978516 L 1655.4907455444336,498.92953872680664 L 1689.854248046875,522.4253540039062 L 1710.7801513671875,564.2337799072266 L 1726.4747314453125,609.3336868286133 L 1718.62744140625,665.888370513916 L 1697.701416015625,714.5957641601562 L 1664.0170440673828,744.2982025146484 L 1630.172477722168,766.3426895141602 L 1591.0163078308105,774.7492408752441 L 1565.5528469085693,771.7592182159424 L 1524.3948059082031,749.1510314941406 L 1485.6457290649414,740.7874984741211 L 1436.190013885498,741.183277130127 L 1393.1520977020264,745.304780960083 L 1342.2059545516968,761.7521600723267 L 1289.9518280029297,787.3546905517578 L 1263.6274948120117,809.7261428833008 L 1211.2291221618652,813.0646705627441 L 1135.3306560516357,814.079912185669 L 1092.804030418396,800.2009973526001 L 1053.2304453849792,766.4501385688782 L 1019.0569951534271,722.7632467746735 L 992.7308349609375,662.0740356445312 L 994.4515075683594,603.0799713134766 L 1012.9680633544922,550.0411911010742 L 1043.8062362670898,502.5958061218262 L 1082.76713180542,468.41014671325684 L 1126.4432582855225,443.4700574874878 Z"
+ "svg_x": 923.147339,
+ "svg_y": 941.493347,
+ "svg_scale": 1.715605,
+ "svg_rotate": 359.721704
}
],
"visible_in_views": [
- "Exterior"
+ "Kitchen",
+ "Interior"
]
},
{
@@ -357,9 +438,10 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1627.031616,
- "svg_y": 1263.704956,
- "svg_rotate": 357.633046
+ "svg_x": 739.824951,
+ "svg_y": 689.992981,
+ "svg_scale": 2.816287,
+ "svg_rotate": 359.569731
}
],
"visible_in_views": [
@@ -381,10 +463,10 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1091.289551,
- "svg_y": 1163.51123,
+ "svg_x": 1291.500977,
+ "svg_y": 1212.539307,
"svg_scale": 1.761753,
- "svg_rotate": 356.838332
+ "svg_rotate": 0.151648
}
],
"visible_in_views": [
@@ -397,10 +479,10 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1126.773438,
- "svg_y": 1375.73291,
+ "svg_x": 1115.921997,
+ "svg_y": 1028.424683,
"svg_scale": 1.169155,
- "svg_rotate": 356.750437
+ "svg_rotate": 359.464479
}
],
"visible_in_views": [
@@ -413,9 +495,9 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1383.592163,
- "svg_y": 1632.89563,
- "svg_rotate": 356.844129
+ "svg_x": 470.374115,
+ "svg_y": 646.141052,
+ "svg_rotate": 359.480839
}
],
"visible_in_views": [
@@ -428,10 +510,10 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1329.327393,
- "svg_y": 1644.55542,
+ "svg_x": 467.623749,
+ "svg_y": 844.581482,
"svg_scale": 1.363181,
- "svg_rotate": 358.640927
+ "svg_rotate": 359.394081
}
],
"visible_in_views": [
@@ -444,8 +526,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 2206.597656,
- "svg_y": 2803.320313,
+ "svg_x": 1901.77124,
+ "svg_y": 1889.178223,
"svg_scale": 2.019884
}
],
@@ -459,7 +541,7 @@
"paths": [
{
"location_name": "My Home",
- "svg_path": " M 1693.4159028167815,1650.810668945312 L 2212.1012712173597,2785.221557617187"
+ "svg_path": " M 1755.3248383636565,1490.3061523437495 L 1887.7213884048597,1848.4343261718745"
}
],
"visible_in_views": [
@@ -472,9 +554,10 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 863.824646,
- "svg_y": 1087.922974,
- "svg_rotate": 357.718234
+ "svg_x": 738.054443,
+ "svg_y": 1240.392212,
+ "svg_scale": 1.272376,
+ "svg_rotate": 0.14466
}
],
"visible_in_views": [
diff --git a/src/hi/apps/profiles/assets/profiles/two_story.json b/src/hi/apps/profiles/assets/profiles/two_story.json
index b6d9c8f7..3105fb23 100644
--- a/src/hi/apps/profiles/assets/profiles/two_story.json
+++ b/src/hi/apps/profiles/assets/profiles/two_story.json
@@ -4,14 +4,12 @@
"locations": [
{
"name": "My Home",
- "svg_fragment_filename": "location/svg/two_story-0.svg",
- "svg_view_box_str": "0.0 0.0 2000.0 2000.0",
"order_id": 0,
"views": [
{
"name": "Interior",
"location_view_type_str": "default",
- "svg_view_box_str": "113.22166091814749 449.0580103532524 1775.3292954434396 1342.0739711557344",
+ "svg_view_box_str": "0 0 2000 2000",
"svg_style_name_str": "color",
"svg_rotate": 0.0,
"order_id": 2
@@ -27,28 +25,28 @@
{
"name": "Kitchen",
"location_view_type_str": "default",
- "svg_view_box_str": "1253.1958944380513 575.77935670453 613.6162989227576 463.8680075717739",
+ "svg_view_box_str": "1103.142981709687 874.7585050264764 767.0925682200003 808.2064433295275",
"svg_style_name_str": "color",
"svg_rotate": 0.0,
"order_id": 6
}
- ]
+ ],
+ "svg_template_name": "profiles/svg/backgrounds/two_story-0.svg"
},
{
"name": "Upstairs",
- "svg_fragment_filename": "location/svg/two_story-1.svg",
- "svg_view_box_str": "0.0 0.0 2000.0 2000.0",
"order_id": 1,
"views": [
{
"name": "All",
"location_view_type_str": "default",
- "svg_view_box_str": "112.75172814987144 445.5835709547622 1779.080561403294 1344.9097697968793",
+ "svg_view_box_str": "152.88967718626765 97.09804892210309 1743.6768582313691 1837.132740286189",
"svg_style_name_str": "color",
"svg_rotate": 0.0,
"order_id": 0
}
- ]
+ ],
+ "svg_template_name": "profiles/svg/backgrounds/two_story-1.svg"
}
],
"collections": [
@@ -78,7 +76,7 @@
"paths": [
{
"location_name": "My Home",
- "svg_path": " M 1663.9242553710938,170.9359586858052 L 1837.4561767578125,171.6185758733052 L 1836.6661376953125,330.02465322131366 L 1663.0172729492188,330.59032704943866 Z"
+ "svg_path": " M 840.1774291992188,229.75241071217238 L 1131.2366943359375,229.741088690688 L 1130.4466552734375,293.3379161607668 L 839.8587646484375,291.7162120592043 Z"
}
],
"visible_in_views": [
@@ -94,9 +92,9 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 243.805206,
- "svg_y": 953.147949,
- "svg_scale": 1.673368
+ "svg_x": 361.612671,
+ "svg_y": 979.249084,
+ "svg_scale": 2.058968
}
],
"visible_in_views": [
@@ -106,7 +104,15 @@
{
"name": "Blender",
"entity_type_str": "appliance",
- "comment": "Entities that are part of collections"
+ "comment": "Entities that are part of collections",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1486.689266,
+ "svg_y": 1278.861727,
+ "svg_scale": 1.198582
+ }
+ ]
},
{
"name": "Breaker Panel",
@@ -114,14 +120,15 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1777.938843,
- "svg_y": 1515.282715,
+ "svg_x": 1217.228394,
+ "svg_y": 999.646423,
"svg_scale": 1.519867
}
],
"visible_in_views": [
"Exterior",
- "Interior"
+ "Interior",
+ "Kitchen"
]
},
{
@@ -130,8 +137,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1568.953735,
- "svg_y": 1769.295898,
+ "svg_x": 541.721619,
+ "svg_y": 1916.045288,
"svg_scale": 1.330223,
"svg_rotate": 269.918069
}
@@ -146,8 +153,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1651.280273,
- "svg_y": 665.384888,
+ "svg_x": 1629.95752,
+ "svg_y": 1486.761597,
"svg_scale": 1.526897
}
],
@@ -161,9 +168,9 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1345.305786,
- "svg_y": 677.450439,
- "svg_scale": 1.292838
+ "svg_x": 1663.131714,
+ "svg_y": 1162.663574,
+ "svg_scale": 1.695319
}
],
"visible_in_views": [
@@ -177,13 +184,14 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1777.978882,
- "svg_y": 1361.411255,
+ "svg_x": 1262.080811,
+ "svg_y": 1324.753906,
"svg_scale": 1.712929
}
],
"visible_in_views": [
- "Interior"
+ "Interior",
+ "Kitchen"
]
},
{
@@ -192,8 +200,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 110.966972,
- "svg_y": 1511.568726,
+ "svg_x": 186.624634,
+ "svg_y": 1424.442993,
"svg_scale": 1.226173
}
],
@@ -203,7 +211,15 @@
},
{
"name": "Food Processor",
- "entity_type_str": "appliance"
+ "entity_type_str": "appliance",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1547.370605,
+ "svg_y": 1489.048096,
+ "svg_scale": 1.198582
+ }
+ ]
},
{
"name": "HVAC",
@@ -217,8 +233,8 @@
},
{
"location_name": "My Home",
- "svg_x": 151.212189,
- "svg_y": 803.715515,
+ "svg_x": 1249.603516,
+ "svg_y": 237.49353,
"svg_scale": 2.182897
}
],
@@ -236,9 +252,9 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1450.717773,
- "svg_y": 669.122009,
- "svg_scale": 1.353239
+ "svg_x": 1551.332764,
+ "svg_y": 1142.849121,
+ "svg_scale": 1.774636
}
],
"visible_in_views": [
@@ -260,23 +276,70 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 238.043137,
- "svg_y": 242.832367,
- "svg_scale": 4.283128
+ "svg_x": 159.893005,
+ "svg_y": 171.552963,
+ "svg_scale": 3.417176
}
],
"visible_in_views": [
"Exterior"
]
},
+ {
+ "name": "Main Bath Shower",
+ "entity_type_str": "shower",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1655.259277,
+ "svg_y": 783.701172,
+ "svg_scale": 2.248753
+ }
+ ],
+ "visible_in_views": [
+ "Interior"
+ ]
+ },
+ {
+ "name": "Main Bath Sink",
+ "entity_type_str": "sink",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1477.710938,
+ "svg_y": 1024.190308,
+ "svg_scale": 2.075106,
+ "svg_rotate": 179.450907
+ }
+ ],
+ "visible_in_views": [
+ "Interior"
+ ]
+ },
+ {
+ "name": "Main Bath Toilet",
+ "entity_type_str": "toilet",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1708.455078,
+ "svg_y": 995.356873,
+ "svg_scale": 2.549861,
+ "svg_rotate": 180.518676
+ }
+ ],
+ "visible_in_views": [
+ "Interior"
+ ]
+ },
{
"name": "Microwave",
"entity_type_str": "microwave_oven",
"positions": [
{
"location_name": "My Home",
- "svg_x": 1761.850586,
- "svg_y": 671.72168,
+ "svg_x": 1745.810791,
+ "svg_y": 1488.009888,
"svg_scale": 1.326768
}
],
@@ -291,9 +354,9 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1560.365479,
- "svg_y": 675.229614,
- "svg_scale": 1.286659
+ "svg_x": 1431.642334,
+ "svg_y": 1161.077637,
+ "svg_scale": 1.849968
}
],
"visible_in_views": [
@@ -307,9 +370,9 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1794.635742,
- "svg_y": 777.043701,
- "svg_scale": 1.471845
+ "svg_x": 1769.103027,
+ "svg_y": 1188.592773,
+ "svg_scale": 2.796118
}
],
"visible_in_views": [
@@ -319,7 +382,15 @@
},
{
"name": "Rice Cooker",
- "entity_type_str": "appliance"
+ "entity_type_str": "appliance",
+ "positions": [
+ {
+ "location_name": "My Home",
+ "svg_x": 1490.207031,
+ "svg_y": 1484.650879,
+ "svg_scale": 1.198582
+ }
+ ]
},
{
"name": "String Trimmer",
@@ -331,9 +402,9 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 244.450958,
- "svg_y": 830.973022,
- "svg_scale": 1.761753
+ "svg_x": 531.097717,
+ "svg_y": 988.650085,
+ "svg_scale": 2.407921
}
],
"visible_in_views": [
@@ -346,8 +417,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 354.805695,
- "svg_y": 1561.562134,
+ "svg_x": 1214.65564,
+ "svg_y": 875.972107,
"svg_scale": 1.680121
}
],
@@ -355,14 +426,61 @@
"Interior"
]
},
+ {
+ "name": "Upstairs Shower",
+ "entity_type_str": "shower",
+ "positions": [
+ {
+ "location_name": "Upstairs",
+ "svg_x": 940.667786,
+ "svg_y": 403.603363,
+ "svg_scale": 1.908946
+ }
+ ],
+ "visible_in_views": [
+ "All"
+ ]
+ },
+ {
+ "name": "Upstairs Sink",
+ "entity_type_str": "sink",
+ "positions": [
+ {
+ "location_name": "Upstairs",
+ "svg_x": 1187.934448,
+ "svg_y": 420.445404,
+ "svg_scale": 2.265066,
+ "svg_rotate": 89.305133
+ }
+ ],
+ "visible_in_views": [
+ "All"
+ ]
+ },
+ {
+ "name": "Upstairs Toilet",
+ "entity_type_str": "toilet",
+ "positions": [
+ {
+ "location_name": "Upstairs",
+ "svg_x": 1185.335693,
+ "svg_y": 621.433838,
+ "svg_scale": 2.086857,
+ "svg_rotate": 89.717122
+ }
+ ],
+ "visible_in_views": [
+ "All"
+ ]
+ },
{
"name": "Washer",
"entity_type_str": "clothes_washer",
"positions": [
{
"location_name": "My Home",
- "svg_x": 1779.282104,
- "svg_y": 1226.346924,
+ "svg_x": 1263.380249,
+ "svg_y": 1198.834473,
"svg_scale": 1.683932
}
],
@@ -376,13 +494,14 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 1664.889771,
- "svg_y": 1513.095215,
+ "svg_x": 1316.365601,
+ "svg_y": 992.605286,
"svg_scale": 1.773727
}
],
"visible_in_views": [
- "Interior"
+ "Interior",
+ "Kitchen"
]
},
{
@@ -406,8 +525,8 @@
"positions": [
{
"location_name": "My Home",
- "svg_x": 246.357956,
- "svg_y": 700.745972,
+ "svg_x": 684.302979,
+ "svg_y": 973.593201,
"svg_scale": 1.351972
}
],
diff --git a/src/hi/apps/profiles/constants.py b/src/hi/apps/profiles/constants.py
index bfc80bb8..1aafc44e 100644
--- a/src/hi/apps/profiles/constants.py
+++ b/src/hi/apps/profiles/constants.py
@@ -27,8 +27,7 @@ PROFILE_FIELD_ENTITIES = 'entities'
# Location fields
LOCATION_FIELD_NAME = 'name'
-LOCATION_FIELD_SVG_FRAGMENT_FILENAME = 'svg_fragment_filename'
-LOCATION_FIELD_SVG_VIEW_BOX_STR = 'svg_view_box_str'
+LOCATION_FIELD_SVG_TEMPLATE_NAME = 'svg_template_name'
LOCATION_FIELD_ORDER_ID = 'order_id'
LOCATION_FIELD_VIEWS = 'views'
diff --git a/src/hi/apps/profiles/profile_manager.py b/src/hi/apps/profiles/profile_manager.py
index d27eaa21..4a47d8a2 100644
--- a/src/hi/apps/profiles/profile_manager.py
+++ b/src/hi/apps/profiles/profile_manager.py
@@ -1,14 +1,10 @@
import json
import logging
-import os
-import shutil
from decimal import Decimal
from pathlib import Path
from typing import Dict, List
from dataclasses import dataclass
-from django.conf import settings
-from django.core.files.storage import default_storage, FileSystemStorage
from django.db import transaction
from hi.apps.entity.models import Entity, EntityPosition, EntityPath, EntityView
@@ -145,7 +141,7 @@ class ProfileManager:
self._validate_fundamental_requirements(profile_data)
# Copy SVG fragment files from assets to MEDIA_ROOT before validation
- self._copy_svg_fragment_files(profile_data)
+ self._render_svg_templates(profile_data)
# Initialize tracking
stats = ProfileLoadingStats()
@@ -260,77 +256,54 @@ class ProfileManager:
"""
return Path(__file__).parent / 'assets'
- def _copy_svg_fragment_files(self, profile_data: dict) -> None:
+ def _render_svg_templates(self, profile_data: dict) -> None:
"""
- Copy predefined SVG fragment files from profile assets to MEDIA_ROOT.
-
- This must be called before location creation/validation to ensure
- referenced SVG files exist in MEDIA_ROOT.
-
+ Render SVG background templates and write processed output to MEDIA_ROOT.
+
+ Each location in the profile data references an SVG template by name.
+ This renders the template, processes the SVG (strip wrapper, extract
+ viewBox, scan for dangerous content), and writes the result to
+ MEDIA_ROOT. The location data is updated in-place with the generated
+ filename and viewBox for subsequent Location creation.
+
Args:
- profile_data: The loaded profile JSON data
-
- Raises:
- FileNotFoundError: If required SVG fragment files are missing from assets
- Exception: For other file system errors during copying
+ profile_data: The loaded profile JSON data (modified in-place)
"""
+ from hi.apps.location.location_manager import LocationManager
+
locations_data = profile_data.get(PC.PROFILE_FIELD_LOCATIONS, [])
- assets_base_dir = self._get_assets_base_directory()
-
+ location_manager = LocationManager()
+
for location_data in locations_data:
- svg_fragment_filename = location_data.get(PC.LOCATION_FIELD_SVG_FRAGMENT_FILENAME)
- if not svg_fragment_filename:
+ svg_template_name = location_data.get(PC.LOCATION_FIELD_SVG_TEMPLATE_NAME)
+ if not svg_template_name:
continue
-
- # Source: profile assets directory
- source_path = assets_base_dir / svg_fragment_filename
-
- # Destination: MEDIA_ROOT
- destination_path = os.path.join(settings.MEDIA_ROOT, svg_fragment_filename)
-
+
try:
- if not source_path.exists():
- raise FileNotFoundError(f'SVG fragment file not found in assets: {source_path}')
-
- # Ensure destination directory exists
- self._ensure_directory_exists(svg_fragment_filename)
-
- # Copy the file
- shutil.copy2(str(source_path), destination_path)
- logger.debug(f'Copied SVG fragment: {source_path} -> {destination_path}')
-
+ result = location_manager.render_svg_template_to_media(
+ svg_template_name = svg_template_name,
+ )
+ location_data['_svg_fragment_filename'] = result['svg_fragment_filename']
+ location_data['_svg_view_box_str'] = str(result['svg_viewbox'])
+ logger.debug(f'Rendered SVG template: {svg_template_name} -> {result["svg_fragment_filename"]}')
+
except Exception as e:
- logger.error(f'Failed to copy SVG fragment {svg_fragment_filename}: {e}')
+ logger.error(f'Failed to render SVG template {svg_template_name}: {e}')
raise
-
- logger.debug('SVG fragment files copied successfully')
-
- def _ensure_directory_exists(self, filepath: str) -> None:
- """
- Ensure the directory for the given filepath exists in MEDIA_ROOT.
-
- This follows the same pattern as LocationManager._ensure_directory_exists
- """
- if isinstance(default_storage, FileSystemStorage):
- directory = os.path.dirname(default_storage.path(filepath))
- if not os.path.exists(directory):
- os.makedirs(directory, exist_ok=True)
+ logger.debug('SVG templates rendered successfully')
+
def _create_locations(self, location_data_list: List[dict]) -> List[Location]:
locations = []
for location_data in location_data_list:
- svg_fragment_filename = location_data[PC.LOCATION_FIELD_SVG_FRAGMENT_FILENAME]
-
- # Validate SVG file exists in MEDIA_ROOT (same as include_media_template)
- full_filesystem_path = os.path.join(settings.MEDIA_ROOT, svg_fragment_filename)
- if not os.path.exists(full_filesystem_path):
- raise ValueError(f'SVG file not found: {full_filesystem_path}')
-
+ svg_fragment_filename = location_data['_svg_fragment_filename']
+ svg_view_box_str = location_data['_svg_view_box_str']
+
location = Location.objects.create(
name = location_data[PC.LOCATION_FIELD_NAME],
svg_fragment_filename = svg_fragment_filename,
- svg_view_box_str = location_data[PC.LOCATION_FIELD_SVG_VIEW_BOX_STR],
+ svg_view_box_str = svg_view_box_str,
order_id = location_data.get(PC.LOCATION_FIELD_ORDER_ID, 0),
)
locations.append(location)
@@ -640,17 +613,13 @@ class ProfileManager:
for location_data in location_data_list:
stats.locations_attempted += 1
try:
- svg_fragment_filename = location_data[PC.LOCATION_FIELD_SVG_FRAGMENT_FILENAME]
-
- # Validate SVG file exists in MEDIA_ROOT (same as include_media_template)
- full_filesystem_path = os.path.join(settings.MEDIA_ROOT, svg_fragment_filename)
- if not os.path.exists(full_filesystem_path):
- raise ValueError(f'SVG file not found: {full_filesystem_path}')
-
+ svg_fragment_filename = location_data['_svg_fragment_filename']
+ svg_view_box_str = location_data['_svg_view_box_str']
+
location = Location.objects.create(
name = location_data[PC.LOCATION_FIELD_NAME],
svg_fragment_filename = svg_fragment_filename,
- svg_view_box_str = location_data[PC.LOCATION_FIELD_SVG_VIEW_BOX_STR],
+ svg_view_box_str = svg_view_box_str,
order_id = location_data.get(PC.LOCATION_FIELD_ORDER_ID, 0),
)
locations.append(location)
diff --git a/src/hi/apps/profiles/session_helpers.py b/src/hi/apps/profiles/session_helpers.py
index c71306ea..9c47c177 100644
--- a/src/hi/apps/profiles/session_helpers.py
+++ b/src/hi/apps/profiles/session_helpers.py
@@ -39,6 +39,11 @@ def mark_edit_mode_entry(request):
request.session[EDIT_MODE_ENTRY_COUNT_KEY] = count + 1
+def dismiss_view_intro_help(request):
+ """Dismiss view mode help early by removing the session timestamp."""
+ request.session.pop(VIEW_INTRO_HELP_SESSION_KEY, None)
+
+
def should_show_view_intro_help(request):
"""Check if view mode help should be shown based on session timing."""
timestamp = request.session.get(VIEW_INTRO_HELP_SESSION_KEY)
diff --git a/src/hi/apps/profiles/templates/profiles/modals/edit_reference_help.html b/src/hi/apps/profiles/templates/profiles/modals/edit_reference_help.html
index ce1fcd1d..7cf7af25 100644
--- a/src/hi/apps/profiles/templates/profiles/modals/edit_reference_help.html
+++ b/src/hi/apps/profiles/templates/profiles/modals/edit_reference_help.html
@@ -16,124 +16,116 @@ Editing Help
</div>
<div class="editing-help-categories">
- <!-- Moving -->
+ <!-- General -->
<div class="help-category">
<div class="category-header">
<div class="category-icon">
{% icon "move" size="sm" color="primary" %}
</div>
- <h6 class="category-title">Moving</h6>
+ <h6 class="category-title">General</h6>
</div>
<ul class="help-actions">
<li>
<span class="action-method">Click & Drag</span>
- <span class="action-description">Left mouse button</span>
+ <span class="action-description">Pan the view</span>
</li>
<li>
- <span class="action-method">Touch Drag</span>
- <span class="action-description">One finger drag</span>
- </li>
- </ul>
- </div>
-
- <!-- Scaling -->
- <div class="help-category">
- <div class="category-header">
- <div class="category-icon">
- {% icon "zoom" size="sm" color="primary" %}
- </div>
- <h6 class="category-title">Scaling</h6>
- </div>
- <ul class="help-actions">
- <li>
- <span class="action-method">Mouse Wheel</span>
- <span class="action-description">Scroll to zoom</span>
- </li>
- <li>
- <span class="action-method">+ / -</span>
+ <span class="action-method">Mouse Wheel / + / -</span>
<span class="action-description">Zoom in/out</span>
</li>
<li>
- <span class="action-method">S + Drag</span>
+ <span class="action-method">S + Drag/Wheel</span>
<span class="action-description">Scale mode</span>
</li>
<li>
- <span class="action-method">Pinch</span>
- <span class="action-description">Two finger gesture</span>
+ <span class="action-method">R + Drag/Wheel</span>
+ <span class="action-description">Rotate mode</span>
+ </li>
+ <li>
+ <span class="action-method">SHIFT + Drag</span>
+ <span class="action-description">Fine positioning (bypass snap)</span>
</li>
<li>
- <span class="action-method">ESC</span>
- <span class="action-description">End scale mode</span>
+ <span class="action-method">Snap (footer)</span>
+ <span class="action-description">Set grid size, 0 to disable</span>
</li>
</ul>
</div>
- <!-- Rotating -->
+ <!-- Icon Editing -->
<div class="help-category">
<div class="category-header">
<div class="category-icon">
- {% icon "rotate" size="sm" color="primary" %}
+ {% icon "zoom" size="sm" color="primary" %}
</div>
- <h6 class="category-title">Rotating</h6>
+ <h6 class="category-title">Icon Editing</h6>
</div>
<ul class="help-actions">
<li>
- <span class="action-method">R + Drag</span>
- <span class="action-description">Rotate mode</span>
+ <span class="action-method">Click</span>
+ <span class="action-description">Select entity</span>
</li>
<li>
- <span class="action-method">R + Wheel</span>
- <span class="action-description">Rotate with mouse</span>
+ <span class="action-method">Drag</span>
+ <span class="action-description">Move entity</span>
</li>
<li>
- <span class="action-method">R + +/-</span>
- <span class="action-description">Rotate right/left</span>
+ <span class="action-method">S + Drag/Wheel/+/-</span>
+ <span class="action-description">Scale entity</span>
</li>
<li>
- <span class="action-method">Two Finger</span>
- <span class="action-description">Touch rotate</span>
+ <span class="action-method">R + Drag/Wheel/+/-</span>
+ <span class="action-description">Rotate entity</span>
</li>
<li>
<span class="action-method">ESC</span>
- <span class="action-description">End rotate mode</span>
+ <span class="action-description">Deselect</span>
</li>
</ul>
</div>
<!-- Path Editing -->
- <div class="help-category">
+ <div class="help-category help-category-wide">
<div class="category-header">
<div class="category-icon">
{% icon "path" size="sm" color="primary" %}
</div>
<h6 class="category-title">Path Editing</h6>
</div>
- <ul class="help-actions">
- <li>
- <span class="action-method">Click</span>
- <span class="action-description">Select area</span>
- </li>
- <li>
- <span class="action-method">Drag Points</span>
- <span class="action-description">Change shape</span>
- </li>
- <li>
- <span class="action-method">I/INSERT</span>
- <span class="action-description">Insert path node</span>
- </li>
- <li>
- <span class="action-method">X/DEL</span>
- <span class="action-description">Delete path node</span>
- </li>
- <li>
- <span class="action-method">A/+</span>
- <span class="action-description">Add new segment</span>
- </li>
- <li>
- <span class="action-method">ESC</span>
- <span class="action-description">End path editing</span>
- </li>
- </ul>
+ <div class="help-actions-columns">
+ <ul class="help-actions">
+ <li>
+ <span class="action-method">Click</span>
+ <span class="action-description">Select path to edit vertices</span>
+ </li>
+ <li>
+ <span class="action-method">Drag Point</span>
+ <span class="action-description">Move single vertex</span>
+ </li>
+ <li>
+ <span class="action-method">CTRL + Drag</span>
+ <span class="action-description">Move entire path</span>
+ </li>
+ <li>
+ <span class="action-method">I / INSERT</span>
+ <span class="action-description">Insert vertex</span>
+ </li>
+ </ul>
+ <ul class="help-actions">
+ <li>
+ <span class="action-method">X / DEL</span>
+ <span class="action-description">Delete vertex</span>
+ </li>
+ <li>
+ <span class="action-method">A / +</span>
+ <span class="action-description">Add new segment</span>
+ </li>
+ <li>
+ <span class="action-method">ESC</span>
+ <span class="action-description">Finish path editing</span>
+ </li>
+ </ul>
+ </div>
</div>
</div>
@@ -143,7 +135,7 @@ Editing Help
<h6 class="note-title">Important Note</h6>
</div>
<p class="note-content">
- Background edits are only saved when the "View" editing pane is showing.
+ View pan/zoom/rotate changes are only saved when the "View" editing pane is showing.
</p>
</div>
</div>
diff --git a/src/hi/apps/profiles/templates/profiles/panes/edit_empty_help_sidebar.html b/src/hi/apps/profiles/templates/profiles/panes/edit_empty_help_sidebar.html
index e3a81a7e..93417d94 100644
--- a/src/hi/apps/profiles/templates/profiles/panes/edit_empty_help_sidebar.html
+++ b/src/hi/apps/profiles/templates/profiles/panes/edit_empty_help_sidebar.html
@@ -4,31 +4,43 @@
{% icon "rocket" size="lg" color="primary" %}
<h5>Getting Started</h5>
</div>
-
+
<div class="guide-content">
<div class="mode-explanation">
<span class="badge badge-info">Edit Mode</span>
<p class="small mb-0">You're in editing mode to set up your home layout.</p>
</div>
-
+
<div class="steps">
<div class="step">
<div class="step-number">1</div>
<div class="step-content">
<div><strong>Add Your First Item</strong></div>
- <p class="small mb-0">Click "Add New Item" above to create your first home item.</p>
+ <p class="small mb-0">Click "ADD NEW" button above to create your home's first item.</p>
</div>
</div>
-
+
<div class="step">
<div class="step-number">2</div>
+ <div class="step-content">
+ <div><strong>Customize Background</strong></div>
+ <p class="small mb-0">
+ <a href="{% url 'location_svg_background' location_id=request.view_parameters.location.id %}"
+ data-async="true">
+ Customize the background</a> to match your home.
+ </p>
+ </div>
+ </div>
+
+ <div class="step">
+ <div class="step-number">3</div>
<div class="step-content">
<div><strong>Switch to View Mode</strong></div>
<p class="small mb-0">Click "Exit Edit" above when done to start managing your home's information.</p>
</div>
</div>
</div>
-
+
<a class="plain" href="{% url 'profiles_edit_reference_help' %}" data-async="modal">
<div class="help-hint">
{% icon "question-circle" size="sm" color="muted" %}
diff --git a/src/hi/apps/profiles/templates/profiles/panes/edit_intro_help_header.html b/src/hi/apps/profiles/templates/profiles/panes/edit_intro_help_header.html
index b4eca447..fd21a660 100644
--- a/src/hi/apps/profiles/templates/profiles/panes/edit_intro_help_header.html
+++ b/src/hi/apps/profiles/templates/profiles/panes/edit_intro_help_header.html
@@ -5,9 +5,9 @@
<div class="">
<strong>Welcome to Edit Mode!</strong>
</div>
- <button type="button"
- class="btn btn-sm btn-secondary btn-link p-0"
- data-toggle="collapse"
+ <button type="button"
+ class="btn btn-sm btn-secondary btn-link p-0"
+ data-toggle="collapse"
data-target="#edit-mode-welcome-content"
aria-expanded="false"
aria-controls="edit-mode-welcome-content">
@@ -17,38 +17,51 @@
<div class="collapse getting-started-guide mx-2" id="edit-mode-welcome-content">
<div class="guide-content p-2">
-
+
<div class="steps">
<div class="step">
<div class="step-icon">
- {% icon "move" color="primary" aria_label="Add items" %}
+ {% icon "plus" color="primary" aria_label="Add items" %}
</div>
<div class="step-content">
- <div><strong>Adjust the Layout</strong></div>
- <p class="small mb-0">Drag, rotate and zoom items.</p>
+ <div><strong>Manage Items</strong></div>
+ <p class="small mb-0">Add and remove items from your home.</p>
</div>
</div>
<div class="step">
<div class="step-icon">
- {% icon "plus" color="primary" aria_label="Add items" %}
+ {% icon "move" color="primary" aria_label="Move items" %}
</div>
<div class="step-content">
- <div><strong>Manage Items</strong></div>
- <p class="small mb-0">Add/remove items from your home.</p>
+ <div><strong>Move Items</strong></div>
+ <p class="small mb-0">Drag, rotate and zoom items on the layout.</p>
</div>
</div>
<div class="step">
<div class="step-icon">
- {% icon "eye" color="primary" aria_label="Add items" %}
+ {% icon "layers" color="primary" aria_label="Background editor" %}
+ </div>
+ <div class="step-content">
+ <div><strong>Customize Background</strong></div>
+ <p class="small mb-0">
+ <a href="{% url 'location_svg_background' location_id=request.view_parameters.location.id %}"
+ data-async="true">
+ Customize the background</a> to match your home.
+ </p>
+ </div>
+ </div>
+ <div class="step">
+ <div class="step-icon">
+ {% icon "eye" color="primary" aria_label="Exit edit mode" %}
</div>
<div class="step-content">
<div><strong>Exit to View Mode</strong></div>
- <p class="small mb-0">Exit to resume managing your home's information..</p>
+ <p class="small mb-0">Exit to resume managing your home's information.</p>
</div>
</div>
-
+
</div>
-
+
<a class="plain" href="{% url 'profiles_edit_reference_help' %}" data-async="modal">
<div class="help-hint">
{% icon "question-circle" size="sm" color="muted" %}
diff --git a/src/hi/apps/profiles/templates/profiles/panes/view_intro_help_sidebar.html b/src/hi/apps/profiles/templates/profiles/panes/view_intro_help_sidebar.html
index 15c4b19c..33266118 100644
--- a/src/hi/apps/profiles/templates/profiles/panes/view_intro_help_sidebar.html
+++ b/src/hi/apps/profiles/templates/profiles/panes/view_intro_help_sidebar.html
@@ -54,5 +54,13 @@
<small>Need more help with getting started?</small>
</div>
</a>
+
+ <form action="{% url 'profiles_dismiss_view_intro_help' %}"
+ method="post" class="text-center mt-2" data-async="true">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-sm btn-outline-secondary">
+ {% icon "close" size="sm" css_class="hi-icon-left" %}Dismiss
+ </button>
+ </form>
</div>
</div>
diff --git a/src/hi/apps/profiles/templates/profiles/svg/backgrounds/apartment-0.svg b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/apartment-0.svg
new file mode 100644
index 00000000..4a96ca05
--- /dev/null
+++ b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/apartment-0.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000">
+<g data-hi-editor="1" data-hi-name="My Home">
+<g id="bg-a6d393a1" class="hi-bg-element" data-bg-type="pavement" data-bg-edit-type="closed" data-bg-layer="40" style=""><path class="pavement" d=" M 1686.615832575682,903.1555748631072 L 1904.2436819402863,903.1555748631072 L 1904.2436819402863,1566.9205154251497 L 1686.615832575682,1566.9205154251497 Z"></path></g><g id="bg-f8619cb0" class="hi-bg-element" data-bg-type="interior-floors" data-bg-edit-type="closed" data-bg-layer="130" style=""><path class="interior-floors" d=" M 206.74645689637393,130.5767096187625 L 1675.7344401074517,141.45810208699268 L 1675.7344401074517,1838.9553271309048 L 217.62784936460412,1838.9553271309048 Z"></path></g><g id="bg-4cdff8cb" class="hi-bg-element" data-bg-type="countertops" data-bg-edit-type="closed" data-bg-layer="150" style=""><path class="countertops" d=" M 1131.6648166959415,141.45810208699268 L 1458.1065907428476,141.45810208699268 L 1458.1065907428476,250.27202676929474 L 1131.6648166959415,250.27202676929474 Z"></path></g><g id="bg-2033d146" class="hi-bg-element" data-bg-type="countertops" data-bg-edit-type="closed" data-bg-layer="150" style=""><path class="countertops" d=" M 1077.2578543547904,1327.5298811240853 L 1077.2578543547904,1697.4972250439123 L 1523.3949455522288,1697.4972250439123 L 1523.3949455522288,1458.1065907428476 L 1675.7344401074517,1458.1065907428476 L 1675.7344401074517,1838.9553271309048 L 914.0369673313373,1828.0739346626747 L 914.0369673313373,1327.5298811240853 Z"></path></g><g id="bg-aab87ea9" class="hi-bg-element" data-bg-type="shelves" data-bg-edit-type="closed" data-bg-layer="160" style=""><path class="shelves" d=" M 413.49291379274786,914.0369673313373 L 1099.020639291251,914.0369673313373 L 1099.020639291251,1001.088107077179 L 413.49291379274786,1001.088107077179 Z"></path></g><g id="bg-d3e07a39" class="hi-bg-element" data-bg-type="shelves" data-bg-edit-type="closed" data-bg-layer="160" style=""><path class="shelves" d=" M 1588.6833003616102,478.7812686021291 L 1675.7344401074517,478.7812686021291 L 1675.7344401074517,957.5625372042582 L 1588.6833003616102,957.5625372042582 Z"></path></g><g id="bg-de5285ac" class="hi-bg-element" data-bg-type="cabinets" data-bg-edit-type="closed" data-bg-layer="170" style=""><path class="cabinets" d=" M 1077.2578543547904,1773.6669723215236 L 1610.4460852980706,1773.6669723215236 L 1610.4460852980706,1458.1065907428476 L 1675.7344401074517,1458.1065907428476 L 1675.7344401074517,1838.9553271309048 L 1077.2578543547904,1838.9553271309048 Z"></path></g><g id="bg-ab37684b" class="hi-bg-element" data-bg-type="stairs" data-bg-edit-type="icon" data-bg-layer="200" transform="scale(3.331219907924473 3.331219907924473) translate(506.3057323908339, 472.9875666426297) rotate(0, 0, 0)"><path class="stairs" d="M 0,0 L 60,0 L 60,10 L 0,10 Z M 0,10 L 60,10 L 60,20 L 0,20 Z M 0,20 L 60,20 L 60,30 L 0,30 Z M 0,30 L 60,30 L 60,40 L 0,40 Z M 0,40 L 60,40 L 60,50 L 0,50 Z M 0,50 L 60,50 L 60,60 L 0,60 Z M 0,60 L 60,60 L 60,70 L 0,70 Z M 0,70 L 60,70 L 60,80 L 0,80 Z"></path><rect x="0" y="0" width="60" height="80" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-bc56341a" class="hi-bg-element" data-bg-type="interior-walls" data-bg-edit-type="open" data-bg-layer="210" style=""><path class="interior-wall-stroke" d=" M 217.62784936460412,1001.088107077179 L 1102.276587246477,997.750359145518 L 1102.276587246477,703.1764435882699 M 1244.8123528386939,475.11921864072286 L 892.2741823948769,478.7812686021291 L 892.2741823948769,141.45810208699268 M 1675.7344401074517,478.7812686021291 L 1425.4624133381571,478.7812686021291 M 1463.3671934134265,475.11921864072286 L 1463.3671934134265,959.7408216542602 L 1675.7344401074517,957.5625372042582 M 1111.7789716192915,475.11921864072286 L 1111.7789716192915,522.6311405047952 M 217.62784936460412,794.3416501808051 L 1099.020639291251,794.3416501808051 M 413.49291379274786,794.3416501808051 L 413.49291379274786,1001.088107077179"></path><path d=" M 217.62784936460412,1001.088107077179 L 1102.276587246477,997.750359145518 L 1102.276587246477,703.1764435882699 M 1244.8123528386939,475.11921864072286 L 892.2741823948769,478.7812686021291 L 892.2741823948769,141.45810208699268 M 1675.7344401074517,478.7812686021291 L 1425.4624133381571,478.7812686021291 M 1463.3671934134265,475.11921864072286 L 1463.3671934134265,959.7408216542602 L 1675.7344401074517,957.5625372042582 M 1111.7789716192915,475.11921864072286 L 1111.7789716192915,522.6311405047952 M 217.62784936460412,794.3416501808051 L 1099.020639291251,794.3416501808051 M 413.49291379274786,794.3416501808051 L 413.49291379274786,1001.088107077179" class="hi-bg-hit-area"></path></g><g id="bg-d168de6d" class="hi-bg-element" data-bg-type="exterior-walls" data-bg-edit-type="open" data-bg-layer="220" style=""><path class="exterior-wall-stroke" d=" M 1566.9205154251497,1294.8857037193945 L 1675.7344401074517,1294.8857037193945 L 1675.7344401074517,1838.9553271309048 L 217.62784936460412,1838.9553271309048 L 206.74645689637393,141.45810208699268 L 1675.7344401074517,141.45810208699268 L 1675.7344401074517,1109.9020317594811"></path><path d=" M 1566.9205154251497,1294.8857037193945 L 1675.7344401074517,1294.8857037193945 L 1675.7344401074517,1838.9553271309048 L 217.62784936460412,1838.9553271309048 L 206.74645689637393,141.45810208699268 L 1675.7344401074517,141.45810208699268 L 1675.7344401074517,1109.9020317594811" class="hi-bg-hit-area"></path></g><g id="bg-1b68cc27" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(-1.8607350307897779 1.8607350307897779) translate(-901.4342250866189, 692.3913904386125) rotate(270, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71"></path><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71"></path><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-32ec51d1" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(1.837185174480733 1.837185174480733) translate(777.5265453342602, 260.3013775032597) rotate(185, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71"></path><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71"></path><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-2d80d953" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(1.8237745386431128 1.8237745386431128) translate(612.6761454199889, 285.47013379154447) rotate(95, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71"></path><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71"></path><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-1b341362" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.5958100008597527 1.5958100008597527) translate(137.73828651318732, 282.2952860641858) rotate(90, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z"></path><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-94f1c836" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.7127436541570613 1.7127436541570613) translate(129.60516210695383, 693.7687693032074) rotate(90, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z"></path><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-ca002970" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.8090275362071606 1.8090275362071606) translate(123.91001182977915, 771.1294197058675) rotate(90, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z"></path><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-7cdf16bc" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.5079589016559942 1.5079589016559942) translate(145.7626720824235, 176.06977401022715) rotate(90, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z"></path><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-5f0dbe95" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.7612490915293437 1.7612490915293437) translate(836.2090028021884, 278.3397812410161) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z"></path><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11"></line><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-57c2ac8f" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.828526704143698 1.828526704143698) translate(806.8099824886643, 396.2672961117848) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z"></path><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11"></line><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-92407857" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1 1) translate(415.66918332399786, 840.0435305394082) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z"></path><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11"></line><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-05e09c03" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(2.4320332654174748 2.4320332654174748) translate(181.65225976683868, 323.0368694773011) rotate(0, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z"></path><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11"></line><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area"></rect></g><g id="bg-5416caa5" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(2.4014786333148215 2.4014786333148215) translate(323.52202458737816, 328.05313587566377) rotate(0, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z"></path><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11"></line><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area"></rect></g></g>
+</svg>
diff --git a/src/hi/apps/profiles/templates/profiles/svg/backgrounds/blank.svg b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/blank.svg
new file mode 100644
index 00000000..faedf8d5
--- /dev/null
+++ b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/blank.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000">
+<g data-hi-editor="1" data-hi-name="Blank">
+</g>
+</svg>
diff --git a/src/hi/apps/profiles/templates/profiles/svg/backgrounds/single_story-0.svg b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/single_story-0.svg
new file mode 100644
index 00000000..0eb03c32
--- /dev/null
+++ b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/single_story-0.svg
@@ -0,0 +1,6 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000">
+<g data-hi-editor="1" data-hi-name="My Home">
+<g id="bg-56f1b2e7" class="hi-bg-element" data-bg-type="property-lines" data-bg-edit-type="closed" data-bg-layer="10" style=""><path class="property-lines" d=" M 21.762784936460413,32.64417740469062 L 1969.5320367496674,32.64417740469062 L 1969.5320367496674,1926.0064668767466 L 21.762784936460413,1936.8878593449767 Z" /></g><g id="bg-0f3b7c8d" class="hi-bg-element" data-bg-type="grass" data-bg-edit-type="closed" data-bg-layer="20" style=""><path class="grass" d=" M 32.64417740469062,87.05113974584165 L 1958.6506442814373,87.05113974584165 L 1969.5320367496674,1926.0064668767466 L 21.762784936460413,1936.8878593449767 Z" /></g><g id="bg-e0fafc59" class="hi-bg-element" data-bg-type="pavement" data-bg-edit-type="closed" data-bg-layer="40" style=""><path class="pavement" d=" M 696.4091179667332,1468.9879832110778 L 1468.9879832110778,1468.9879832110778 L 1468.9879832110778,1545.1577304886894 L 696.4091179667332,1545.1577304886894 Z" /></g><g id="bg-0ad769f0" class="hi-bg-element" data-bg-type="pavement" data-bg-edit-type="closed" data-bg-layer="40" style=""><path class="pavement" d=" M 500.5440535385895,511.4254460068197 L 750.8160803078842,511.4254460068197 L 750.8160803078842,587.5951932844312 L 500.5440535385895,587.5951932844312 Z" /></g><g id="bg-b4ea280f" class="hi-bg-element" data-bg-type="pavement" data-bg-edit-type="closed" data-bg-layer="40" style=""><path class="pavement" d=" M 1240.4787413782435,1545.1577304886894 L 1371.0554509970061,1545.1577304886894 L 1371.0554509970061,1926.0064668767466 L 1240.4787413782435,1926.0064668767466 Z" /></g><g id="bg-599f6384" class="hi-bg-element" data-bg-type="wood-decks" data-bg-edit-type="closed" data-bg-layer="110" style=""><path class="wood-decks" d=" M 750.8160803078842,391.7301288562874 L 1305.7670961876247,391.7301288562874 L 1305.7670961876247,576.713800816201 L 750.8160803078842,576.713800816201 Z" /></g><g id="bg-3d78cc4b" class="hi-bg-element" data-bg-type="interior-floors" data-bg-edit-type="closed" data-bg-layer="130" style=""><path class="interior-floors" d=" M 206.74645689637393,587.5951932844312 L 1762.7855798532935,587.5951932844312 L 1762.7855798532935,1468.9879832110778 L 206.74645689637393,1468.9879832110778 Z" /></g><g id="bg-8e872ed4" class="hi-bg-element" data-bg-type="countertops" data-bg-edit-type="closed" data-bg-layer="150" style=""><path class="countertops" d=" M 321.2676702071408,749.6245638166617 L 414.07833048920367,749.6245638166617 L 413.49291379274786,957.5625372042582 L 321.2676702071408,956.6637290612636 Z" /></g><g id="bg-34e7abfb" class="hi-bg-element" data-bg-type="countertops" data-bg-edit-type="closed" data-bg-layer="150" style=""><path class="countertops" d=" M 1135.1457680652306,721.067437576027 L 1213.677865226976,721.067437576027 L 1213.677865226976,842.4352240987247 L 1135.7991114492384,840.6702084742394 Z" /></g><g id="bg-72211eb6" class="hi-bg-element" data-bg-type="countertops" data-bg-edit-type="closed" data-bg-layer="150" style=""><path class="countertops" d=" M 813.840308203785,590.2578059499979 L 1135.7991114492384,590.2578059499979 L 1135.1457680652306,999.4994184222156 L 1035.1958262230091,999.4994184222156 L 1035.1958262230091,692.5103113353923 L 813.8780978580899,692.5103113353923 Z" /></g><g id="bg-2050bbd5" class="hi-bg-element" data-bg-type="shelves" data-bg-edit-type="closed" data-bg-layer="160" style=""><path class="shelves" d=" M 692.7237893902359,1128.8832123396437 L 718.3802260343186,1128.8832123396437 L 718.3802260343186,1462.41688871272 L 692.7237893902359,1462.41688871272 Z" /></g><g id="bg-d0dbad84" class="hi-bg-element" data-bg-type="cabinets" data-bg-edit-type="closed" data-bg-layer="170" style=""><path class="cabinets" d=" M 1010.5929101871176,590.2578059499979 L 1135.7991114492384,590.2578059499979 L 1135.7991114492384,617.0877062204523 L 1010.5929101871176,617.0877062204523 Z M 813.840308203785,590.2578059499979 L 885.3867089249968,590.2578059499979 L 885.3867089249968,617.0877062204523 L 813.840308203785,617.0877062204523 Z" /></g><g id="bg-6a3c801e" class="hi-bg-element" data-bg-type="interior-walls" data-bg-edit-type="open" data-bg-layer="210" style=""><path class="interior-wall-stroke" d=" M 535.4461170119013,585.421087933012 L 535.4461170119013,1006.6386999823744 M 392.66048580872757,1006.6386999823744 L 585.421087933012,1006.6386999823744 M 671.0924666549163,999.4994184222156 L 713.9281560158684,999.4994184222156 M 414.07833048920367,585.421087933012 L 414.07833048920367,956.6637290612636 L 299.8498255266647,956.6637290612636 L 299.8498255266647,1006.6386999823744 L 321.2676702071408,1006.6386999823744 M 414.07833048920367,956.6637290612636 L 414.07833048920367,1006.6386999823744 M 692.5103113353923,999.4994184222156 L 692.5103113353923,1463.55271983253 L 635.3960588541228,1463.55271983253 L 635.3960588541228,1170.842175866024 L 692.5103113353923,1170.842175866024 M 856.713787219042,999.4994184222156 L 1227.9564283472935,999.4994184222156 M 1135.1457680652306,585.421087933012 L 1135.1457680652306,999.4994184222156 M 1135.1457680652306,842.4352240987247 L 1263.6528361480869,842.4352240987247 M 1356.46349643015,592.5603694931707 L 1356.46349643015,849.5745056588834 M 1342.1849333098326,849.5745056588834 L 1377.881341110626,849.5745056588834 M 1356.46349643015,999.4994184222156 L 1356.46349643015,1470.6920013926888 M 1342.1849333098326,999.4994184222156 L 1370.7420595504673,999.4994184222156 M 1458.5552351537258,1002.3551395770097 L 1760.546847718594,1002.3551395770097 M 1760.546847718594,931.6762515299129 L 1484.2566489890337,931.6762515299129 L 1484.2566489890337,1066.6086741652796 L 1760.546847718594,1066.6086741652796 M 1458.5552351537258,848.1466565651621 L 1484.2566489890337,848.1466565651621 L 1484.2566489890337,931.6762515299129 M 413.49291379274786,783.4602577125748 L 533.1882309432801,783.4602577125748" /><path d=" M 535.4461170119013,585.421087933012 L 535.4461170119013,1006.6386999823744 M 392.66048580872757,1006.6386999823744 L 585.421087933012,1006.6386999823744 M 671.0924666549163,999.4994184222156 L 713.9281560158684,999.4994184222156 M 414.07833048920367,585.421087933012 L 414.07833048920367,956.6637290612636 L 299.8498255266647,956.6637290612636 L 299.8498255266647,1006.6386999823744 L 321.2676702071408,1006.6386999823744 M 414.07833048920367,956.6637290612636 L 414.07833048920367,1006.6386999823744 M 692.5103113353923,999.4994184222156 L 692.5103113353923,1463.55271983253 L 635.3960588541228,1463.55271983253 L 635.3960588541228,1170.842175866024 L 692.5103113353923,1170.842175866024 M 856.713787219042,999.4994184222156 L 1227.9564283472935,999.4994184222156 M 1135.1457680652306,585.421087933012 L 1135.1457680652306,999.4994184222156 M 1135.1457680652306,842.4352240987247 L 1263.6528361480869,842.4352240987247 M 1356.46349643015,592.5603694931707 L 1356.46349643015,849.5745056588834 M 1342.1849333098326,849.5745056588834 L 1377.881341110626,849.5745056588834 M 1356.46349643015,999.4994184222156 L 1356.46349643015,1470.6920013926888 M 1342.1849333098326,999.4994184222156 L 1370.7420595504673,999.4994184222156 M 1458.5552351537258,1002.3551395770097 L 1760.546847718594,1002.3551395770097 M 1760.546847718594,931.6762515299129 L 1484.2566489890337,931.6762515299129 L 1484.2566489890337,1066.6086741652796 L 1760.546847718594,1066.6086741652796 M 1458.5552351537258,848.1466565651621 L 1484.2566489890337,848.1466565651621 L 1484.2566489890337,931.6762515299129 M 413.49291379274786,783.4602577125748 L 533.1882309432801,783.4602577125748" class="hi-bg-hit-area" /></g><g id="bg-eaf78ab0" class="hi-bg-element" data-bg-type="exterior-walls" data-bg-edit-type="open" data-bg-layer="220" style=""><path class="exterior-wall-stroke" d=" M 574.5181262476289,584.8698041980365 L 207.03355900815453,584.8698041980365 L 206.74645689637393,1468.9879832110778 L 402.61152132451764,1468.9879832110778 M 1011.9694995454092,1468.9879832110778 L 1240.9726139140773,1469.889892208907 M 602.0518005559562,1468.4190257462346 L 816.1044351172654,1468.9879832110778 M 1340.3709058052534,1469.889892208907 L 1484.9502394651458,1469.889892208907 M 1523.3949455522288,587.5951932844312 L 1762.7855798532935,587.5951932844312 L 1762.0606289799398,1466.8778227576593 L 1686.7588926987457,1466.8778227576593 M 994.0664815843922,588.1126304661587 L 1425.4624133381571,587.5951932844312 M 678.0349057517061,590.0456431732404 L 892.2741823948769,587.5951932844312" /><path d=" M 574.5181262476289,584.8698041980365 L 207.03355900815453,584.8698041980365 L 206.74645689637393,1468.9879832110778 L 402.61152132451764,1468.9879832110778 M 1011.9694995454092,1468.9879832110778 L 1240.9726139140773,1469.889892208907 M 602.0518005559562,1468.4190257462346 L 816.1044351172654,1468.9879832110778 M 1340.3709058052534,1469.889892208907 L 1484.9502394651458,1469.889892208907 M 1523.3949455522288,587.5951932844312 L 1762.7855798532935,587.5951932844312 L 1762.0606289799398,1466.8778227576593 L 1686.7588926987457,1466.8778227576593 M 994.0664815843922,588.1126304661587 L 1425.4624133381571,587.5951932844312 M 678.0349057517061,590.0456431732404 L 892.2741823948769,587.5951932844312" class="hi-bg-hit-area" /></g><g id="bg-49311b97" class="hi-bg-element" data-bg-type="fencing" data-bg-edit-type="open" data-bg-layer="230" style=""><path class="fencing" d=" M 1762.7855798532935,1164.3089941006322 L 1936.8878593449767,1164.3089941006322 L 1936.8878593449767,97.93253221407186 L 43.525569872920826,97.93253221407186 L 43.525569872920826,1153.427601632402 L 206.74645689637393,1153.427601632402" /><path d=" M 1762.7855798532935,1164.3089941006322 L 1936.8878593449767,1164.3089941006322 L 1936.8878593449767,97.93253221407186 L 43.525569872920826,97.93253221407186 L 43.525569872920826,1153.427601632402 L 206.74645689637393,1153.427601632402" class="hi-bg-hit-area" /></g><g id="bg-6a1c42ce" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(1 1) translate(1343.434443301661, 1470.0092219951305) rotate(175, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-0149af8a" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(1 1) translate(570.8311047986035, 588.3788974875479) rotate(0, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-85ef6b4d" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(0.7054358800491191 0.7054358800491191) translate(449.8739395266207, 1430.4751401800224) rotate(0, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-edb2f1a3" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(-0.8234809714326543 0.8234809714326543) translate(-257.56443409614195, 1214.1984439205394) rotate(170, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-52df8954" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(-0.8806400702030412 0.8806400702030412) translate(-766.7655284599324, 1133.8472673570027) rotate(5, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-97d4d3aa" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(0.7833497464347192 0.7833497464347192) translate(1715.6754495345706, 1082.3480058807477) rotate(180, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-837a1bec" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(-0.7821939836383923 0.7821939836383923) translate(-1757.004207878986, 1083.878371113345) rotate(175, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-bef2f166" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(0.8634680756134355 0.8634680756134355) translate(1586.4922142563114, 1162.336305072444) rotate(0, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-77d6d99c" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1 1) translate(888.3283305964862, 584.0696798834977) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-4502af03" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1 1) translate(1423.1382720557158, 584.013039453767) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-27c5b1f4" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1 1) translate(394.27969140821125, 1463.4218567234573) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-7638c539" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1 1) translate(498.50010397456776, 1463.4219083204023) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-5363d97c" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1 1) translate(811.9937157645256, 1464.5908881152973) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-77ea9b7e" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1 1) translate(916.6674775218518, 1464.1326354237362) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-654adcb5" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1 1) translate(1482.7244608460505, 1464.4419162491176) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-3ed534c0" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1 1) translate(1584.3485355529924, 1464.4681454830954) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-763f4e6d" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.4511318287257404 1.4511318287257404) translate(374.7248255017258, 412.0498227844541) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-465d5dee" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.6036416776108073 1.6036416776108073) translate(339.1426910268911, 499.5569239009369) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-2396bd3e" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.8003118890714143 1.8003118890714143) translate(355.68300032894217, 672.6183064423602) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-0e568348" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.3026996312489676 1.3026996312489676) translate(923.4647384361836, 646.4697536197046) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-bf5bb0a8" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.7051106170326136 1.7051106170326136) translate(888.8138362861508, 542.4325110472302) rotate(0, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-e7d595ad" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.7262818715897663 1.7262818715897663) translate(877.416655488979, 613.0003202710542) rotate(0, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g>
+</g>
+
+</svg>
diff --git a/src/hi/apps/profiles/templates/profiles/svg/backgrounds/single_story-1.svg b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/single_story-1.svg
new file mode 100644
index 00000000..2d145052
--- /dev/null
+++ b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/single_story-1.svg
@@ -0,0 +1,5 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000">
+<g data-hi-editor="1" data-hi-name="Attic">
+<g id="bg-cb1ba43b" class="hi-bg-element" data-bg-type="dead-space" data-bg-edit-type="closed" data-bg-layer="120" style=""><path class="dead-space" d=" M 174.1022794916833,848.7486125219561 L 1316.648488655855,848.7486125219561 L 1316.648488655855,1392.8182359334664 L 174.1022794916833,1392.8182359334664 Z" /></g><g id="bg-68fde669" class="hi-bg-element" data-bg-type="transitions" data-bg-edit-type="open" data-bg-layer="190" style=""><path class="transitions" d=" M 1316.648488655855,718.1719029031937 L 1468.9879832110778,718.1719029031937 L 1468.9879832110778,794.3416501808051 L 1316.648488655855,794.3416501808051 L 1316.648488655855,718.1719029031937" /><path d=" M 1316.648488655855,718.1719029031937 L 1468.9879832110778,718.1719029031937 L 1468.9879832110778,794.3416501808051 L 1316.648488655855,794.3416501808051 L 1316.648488655855,718.1719029031937" class="hi-bg-hit-area" /></g><g id="bg-b1460f63" class="hi-bg-element" data-bg-type="exterior-walls" data-bg-edit-type="open" data-bg-layer="220" style=""><path class="exterior-wall-stroke" d=" M 174.1022794916833,1392.8182359334664 L 174.1022794916833,478.7812686021291 L 1806.3111497262144,478.7812686021291 L 1806.3111497262144,1392.8182359334664 L 174.1022794916833,1392.8182359334664" /><path d=" M 174.1022794916833,1392.8182359334664 L 174.1022794916833,478.7812686021291 L 1806.3111497262144,478.7812686021291 L 1806.3111497262144,1392.8182359334664 L 174.1022794916833,1392.8182359334664" class="hi-bg-hit-area" /></g></g>
+
+</svg>
diff --git a/src/hi/apps/profiles/templates/profiles/svg/backgrounds/two_story-0.svg b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/two_story-0.svg
new file mode 100644
index 00000000..1357a9f2
--- /dev/null
+++ b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/two_story-0.svg
@@ -0,0 +1,5 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000">
+<g data-hi-editor="1" data-hi-name="My Home">
+<g id="bg-6953a389" class="hi-bg-element" data-bg-type="property-lines" data-bg-edit-type="closed" data-bg-layer="10" style=""><path class="property-lines" d=" M 21.762784936460413,21.762784936460413 L 1991.2948216861278,21.762784936460413 L 1980.4134292178976,1969.5320367496674 L 32.64417740469062,1969.5320367496674 Z" /></g><g id="bg-92128b69" class="hi-bg-element" data-bg-type="grass" data-bg-edit-type="closed" data-bg-layer="20" style=""><path class="grass" d=" M 21.762784936460413,21.762784936460413 L 1991.2948216861278,21.762784936460413 L 1980.4134292178976,1969.5320367496674 L 32.64417740469062,1969.5320367496674 Z" /></g><g id="bg-58757953" class="hi-bg-element" data-bg-type="pavement" data-bg-edit-type="closed" data-bg-layer="40" style=""><path class="pavement" d=" M 990.2067146089488,1545.1577304886894 L 1251.3601338464737,1545.1577304886894 L 1251.3601338464737,1643.0902627027613 L 1196.9531715053226,1643.0902627027613 L 1196.9531715053226,1958.6506442814373 L 1044.6136769501,1958.6506442814373 L 1044.6136769501,1643.0902627027613 L 990.2067146089488,1643.0902627027613 Z" /></g><g id="bg-f931a0bc" class="hi-bg-element" data-bg-type="pavement" data-bg-edit-type="closed" data-bg-layer="40" style=""><path class="pavement" d=" M 1838.9553271309048,1273.1229187829342 L 1958.6506442814373,1273.1229187829342 L 1958.6506442814373,1762.7855798532935 L 1196.9531715053226,1762.7855798532935 L 1196.9531715053226,1643.0902627027613 L 1838.9553271309048,1643.0902627027613 Z" /></g><g id="bg-77c99d32" class="hi-bg-element" data-bg-type="mulch" data-bg-edit-type="closed" data-bg-layer="60" style=""><path class="mulch" d=" M 272.03481170575515,1545.1577304886894 L 903.1555748631072,1545.1577304886894 L 904.028010438695,1592.5882049179083 L 899.3439274830541,1620.6927026517537 L 889.9757615717723,1644.1131174299583 L 871.2394297492087,1662.849449252522 L 843.1349320153632,1672.2176151638039 L 810.3463513258769,1676.9016981194447 L 369.96734391982704,1675.7344401074517 L 332.5698898505044,1672.2176151638039 L 304.46539211665896,1662.849449252522 L 285.72906029409535,1648.7972003855994 L 276.3608943828135,1630.0608685630357 L 271.6768114271726,1616.0086196961129 L 272.03481170575515,1599.5646928298404 Z" /></g><g id="bg-63f0dff5" class="hi-bg-element" data-bg-type="interior-floors" data-bg-edit-type="closed" data-bg-layer="130" style=""><path class="interior-floors" d=" M 219.50507403902773,292.673432052037 L 1838.9553271309048,293.7975966422156 L 1850.1141954718053,1546.9881408464812 L 219.50507403902773,1546.9881408464812 Z" /></g><g id="bg-80940722" class="hi-bg-element" data-bg-type="dead-space" data-bg-edit-type="closed" data-bg-layer="135" style=""><path class="dead-space" d=" M 1077.2578543547904,1099.020639291251 L 1207.834563973553,1099.020639291251 L 1207.834563973553,1207.834563973553 L 1077.2578543547904,1207.834563973553 Z" /></g><g id="bg-e557283b" class="hi-bg-element" data-bg-type="countertops" data-bg-edit-type="closed" data-bg-layer="150" style=""><path class="countertops" d=" M 1381.9368434652363,968.4439296724884 L 1566.9205154251497,968.4439296724884 L 1566.9205154251497,1088.1392468230206 L 1381.9368434652363,1088.1392468230206 Z" /></g><g id="bg-85fbf6a6" class="hi-bg-element" data-bg-type="countertops" data-bg-edit-type="closed" data-bg-layer="150" style=""><path class="countertops" d=" M 1381.9368434652363,1088.1392468230206 L 1675.7344401074517,1088.1392468230206 L 1675.7344401074517,1196.9531715053226 L 1381.9368434652363,1196.9531715053226 Z" /></g><g id="bg-ef71d1c8" class="hi-bg-element" data-bg-type="shelves" data-bg-edit-type="closed" data-bg-layer="160" style=""><path class="shelves" d=" M 924.9183597995676,293.7975966422156 L 990.2067146089488,293.7975966422156 L 990.2067146089488,609.3579782208916 L 924.9183597995676,609.3579782208916 Z" /></g><g id="bg-68ab7ad2" class="hi-bg-element" data-bg-type="shelves" data-bg-edit-type="closed" data-bg-layer="160" style=""><path class="shelves" d=" M 990.2067146089488,293.7975966422156 L 1044.6136769501,293.7975966422156 L 1044.6136769501,609.3579782208916 L 990.2067146089488,609.3579782208916 Z" /></g><g id="bg-434d8745" class="hi-bg-element" data-bg-type="shelves" data-bg-edit-type="closed" data-bg-layer="160" style=""><path class="shelves" d=" M 837.8672200537259,609.3579782208916 L 1131.6648166959415,609.3579782208916 L 1131.6648166959415,652.8835480938124 L 837.8672200537259,652.8835480938124 Z" /></g><g id="bg-f23adfde" class="hi-bg-element" data-bg-type="transitions" data-bg-edit-type="open" data-bg-layer="190" style=""><path class="transitions" d=" M 1001.088107077179,1643.0902627027613 L 1251.3601338464737,1643.0902627027613" /><path d=" M 1001.088107077179,1643.0902627027613 L 1251.3601338464737,1643.0902627027613" class="hi-bg-hit-area" /></g><g id="bg-6b868565" class="hi-bg-element" data-bg-type="transitions" data-bg-edit-type="open" data-bg-layer="190" style=""><path class="transitions" d=" M 1838.9553271309048,1479.8693756793082 L 1958.6506442814373,1479.8693756793082" /><path d=" M 1838.9553271309048,1479.8693756793082 L 1958.6506442814373,1479.8693756793082" class="hi-bg-hit-area" /></g><g id="bg-831ff843" class="hi-bg-element" data-bg-type="stairs" data-bg-edit-type="icon" data-bg-layer="200" transform="scale(2.1220496836042306 2.1220496836042306) translate(509.7007250701858, 570.2084586705328) rotate(0, 0, 0)"><path class="stairs" d="M 0,0 L 60,0 L 60,10 L 0,10 Z M 0,10 L 60,10 L 60,20 L 0,20 Z M 0,20 L 60,20 L 60,30 L 0,30 Z M 0,30 L 60,30 L 60,40 L 0,40 Z M 0,40 L 60,40 L 60,50 L 0,50 Z M 0,50 L 60,50 L 60,60 L 0,60 Z M 0,60 L 60,60 L 60,70 L 0,70 Z M 0,70 L 60,70 L 60,80 L 0,80 Z" /><rect x="0" y="0" width="60" height="80" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-a2483743" class="hi-bg-element" data-bg-type="interior-walls" data-bg-edit-type="open" data-bg-layer="210" style=""><path class="interior-wall-stroke" d=" M 217.62784936460412,914.0369673313373 L 837.8672200537259,914.0369673313373 L 837.8672200537259,881.3927899266467 M 837.8672200537259,293.7975966422156 L 837.8672200537259,609.3579782208916 L 1131.6648166959415,609.3579782208916 L 1131.6648166959415,304.6789891104458 M 990.2067146089488,304.6789891104458 L 990.2067146089488,609.3579782208916 M 837.8672200537259,707.2905104349634 L 1131.6648166959415,707.2905104349634 L 1131.6648166959415,609.3579782208916 L 837.8672200537259,609.3579782208916 L 837.8672200537259,772.5788652443447 M 1131.6648166959415,707.2905104349634 L 1164.3089941006322,707.2905104349634" /><path d=" M 217.62784936460412,914.0369673313373 L 837.8672200537259,914.0369673313373 L 837.8672200537259,881.3927899266467 M 837.8672200537259,293.7975966422156 L 837.8672200537259,609.3579782208916 L 1131.6648166959415,609.3579782208916 L 1131.6648166959415,304.6789891104458 M 990.2067146089488,304.6789891104458 L 990.2067146089488,609.3579782208916 M 837.8672200537259,707.2905104349634 L 1131.6648166959415,707.2905104349634 L 1131.6648166959415,609.3579782208916 L 837.8672200537259,609.3579782208916 L 837.8672200537259,772.5788652443447 M 1131.6648166959415,707.2905104349634 L 1164.3089941006322,707.2905104349634" class="hi-bg-hit-area" /></g><g id="bg-400e9d39" class="hi-bg-element" data-bg-type="interior-walls" data-bg-edit-type="open" data-bg-layer="210" style=""><path class="interior-wall-stroke" d=" M 1077.2578543547904,1207.834563973553 L 1077.2578543547904,914.0369673313373 L 1381.9368434652363,914.0369673313373 L 1381.9368434652363,1088.1392468230206 L 1838.9553271309048,1088.1392468230206 M 1273.1229187829342,707.2905104349634 L 1838.9553271309048,707.2905104349634 M 1381.9368434652363,707.2905104349634 L 1381.9368434652363,794.3416501808051" /><path d=" M 1077.2578543547904,1207.834563973553 L 1077.2578543547904,914.0369673313373 L 1381.9368434652363,914.0369673313373 L 1381.9368434652363,1088.1392468230206 L 1838.9553271309048,1088.1392468230206 M 1273.1229187829342,707.2905104349634 L 1838.9553271309048,707.2905104349634 M 1381.9368434652363,707.2905104349634 L 1381.9368434652363,794.3416501808051" class="hi-bg-hit-area" /></g><g id="bg-1973ec36" class="hi-bg-element" data-bg-type="exterior-walls" data-bg-edit-type="open" data-bg-layer="220" style=""><path class="exterior-wall-stroke" d=" M 1055.49506941833,1545.1577304886894 L 217.62784936460412,1545.1577304886894 L 217.62784936460412,293.7975966422156 L 1838.9553271309048,293.7975966422156 L 1838.9553271309048,1305.7670961876247 M 1838.9553271309048,1425.4624133381571 L 1838.9553271309048,1545.1577304886894 L 1175.1903865688623,1545.1577304886894" /><path d=" M 1055.49506941833,1545.1577304886894 L 217.62784936460412,1545.1577304886894 L 217.62784936460412,293.7975966422156 L 1838.9553271309048,293.7975966422156 L 1838.9553271309048,1305.7670961876247 M 1838.9553271309048,1425.4624133381571 L 1838.9553271309048,1545.1577304886894 L 1175.1903865688623,1545.1577304886894" class="hi-bg-hit-area" /></g><g id="bg-a675456f" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(1.2878961630546426 1.2878961630546426) translate(917.5577476515272, 1192.9941482670415) rotate(175, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-f4f141ea" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(-1.13815062325021 1.13815062325021) translate(-733.3290822022855, 774.4078180700437) rotate(270, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-ed414e4c" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(-1.111541536226149 1.111541536226149) translate(-1046.9500262136307, 636.314890688797) rotate(180, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-58886c1d" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(-1.2232799153640204 1.2232799153640204) translate(-1128.5118728750529, 745.4226692921069) rotate(270, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-1c8481e6" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(-1.2877442375572465 1.2877442375572465) translate(-1427.5930943341953, 1113.7052197709975) rotate(270, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-9ac0d0cf" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.6330540179952042 1.6330540179952042) translate(270.63030612505963, 176.14029968630268) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-0e0aa687" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.5515005169718687 1.5515005169718687) translate(144.70715690272507, 407.88035077862247) rotate(90, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-ec0db250" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.541754124134481 1.541754124134481) translate(142.7290881683745, 743.8851185734559) rotate(90, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-c0d82c5f" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.4737957180218078 1.4737957180218078) translate(359.68692873924863, 1044.8023025868222) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-2dd6bed9" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.5051501997863896 1.5051501997863896) translate(1021.7036222478315, 1022.303610682145) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-1c48d082" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.3662538774719857 1.3662538774719857) translate(1351.5973781144771, 528.0373323442393) rotate(90, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-7a48e6b6" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.4536733397152435 1.4536733397152435) translate(1004.7473048933712, 197.219987751336) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-1ec0d997" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.4407926989155289 1.4407926989155289) translate(1281.4129055123378, 273.5736777329555) rotate(90, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-c9248787" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.5429193072333054 1.5429193072333054) translate(883.2899915661335, 997.7019731842762) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-17b3e787" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(2.0787154432591337 2.0787154432591337) translate(413.95705734406073, 336.6814446334706) rotate(0, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-9b3640e7" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.8840749951546911 1.8840749951546911) translate(450.0095890129806, 181.341953187801) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-c5391803" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.838185613831079 1.838185613831079) translate(620.4448900572539, 186.82961890425827) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g></g>
+
+</svg>
diff --git a/src/hi/apps/profiles/templates/profiles/svg/backgrounds/two_story-1.svg b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/two_story-1.svg
new file mode 100644
index 00000000..f14abd72
--- /dev/null
+++ b/src/hi/apps/profiles/templates/profiles/svg/backgrounds/two_story-1.svg
@@ -0,0 +1,5 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000">
+<g data-hi-editor="1" data-hi-name="Upstairs">
+<g id="bg-6953a389" class="hi-bg-element" data-bg-type="property-lines" data-bg-edit-type="closed" data-bg-layer="10" style=""><path class="property-lines" d=" M 21.762784936460413,21.762784936460413 L 1991.2948216861278,21.762784936460413 L 1980.4134292178976,1969.5320367496674 L 32.64417740469062,1969.5320367496674 Z" /></g><g id="bg-92128b69" class="hi-bg-element" data-bg-type="grass" data-bg-edit-type="closed" data-bg-layer="20" style=""><path class="grass" d=" M 21.762784936460413,21.762784936460413 L 1991.2948216861278,21.762784936460413 L 1980.4134292178976,1969.5320367496674 L 32.64417740469062,1969.5320367496674 Z" /></g><g id="bg-1e97e705" class="hi-bg-element" data-bg-type="dead-space" data-bg-edit-type="closed" data-bg-layer="135" style=""><path class="dead-space" d=" M 217.62784936460412,1218.7159564417832 L 1838.9553271309048,1218.7159564417832 L 1838.9553271309048,1545.1577304886894 L 217.62784936460412,1545.1577304886894 Z" /></g><g id="bg-34ba1eb2" class="hi-bg-element" data-bg-type="dead-space" data-bg-edit-type="closed" data-bg-layer="135" style=""><path class="dead-space" d=" M 217.62784936460412,293.7975966422156 L 859.6300049901863,293.7975966422156 L 859.6300049901863,478.7812686021291 L 217.62784936460412,478.7812686021291 Z" /></g><g id="bg-93aea48b" class="hi-bg-element" data-bg-type="dead-space" data-bg-edit-type="closed" data-bg-layer="135" style=""><path class="dead-space" d=" M 1262.241526314704,293.7975966422156 L 1838.9553271309048,293.7975966422156 L 1838.9553271309048,489.6626610703593 L 1262.241526314704,489.6626610703593 Z" /></g><g id="bg-25dc26de" class="hi-bg-element" data-bg-type="countertops" data-bg-edit-type="closed" data-bg-layer="150" style=""><path class="countertops" d=" M 1120.7834242277113,293.7975966422156 L 1262.241526314704,293.7975966422156 L 1262.241526314704,544.0696234115103 L 1120.7834242277113,544.0696234115103 Z" /></g><g id="bg-831ff843" class="hi-bg-element" data-bg-type="stairs" data-bg-edit-type="icon" data-bg-layer="200" transform="scale(2.1220496836042306 2.1220496836042306) translate(509.70064219689715, 490.2151207399129) rotate(0, 0, 0)"><path class="stairs" d="M 0,0 L 60,0 L 60,10 L 0,10 Z M 0,10 L 60,10 L 60,20 L 0,20 Z M 0,20 L 60,20 L 60,30 L 0,30 Z M 0,30 L 60,30 L 60,40 L 0,40 Z M 0,40 L 60,40 L 60,50 L 0,50 Z M 0,50 L 60,50 L 60,60 L 0,60 Z M 0,60 L 60,60 L 60,70 L 0,70 Z M 0,70 L 60,70 L 60,80 L 0,80 Z" /><rect x="0" y="0" width="60" height="80" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-a2483743" class="hi-bg-element" data-bg-type="interior-walls" data-bg-edit-type="open" data-bg-layer="210" style=""><path class="interior-wall-stroke" d=" M 859.6300049901863,293.7975966422156 L 859.6300049901863,848.7486125219561 M 859.6300049901863,598.4765857526613 L 1022.8508920136394,598.4765857526613 L 1022.8508920136394,805.2230426490353 M 1229.5973489100134,805.2230426490353 L 1262.241526314704,805.2230426490353 L 1262.241526314704,293.7975966422156 M 859.6300049901863,805.2230426490353 L 1131.6648166959415,805.2230426490353" /><path d=" M 859.6300049901863,293.7975966422156 L 859.6300049901863,848.7486125219561 M 859.6300049901863,598.4765857526613 L 1022.8508920136394,598.4765857526613 L 1022.8508920136394,805.2230426490353 M 1229.5973489100134,805.2230426490353 L 1262.241526314704,805.2230426490353 L 1262.241526314704,293.7975966422156 M 859.6300049901863,805.2230426490353 L 1131.6648166959415,805.2230426490353" class="hi-bg-hit-area" /></g><g id="bg-400e9d39" class="hi-bg-element" data-bg-type="interior-walls" data-bg-edit-type="open" data-bg-layer="210" style=""><path class="interior-wall-stroke" d=" M 1077.2578543547904,1218.7159564417832 L 1077.2578543547904,1001.088107077179 L 848.7486125219561,1001.088107077179 L 848.7486125219561,957.5625372042582 M 1262.241526314704,837.8672200537259 L 1262.241526314704,805.2230426490353 M 1262.241526314704,957.5625372042582 L 1262.241526314704,1001.088107077179 L 1207.834563973553,1001.088107077179 L 1207.834563973553,1218.7159564417832 M 848.7486125219561,1001.088107077179 L 848.7486125219561,1218.7159564417832" /><path d=" M 1077.2578543547904,1218.7159564417832 L 1077.2578543547904,1001.088107077179 L 848.7486125219561,1001.088107077179 L 848.7486125219561,957.5625372042582 M 1262.241526314704,837.8672200537259 L 1262.241526314704,805.2230426490353 M 1262.241526314704,957.5625372042582 L 1262.241526314704,1001.088107077179 L 1207.834563973553,1001.088107077179 L 1207.834563973553,1218.7159564417832 M 848.7486125219561,1001.088107077179 L 848.7486125219561,1218.7159564417832" class="hi-bg-hit-area" /></g><g id="bg-f59c8437" class="hi-bg-element" data-bg-type="interior-walls" data-bg-edit-type="open" data-bg-layer="210" style=""><path class="interior-wall-stroke" d=" M 217.62784936460412,478.7812686021291 L 859.6300049901863,478.7812686021291 M 217.62784936460412,1218.7159564417832 L 1838.9553271309048,1218.7159564417832 M 1262.241526314704,489.6626610703593 L 1838.9553271309048,489.6626610703593" /><path d=" M 217.62784936460412,478.7812686021291 L 859.6300049901863,478.7812686021291 M 217.62784936460412,1218.7159564417832 L 1838.9553271309048,1218.7159564417832 M 1262.241526314704,489.6626610703593 L 1838.9553271309048,489.6626610703593" class="hi-bg-hit-area" /></g><g id="bg-1973ec36" class="hi-bg-element" data-bg-type="exterior-walls" data-bg-edit-type="open" data-bg-layer="220" style=""><path class="exterior-wall-stroke" d=" M 1175.1903865688623,1545.1577304886894 L 217.62784936460412,1545.1577304886894 L 217.62784936460412,293.7975966422156 L 1838.9553271309048,293.7975966422156 L 1838.9553271309048,1305.7670961876247 M 1838.9553271309048,1305.7670961876247 L 1838.9553271309048,1545.1577304886894 L 1175.1903865688623,1545.1577304886894" /><path d=" M 1175.1903865688623,1545.1577304886894 L 217.62784936460412,1545.1577304886894 L 217.62784936460412,293.7975966422156 L 1838.9553271309048,293.7975966422156 L 1838.9553271309048,1305.7670961876247 M 1838.9553271309048,1305.7670961876247 L 1838.9553271309048,1545.1577304886894 L 1175.1903865688623,1545.1577304886894" class="hi-bg-hit-area" /></g><g id="bg-f4f141ea" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(1.13815062325021 1.13815062325021) translate(758.2183557515999, 738.0774654526311) rotate(90, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-ed414e4c" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(-1.111541536226149 1.111541536226149) translate(-1009.7500277316166, 722.4621142197664) rotate(180, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-58886c1d" class="hi-bg-element" data-bg-type="door-standard" data-bg-edit-type="icon" data-bg-layer="240" transform="scale(-1.2232799153640204 1.2232799153640204) translate(-1028.884748995511, 677.8186197242902) rotate(85, 0, 0)"><path class="doors" d="M 0,0 L 70.71,70.71" /><path class="door-arcs" d="M 100,0 C 100,26.52 89.46,51.96 70.71,70.71" /><rect x="0" y="0" width="100" height="70.71" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-0e0aa687" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.5515005169718687 1.5515005169718687) translate(146.10984125796264, 499.0553752123392) rotate(90, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-7a48e6b6" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.4536733397152435 1.4536733397152435) translate(751.7391776881038, 200.21413127250958) rotate(0, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-1ec0d997" class="hi-bg-element" data-bg-type="window-standard" data-bg-edit-type="icon" data-bg-layer="250" transform="scale(1.4407926989155289 1.4407926989155289) translate(1281.4128179442728, 527.3331375227327) rotate(90, 0, 0)"><path class="windows" d="M 0,0 L 105,0 L 105,9 L 0,9 Z" /><rect x="0" y="0" width="105" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-43a4b221" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.4374319663218258 1.4374319663218258) translate(595.003750158413, 719.1520529688137) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-3762e60c" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.4425239894562871 1.4425239894562871) translate(713.5962563230389, 426.9508240336943) rotate(90, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-c05d9b90" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.4864541464745629 1.4864541464745629) translate(837.450205144662, 814.0250280754217) rotate(0, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-3f5eb467" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.2747213748161301 1.2747213748161301) translate(488.27584866054275, 950.9428270337767) rotate(0, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-08af485f" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.3382506781008123 1.3382506781008123) translate(343.1305784281881, 352.8878686323562) rotate(0, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g><g id="bg-2eeacc59" class="hi-bg-element" data-bg-type="sliding-door" data-bg-edit-type="icon" data-bg-layer="260" transform="scale(1.1976257380148745 1.1976257380148745) translate(1252.0237631623106, 405.2268639552499) rotate(0, 0, 0)"><path class="sliding-doors" d="M 0,0 L 120,0 L 120,9 L 0,9 Z" /><line class="sliding-doors-center" x1="60" y1="-2" x2="60" y2="11" /><rect x="0" y="0" width="120" height="9" fill="transparent" class="hi-bg-hit-area" /></g></g>
+
+</svg>
diff --git a/src/hi/apps/profiles/templates/profiles/tests/devtools/modals/snapshot_success.html b/src/hi/apps/profiles/templates/profiles/tests/devtools/modals/snapshot_success.html
index 39673a6a..d5dc12ee 100644
--- a/src/hi/apps/profiles/templates/profiles/tests/devtools/modals/snapshot_success.html
+++ b/src/hi/apps/profiles/templates/profiles/tests/devtools/modals/snapshot_success.html
@@ -11,7 +11,12 @@ Snapshot Generated Successfully
<div class="mb-3">
<strong>Profile Type:</strong> {{ profile_type_label }}<br>
- <strong>Output File:</strong> <code>{{ output_path }}</code>
+ <strong>Output Files:</strong>
+ <ul class="list-unstyled mt-1 mb-0">
+ {% for path in output_paths %}
+ <li><code>{{ path }}</code></li>
+ {% endfor %}
+ </ul>
</div>
{% if output_to_tmp %}
diff --git a/src/hi/apps/profiles/tests/devtools/profile_snapshot_generator.py b/src/hi/apps/profiles/tests/devtools/profile_snapshot_generator.py
index 4e48fe67..df5c97dd 100644
--- a/src/hi/apps/profiles/tests/devtools/profile_snapshot_generator.py
+++ b/src/hi/apps/profiles/tests/devtools/profile_snapshot_generator.py
@@ -1,15 +1,16 @@
import json
import logging
import os
-import shutil
+import re
from decimal import Decimal
from pathlib import Path
from typing import Dict, List, Any, Optional
-from django.conf import settings
+from django.core.files.storage import default_storage
from hi.apps.entity.models import Entity
from hi.apps.location.models import Location
+from hi.apps.location.edit.forms import LocationSvgFileForm
from hi.apps.collection.models import Collection
from hi.apps.profiles.enums import ProfileType
@@ -21,44 +22,49 @@ logger = logging.getLogger(__name__)
class ProfileSnapshotGenerator:
"""
Generates JSON profile specifications from current database state.
-
+
Creates profile data files in the same format used by ProfileManager for
loading, allowing developers to capture UI-configured layouts as templates.
"""
-
- def generate_snapshot(self, profile_type: ProfileType, output_to_tmp: bool = True) -> Path:
+
+ TMP_OUTPUT_DIR = Path('/tmp/hi-profile-snapshot')
+
+ def generate_snapshot(self, profile_type: ProfileType, output_to_tmp: bool = True) -> list:
"""
Generate a JSON snapshot of the current database state.
-
+
Args:
profile_type: The ProfileType enum to use for naming
- output_to_tmp: If True, writes to /tmp; if False, overwrites existing profile data file
-
+ output_to_tmp: If True, writes to /tmp/hi-profile-snapshot/;
+ if False, overwrites existing profile data files
+
Returns:
- Path to the generated JSON file
-
+ List of Paths to all generated files (JSON and any new SVG templates)
+
Raises:
ValueError: If database is empty (no locations)
"""
if not Location.objects.exists():
raise ValueError("Cannot generate snapshot from empty database")
-
+
+ output_paths = []
profile_data = self._build_profile_data(profile_type)
-
+
+ template_paths = self._write_svg_templates(profile_data, profile_type, output_to_tmp)
+ output_paths.extend(template_paths)
+
if output_to_tmp:
- output_path = Path('/tmp') / profile_type.json_filename()
+ output_path = self.TMP_OUTPUT_DIR / profile_type.json_filename()
+ output_path.parent.mkdir(parents=True, exist_ok=True)
else:
output_path = self._get_profile_json_path(profile_type)
-
+
with open(output_path, 'w') as f:
json.dump(profile_data, f, indent=2, default=str)
-
- # Copy SVG fragments to assets if writing to real profile location
- if not output_to_tmp:
- self._copy_svg_fragments_to_assets(profile_data, profile_type)
-
- logger.info(f"Generated profile snapshot to {output_path}")
- return output_path
+
+ output_paths.insert(0, output_path)
+ logger.info(f"Generated profile snapshot: {[str(p) for p in output_paths]}")
+ return output_paths
def _get_assets_base_directory(self) -> Path:
"""
@@ -71,59 +77,82 @@ class ProfileSnapshotGenerator:
"""
return Path(__file__).parent.parent.parent / 'assets'
- def _copy_svg_fragments_to_assets(self, profile_data: Dict[str, Any], profile_type: ProfileType) -> None:
+ def _write_svg_templates( self,
+ profile_data: Dict[str, Any],
+ profile_type: ProfileType,
+ output_to_tmp: bool = False) -> List[Path]:
"""
- Copy SVG fragment files from MEDIA_ROOT to profile assets directory.
+ Write SVG background templates for each Location in the profile.
- This copies the SVG fragments referenced in the profile data to the assets
- directory so they can be packaged with the application for distribution.
- The files are renamed to follow the predictable pattern: {profile_type}-{order_id}.svg
+ Each Location's SVG fragment is read from MEDIA_ROOT, wrapped in a
+ full SVG document, and written as a template file named by profile
+ type and location index (e.g., 'single_story-0.svg').
- Args:
- profile_data: The profile data containing location SVG references
- profile_type: The ProfileType enum to use for naming the SVG files
+ Modifies location data in-place: replaces the temporary
+ '_media_svg_fragment_filename' field with the proper
+ 'svg_template_name' field.
- Raises:
- FileNotFoundError: If referenced SVG fragment files don't exist in MEDIA_ROOT
- Exception: For other file system errors during copying
+ Returns:
+ List of Paths for all written template files.
"""
+ if output_to_tmp:
+ template_dir = self.TMP_OUTPUT_DIR / 'templates' / 'profiles' / 'svg' / 'backgrounds'
+ else:
+ template_dir = self._get_backgrounds_template_dir()
+ template_dir.mkdir(parents=True, exist_ok=True)
+ backgrounds_template_dir = LocationSvgFileForm.BACKGROUNDS_TEMPLATE_DIR
+
+ written_paths = []
locations_data = profile_data.get(PC.PROFILE_FIELD_LOCATIONS, [])
- assets_base_dir = self._get_assets_base_directory()
- for location_data in locations_data:
- original_svg_fragment_filename = location_data.get(PC.LOCATION_FIELD_SVG_FRAGMENT_FILENAME)
- if not original_svg_fragment_filename:
+ for index, location_data in enumerate(locations_data):
+ svg_fragment_filename = location_data.pop('_media_svg_fragment_filename', None)
+ if not svg_fragment_filename:
+ location_data[PC.LOCATION_FIELD_SVG_TEMPLATE_NAME] = ''
continue
- # Generate predictable filename: {profile_type}-{order_id}.svg
- order_id = location_data.get(PC.LOCATION_FIELD_ORDER_ID, 0)
- predictable_filename = f"location/svg/{profile_type}-{order_id}.svg"
-
- # Update the location data to use the predictable filename
- location_data[PC.LOCATION_FIELD_SVG_FRAGMENT_FILENAME] = predictable_filename
+ try:
+ with default_storage.open(svg_fragment_filename, 'r') as f:
+ fragment_content = f.read()
+ except Exception as e:
+ logger.warning(f'Could not read SVG from MEDIA_ROOT: {svg_fragment_filename}: {e}')
+ location_data[PC.LOCATION_FIELD_SVG_TEMPLATE_NAME] = ''
+ continue
- # Source: MEDIA_ROOT (original random filename)
- source_path = os.path.join(settings.MEDIA_ROOT, original_svg_fragment_filename)
+ location_name = location_data.get(PC.LOCATION_FIELD_NAME, 'unknown')
+ filename = f'{profile_type}-{index}.svg'
- # Destination: profile assets directory (predictable filename)
- destination_path = assets_base_dir / predictable_filename
+ # Update data-hi-name to reflect the location name
+ fragment_content = re.sub(
+ r'data-hi-name="[^"]*"',
+ f'data-hi-name="{location_name}"',
+ fragment_content,
+ count=1,
+ )
- try:
- if not os.path.exists(source_path):
- raise FileNotFoundError(f'SVG fragment file not found in MEDIA_ROOT: {source_path}')
+ full_svg = (
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000">\n'
+ f'{fragment_content}\n'
+ '</svg>\n'
+ )
- # Ensure destination directory exists
- destination_path.parent.mkdir(parents=True, exist_ok=True)
+ output_path = template_dir / filename
+ with open(output_path, 'w') as f:
+ f.write(full_svg)
- # Copy the file with new predictable name
- shutil.copy2(source_path, str(destination_path))
- logger.debug(f'Copied SVG fragment to assets: {source_path} -> {destination_path}')
+ template_name = os.path.join(backgrounds_template_dir, filename)
+ location_data[PC.LOCATION_FIELD_SVG_TEMPLATE_NAME] = template_name
+ written_paths.append(output_path)
+ logger.info(f'Wrote SVG template: {svg_fragment_filename} -> {output_path}')
- except Exception as e:
- logger.error(f'Failed to copy SVG fragment {original_svg_fragment_filename} to assets: {e}')
- raise
+ return written_paths
- logger.debug('SVG fragment files copied to assets successfully')
+ def _get_backgrounds_template_dir(self) -> Path:
+ """Get the filesystem path to the backgrounds template directory."""
+ return (
+ Path(__file__).parent.parent.parent
+ / 'templates' / 'profiles' / 'svg' / 'backgrounds'
+ )
def _get_profile_json_path(self, profile_type: ProfileType) -> Path:
"""Get the path to the profile JSON file in the data directory."""
@@ -149,8 +178,8 @@ class ProfileSnapshotGenerator:
for location in Location.objects.order_by('order_id'):
location_dict = {
PC.LOCATION_FIELD_NAME: location.name,
- PC.LOCATION_FIELD_SVG_FRAGMENT_FILENAME: location.svg_fragment_filename,
- PC.LOCATION_FIELD_SVG_VIEW_BOX_STR: location.svg_view_box_str,
+ # Temporary field — replaced by _reconcile_svg_templates
+ '_media_svg_fragment_filename': location.svg_fragment_filename,
PC.LOCATION_FIELD_ORDER_ID: location.order_id,
PC.LOCATION_FIELD_VIEWS: [],
}
diff --git a/src/hi/apps/profiles/tests/devtools/views.py b/src/hi/apps/profiles/tests/devtools/views.py
index 68a08fd9..49b3e1ff 100644
--- a/src/hi/apps/profiles/tests/devtools/views.py
+++ b/src/hi/apps/profiles/tests/devtools/views.py
@@ -45,11 +45,11 @@ class ProfileDevtoolsSnapshotView(HiModalView):
try:
generator = ProfileSnapshotGenerator()
- output_path = generator.generate_snapshot(profile_type, output_to_tmp)
-
+ output_paths = generator.generate_snapshot(profile_type, output_to_tmp)
+
context = {
'profile_type_label': profile_type.label,
- 'output_path': str(output_path),
+ 'output_paths': [str(p) for p in output_paths],
'output_to_tmp': output_to_tmp,
}
diff --git a/src/hi/apps/profiles/tests/test_data_utils.py b/src/hi/apps/profiles/tests/test_data_utils.py
index 8ef4079d..3d85c193 100644
--- a/src/hi/apps/profiles/tests/test_data_utils.py
+++ b/src/hi/apps/profiles/tests/test_data_utils.py
@@ -23,7 +23,7 @@ class ProfileTestDataGenerator:
# Corrupt first location's SVG file reference
if data.get('locations') and len(data['locations']) > 0:
- data['locations'][0]['svg_fragment_filename'] = 'location/svg/nonexistent-file.svg'
+ data['locations'][0]['svg_template_name'] = 'location/svg/nonexistent-file.svg'
return data
@@ -78,7 +78,7 @@ class ProfileTestDataGenerator:
# Make all locations reference non-existent SVG files
for location in data.get('locations', []):
- location['svg_fragment_filename'] = f'location/svg/invalid-{location.get("name", "unknown")}.svg'
+ location['svg_template_name'] = f'location/svg/invalid-{location.get("name", "unknown")}.svg'
return data
@@ -99,7 +99,7 @@ class ProfileTestDataGenerator:
# Corrupt some but not all locations (ensure at least 1 remains valid)
locations = data.get('locations', [])
if len(locations) > 1:
- locations[0]['svg_fragment_filename'] = 'location/svg/invalid-first.svg' # Make first invalid
+ locations[0]['svg_template_name'] = 'location/svg/invalid-first.svg' # Make first invalid
# Leave others valid
# Corrupt some but not all entities (ensure at least 1 remains valid)
diff --git a/src/hi/apps/profiles/tests/test_profile_manager.py b/src/hi/apps/profiles/tests/test_profile_manager.py
index fc40ff9b..04632bd0 100644
--- a/src/hi/apps/profiles/tests/test_profile_manager.py
+++ b/src/hi/apps/profiles/tests/test_profile_manager.py
@@ -1,7 +1,6 @@
import logging
import tempfile
from pathlib import Path
-from unittest.mock import patch
from hi.apps.profiles.profile_manager import ProfileManager
from hi.apps.profiles.enums import ProfileType
@@ -217,95 +216,58 @@ class TestProfileManager(BaseTestCase):
except Exception as e:
self.fail(f"Failed to load JSON for {profile_type}: {e}")
- def test_svg_fragment_file_management_with_test_isolation(self):
- """Test SVG fragment copying with proper test isolation using temporary directories."""
+ def test_svg_template_rendering_to_media(self):
+ """Test that profile loading renders SVG templates to MEDIA_ROOT files."""
import os
-
- # Create temporary directories for test isolation
+
with tempfile.TemporaryDirectory() as temp_media_root:
- with tempfile.TemporaryDirectory() as temp_assets_root:
- # Set up test assets directory structure
- test_assets_dir = Path(temp_assets_root)
- test_svg_dir = test_assets_dir / 'location' / 'svg'
- test_svg_dir.mkdir(parents=True, exist_ok=True)
-
- # Create test SVG fragment files
- test_svg_files = {
- 'location/svg/single_story-0.svg': '<g id="test-main">Test Main Floor</g>',
- 'location/svg/single_story-1.svg': '<g id="test-main">Test Main Floor</g>',
- }
-
- for svg_path, svg_content in test_svg_files.items():
- full_svg_path = test_assets_dir / svg_path
- with open(full_svg_path, 'w') as f:
- f.write(svg_content)
-
- # Use Django's override_settings and patch the assets directory
- with self.settings(MEDIA_ROOT=temp_media_root):
- with patch.object(self.profile_manager,
- '_get_assets_base_directory',
- return_value=test_assets_dir):
-
- # Test the actual profile loading with SVG copying
- stats = self.profile_manager.load_profile(ProfileType.SINGLE_STORY)
- self.assertTrue(stats.meets_minimum_requirements())
-
- # Verify that SVG files were copied to test MEDIA_ROOT
- for svg_filename in test_svg_files.keys():
- media_path = os.path.join(temp_media_root, svg_filename)
- self.assertTrue(
- os.path.exists(media_path),
- f"SVG file should be copied to test MEDIA_ROOT: {media_path}")
-
- # Verify file content was copied correctly
- with open(media_path, 'r') as f:
- copied_content = f.read()
- self.assertEqual(
- copied_content, test_svg_files[svg_filename],
- f"SVG file content should match: {svg_filename}")
-
- # Verify database objects were created
- locations = Location.objects.all()
- self.assertGreater(locations.count(), 0, "Should create locations")
-
- for location in locations:
- self.assertIsNotNone(
- location.svg_fragment_filename,
- "Location should have SVG fragment filename")
- # Verify the referenced file exists in test MEDIA_ROOT
- full_path = os.path.join(temp_media_root, location.svg_fragment_filename)
- self.assertTrue(
- os.path.exists(full_path),
- f"Location SVG file should exist in test MEDIA_ROOT: {full_path}")
+ with self.settings(MEDIA_ROOT=temp_media_root):
+ stats = self.profile_manager.load_profile(ProfileType.SINGLE_STORY)
+ self.assertTrue(stats.meets_minimum_requirements())
+
+ locations = Location.objects.all()
+ self.assertGreater(locations.count(), 0, "Should create locations")
+
+ for location in locations:
+ self.assertIsNotNone(
+ location.svg_fragment_filename,
+ "Location should have SVG fragment filename")
+ full_path = os.path.join(temp_media_root, location.svg_fragment_filename)
+ self.assertTrue(
+ os.path.exists(full_path),
+ f"Rendered SVG should exist in MEDIA_ROOT: {full_path}")
+ # Verify file has content
+ with open(full_path, 'r') as f:
+ content = f.read()
+ self.assertGreater(len(content), 0,
+ f"SVG file should not be empty: {full_path}")
- def test_real_profile_assets_exist(self):
- """Test that the real profile JSON files point to existing assets."""
+ def test_real_profile_templates_exist(self):
+ """Test that the real profile JSON files reference existing SVG templates."""
+ from django.template.loader import get_template
+
for profile_type in ProfileType:
- # Load the real JSON file
json_path = self.profile_manager._get_profile_json_path(profile_type)
profile_data = self.profile_manager._load_json_file(json_path)
-
- # Check that all referenced SVG files exist in the real assets directory
- locations_data = profile_data.get('locations', [])
- assets_base_dir = self.profile_manager._get_assets_base_directory()
-
- for location_data in locations_data:
- svg_filename = location_data.get('svg_fragment_filename')
- if svg_filename:
- asset_path = assets_base_dir / svg_filename
- self.assertTrue(
- asset_path.exists(),
- f"Real profile {profile_type} references missing asset: {asset_path}")
+
+ for location_data in profile_data.get('locations', []):
+ svg_template_name = location_data.get('svg_template_name')
+ if svg_template_name:
+ try:
+ get_template(svg_template_name)
+ except Exception:
+ self.fail(
+ f"Profile {profile_type} references missing template: {svg_template_name}"
+ )
- def test_profile_svg_copying_error_handling(self):
- """Test error handling when SVG fragment files are missing from assets."""
+ def test_profile_svg_template_error_handling(self):
+ """Test error handling when SVG template references are invalid."""
with tempfile.TemporaryDirectory() as temp_media_root:
with self.settings(MEDIA_ROOT=temp_media_root):
- # Mock a missing SVG file by patching the copy method
- with patch.object(self.profile_manager, '_copy_svg_fragment_files') as mock_copy:
- # Make the copy method raise FileNotFoundError
- mock_copy.side_effect = FileNotFoundError("SVG fragment file not found in assets")
-
- # Should raise FileNotFoundError when SVG file is missing
- with self.assertRaises(FileNotFoundError):
- self.profile_manager.load_profile(ProfileType.SINGLE_STORY)
+ # Load real profile data and corrupt the template reference
+ json_path = self.profile_manager._get_profile_json_path(ProfileType.SINGLE_STORY)
+ profile_data = self.profile_manager._load_json_file(json_path)
+ profile_data['locations'][0]['svg_template_name'] = 'profiles/svg/backgrounds/nonexistent.svg'
+
+ with self.assertRaises(Exception):
+ self.profile_manager._render_svg_templates(profile_data)
diff --git a/src/hi/apps/profiles/tests/test_profile_manager_error_handling.py b/src/hi/apps/profiles/tests/test_profile_manager_error_handling.py
index 3d931337..369ee416 100644
--- a/src/hi/apps/profiles/tests/test_profile_manager_error_handling.py
+++ b/src/hi/apps/profiles/tests/test_profile_manager_error_handling.py
@@ -1,6 +1,5 @@
import logging
import tempfile
-from pathlib import Path
from hi.apps.profiles.profile_manager import ProfileManager, ProfileLoadingStats
from hi.apps.entity.models import Entity, EntityPosition
@@ -20,34 +19,14 @@ class TestProfileManagerErrorHandling(BaseTestCase):
self.profile_manager = ProfileManager()
self.data_generator = ProfileTestDataGenerator()
- def test_missing_svg_files_continues_loading(self):
- """Test that missing SVG files don't stop entire profile loading."""
- # Create malformed data with non-existent SVG file
+ def test_missing_svg_template_raises_error(self):
+ """Test that a non-existent SVG template causes an error during rendering."""
malformed_data = self.data_generator.create_missing_svg_file_data()
-
- # Create temporary JSON file
- with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
- import json
- json.dump(malformed_data, f, indent=2)
- temp_file = f.name
-
- try:
- # Load malformed profile data directly
- with self.assertRaises(ValueError) as cm:
- stats = self.profile_manager._load_json_file(temp_file)
- self.profile_manager._validate_fundamental_requirements(stats)
- # Since we can't directly test the robust methods without refactoring,
- # we'll verify that missing SVG files cause ValueError
- self.profile_manager._create_locations([malformed_data['locations'][0]])
-
- # Verify error message mentions the missing file
- error_message = str(cm.exception)
- self.assertIn('SVG file not found', error_message)
- self.assertIn('nonexistent-file.svg', error_message)
-
- finally:
- # Clean up temp file
- Path(temp_file).unlink(missing_ok=True)
+
+ with tempfile.TemporaryDirectory() as temp_media_root:
+ with self.settings(MEDIA_ROOT=temp_media_root):
+ with self.assertRaises(Exception):
+ self.profile_manager._render_svg_templates(malformed_data)
def test_invalid_entity_types_individual_failure(self):
"""Test that invalid entity types cause individual entity creation failures."""
@@ -146,8 +125,8 @@ class TestProfileManagerErrorHandling(BaseTestCase):
"""Test that our data generator utilities produce the expected malformed data."""
# Test missing SVG file data
svg_data = self.data_generator.create_missing_svg_file_data()
- self.assertIn('nonexistent-file.svg',
- svg_data['locations'][0]['svg_fragment_filename'])
+ self.assertIn('nonexistent-file.svg',
+ svg_data['locations'][0]['svg_template_name'])
# Test invalid entity type data
entity_data = self.data_generator.create_invalid_entity_types_data()
@@ -162,7 +141,7 @@ class TestProfileManagerErrorHandling(BaseTestCase):
self.assertGreaterEqual(len(mixed_data['entities']), 1)
# First location should be corrupted
- self.assertIn('invalid-first.svg', mixed_data['locations'][0]['svg_fragment_filename'])
+ self.assertIn('invalid-first.svg', mixed_data['locations'][0]['svg_template_name'])
# First entity should be corrupted
self.assertEqual(mixed_data['entities'][0]['entity_type_str'], 'INVALID_FIRST_ENTITY')
@@ -233,18 +212,11 @@ class TestProfileManagerErrorHandling(BaseTestCase):
# Create data where all locations will fail due to missing SVG files
malformed_data = self.data_generator.create_all_locations_invalid_data()
- # Since we can't easily test the full robust loading without exposing internal methods,
- # we'll verify the data would cause all locations to fail by testing SVG validation
- import os
- from django.conf import settings
-
for location_data in malformed_data['locations']:
- svg_filename = location_data['svg_fragment_filename']
- full_path = os.path.join(settings.MEDIA_ROOT, svg_filename)
-
- # Verify the SVG file doesn't exist (would cause location creation failure)
- self.assertFalse(os.path.exists(full_path),
- f"Test SVG file should not exist: {full_path}")
+ svg_template_name = location_data['svg_template_name']
+ # Verify the template name references a non-existent template
+ self.assertIn('invalid', svg_template_name,
+ f"Test template should have invalid reference: {svg_template_name}")
def test_minimum_viability_failure_all_entities_fail(self):
"""Test that profile loading fails when no entities can be created."""
@@ -274,9 +246,9 @@ class TestProfileManagerErrorHandling(BaseTestCase):
valid_locations = 0
for i, location in enumerate(locations):
if i == 0: # First should be invalid
- self.assertIn('invalid-first.svg', location['svg_fragment_filename'])
+ self.assertIn('invalid-first.svg', location['svg_template_name'])
else: # Others should be valid
- self.assertNotIn('invalid', location['svg_fragment_filename'])
+ self.assertNotIn('invalid', location['svg_template_name'])
valid_locations += 1
self.assertGreater(valid_locations, 0, "Should have at least one valid location")
diff --git a/src/hi/apps/profiles/urls.py b/src/hi/apps/profiles/urls.py
index 89a30732..766372b4 100644
--- a/src/hi/apps/profiles/urls.py
+++ b/src/hi/apps/profiles/urls.py
@@ -15,8 +15,12 @@ urlpatterns = [
views.ViewReferenceHelpView.as_view(),
name='profiles_view_reference_help'),
- re_path( r'^edit-reference-help$',
- views.EditReferenceHelpView.as_view(),
+ re_path( r'^edit-reference-help$',
+ views.EditReferenceHelpView.as_view(),
name='profiles_edit_reference_help'),
-
+
+ re_path( r'^dismiss-view-intro-help$',
+ views.DismissViewIntroHelpView.as_view(),
+ name='profiles_dismiss_view_intro_help'),
+
]
diff --git a/src/hi/apps/profiles/views.py b/src/hi/apps/profiles/views.py
index c68eb2da..fe21b186 100644
--- a/src/hi/apps/profiles/views.py
+++ b/src/hi/apps/profiles/views.py
@@ -11,7 +11,11 @@ from hi.apps.location.edit.views import LocationAddFirstView
from .profile_manager import ProfileManager
from .enums import ProfileType
-from .session_helpers import mark_profile_initialized, mark_first_location_created
+from .session_helpers import (
+ mark_profile_initialized,
+ mark_first_location_created,
+ dismiss_view_intro_help,
+)
logger = logging.getLogger(__name__)
@@ -73,6 +77,14 @@ class ViewReferenceHelpView( HiModalView ):
return self.modal_response( request )
+class DismissViewIntroHelpView( View ):
+
+ def post( self, request, *args, **kwargs ):
+ dismiss_view_intro_help( request )
+ redirect_url = reverse( 'home' )
+ return antinode.redirect_response( redirect_url )
+
+
class EditReferenceHelpView( HiModalView ):
def get_template_name( self ) -> str:
diff --git a/src/hi/constants.py b/src/hi/constants.py
index f8a558a6..298dea86 100644
--- a/src/hi/constants.py
+++ b/src/hi/constants.py
@@ -151,4 +151,17 @@ DIVID = {
# Entity Picker - Filter values
'ENTITY_PICKER_FILTER_ALL': 'all',
+
+ # Location SVG Editor Grid Structure
+ 'LOCATION_SVG_EDIT_TOP': 'hi-location-svg-editor-top',
+ 'LOCATION_SVG_EDIT_BOTTOM': 'hi-location-svg-editor-bottom',
+ 'LOCATION_SVG_EDIT_MAIN': 'hi-location-svg-editor-main',
+
+ # Location SVG Editor Elements
+ 'LOCATION_SVG_EDIT_PALETTE': 'hi-svg-edit-palette',
+ 'LOCATION_SVG_EDIT_SVG': 'hi-svg-edit-svg',
+ 'LOCATION_SVG_EDIT_CANVAS': 'hi-svg-edit-canvas',
+ 'LOCATION_SVG_EDIT_CANVAS_CONTAINER': 'hi-svg-edit-canvas-container',
+ 'LOCATION_SVG_EDIT_CONFORMANCE_WARNING': 'hi-svg-edit-conformance-warning',
+
}
diff --git a/src/hi/hi_async_view.py b/src/hi/hi_async_view.py
index 6305548f..92119507 100644
--- a/src/hi/hi_async_view.py
+++ b/src/hi/hi_async_view.py
@@ -112,22 +112,23 @@ class HiModalView( View ):
def get( self, request, *args, **kwargs ):
return self.modal_response( request )
- def modal_response( self, request, context = None, status = 200 ):
+ def modal_response( self, request, context = None, status = 200, template_name = None ):
if context is None:
context = dict()
+ modal_template_name = template_name or self.get_template_name()
if is_ajax( request ):
modal_response = antinode.modal_from_template(
request = request,
- template_name = self.get_template_name(),
+ template_name = modal_template_name,
context = context,
status = status,
)
return modal_response
- context['initial_modal_template_name'] = self.get_template_name()
- template_name = self.DEFAULT_PAGE_TEMPLATE_NAME
+ context['initial_modal_template_name'] = modal_template_name
+ page_template_name = self.DEFAULT_PAGE_TEMPLATE_NAME
return render( request,
- template_name,
+ page_template_name,
context,
status = status )
diff --git a/src/hi/requirements/development.txt b/src/hi/requirements/development.txt
index 3172692a..39b5db1f 100644
--- a/src/hi/requirements/development.txt
+++ b/src/hi/requirements/development.txt
@@ -4,7 +4,6 @@ autopep8==2.3.2
fakeredis==2.35.1
black==26.3.1
flake8==7.3.0
-grip==4.6.2
jedi==0.19.2
pipdeptree==2.28.0
rope==1.14.0
diff --git a/src/hi/services/homebox/hb_client.py b/src/hi/services/homebox/hb_client.py
index 2ebdbdcd..1f59224a 100644
--- a/src/hi/services/homebox/hb_client.py
+++ b/src/hi/services/homebox/hb_client.py
@@ -32,13 +32,28 @@ class HbClient:
def _login(self):
url = f"{self._api_url}/{self.API_VERSION}/users/login"
data = {
- 'username': self._user,
- 'password': self._password,
+ 'username': self._user,
+ 'password': self._password,
'stayLoggedIn': True
}
- response = self._session.post(url, json=data, timeout=self.DEFAULT_TIMEOUT)
+ try:
+ response = self._session.post(url, json=data, timeout=self.DEFAULT_TIMEOUT)
+ except Exception as e:
+ raise ConnectionError(
+ f'Cannot connect to HomeBox at {self._api_url}. '
+ f'Verify the API URL is correct and the server is running.'
+ ) from e
+
response.raise_for_status()
-
+
+ content_type = response.headers.get('content-type', '')
+ if 'json' not in content_type:
+ raise ValueError(
+ f'HomeBox API URL may be incorrect. Expected JSON response but received '
+ f'{content_type or "unknown content type"}. '
+ f'Ensure the URL includes the API path (e.g., http://host:port/api).'
+ )
+
token = response.json().get('token')
if token:
self._session.headers.update({'Authorization': token})
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index e034b5e0..23a64660 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -250,6 +250,12 @@ PIPELINE = {
),
'output_filename': 'css/css_head.css',
},
+ 'css_location_svg_edit': {
+ 'source_filenames': (
+ 'css/location-svg-edit.css',
+ ),
+ 'output_filename': 'css/css_location_svg_edit.css',
+ },
},
'JAVASCRIPT': {
'js_before_content': {
@@ -286,15 +292,26 @@ PIPELINE = {
'js/svg-utils.js',
'js/status.js',
'js/auto-view.js',
- 'js/edit.js',
'js/edit-dragdrop.js',
- 'js/svg-icon.js',
- 'js/svg-path.js',
- 'js/svg-location.js',
- 'js/svg-event-listeners.js',
+ 'js/svg-icon-core.js',
+ 'js/svg-path-core.js',
+ 'js/svg-pan-zoom-core.js',
+ 'js/svg-entity-edit.js',
+ 'js/svg-entity-event-listeners.js',
),
'output_filename': 'js/js_hi_grid_content.js',
},
+ 'js_location_svg_edit': {
+ 'source_filenames': (
+ 'js/svg-utils.js',
+ 'js/svg-pan-zoom-core.js',
+ 'js/svg-icon-core.js',
+ 'js/svg-path-core.js',
+ 'js/svg-bg-edit.js',
+ 'js/svg-bg-event-listeners.js',
+ ),
+ 'output_filename': 'js/js_location_svg_edit.js',
+ },
}
}
diff --git a/src/hi/static/css/location-svg-edit.css b/src/hi/static/css/location-svg-edit.css
new file mode 100644
index 00000000..dc19e1fb
--- /dev/null
+++ b/src/hi/static/css/location-svg-edit.css
@@ -0,0 +1,178 @@
+/* Location SVG Editor Styles */
+
+:root {
+ --svg-editor-top-height: 5rem;
+ --svg-editor-bottom-height: 4rem;
+ --svg-editor-main-height: 4rem;
+
+ /* Teal-based edit mode colors (distinct from orange entity editing) */
+ --svg-editor-bg: #E0F2F2;
+ --svg-editor-border-color: #177072;
+ --svg-editor-dash-color: #115354;
+ --svg-editor-shadow-rgba: rgba(23, 112, 114, 0.1);
+}
+
+#hi-location-svg-editor-top {
+ height: calc( var(--svg-editor-top-height) );
+ background: var(--svg-editor-bg);
+ border-bottom: 4px dashed var(--svg-editor-dash-color);
+ box-shadow: inset 0 -2px 8px var(--svg-editor-shadow-rgba);
+}
+#hi-location-svg-editor-bottom {
+ height: var(--svg-editor-bottom-height);
+ background: var(--svg-editor-bg);
+ border-top: 4px dashed var(--svg-editor-dash-color);
+ box-shadow: inset 0 2px 8px var(--svg-editor-shadow-rgba);
+}
+#hi-location-svg-editor-main {
+ background: var(--white);
+ position: relative;
+ height: calc( 100vh - var(--svg-editor-top-height) - var(--svg-editor-bottom-height) );
+}
+#hi-location-svg-editor-main .hi-location-view {
+ height: 100%;
+ width: 100%;
+ padding: 10px;
+ box-sizing: border-box;
+}
+#hi-location-svg-editor-main .hi-location-view-svg {
+ width: 100%;
+ height: 100%;
+ display: block;
+}
+
+/* ==================== */
+/* Canvas Boundary */
+/* ==================== */
+
+.hi-svg-edit-boundary {
+ fill: none;
+ stroke: #c0c0c0;
+ stroke-width: 1;
+ stroke-dasharray: 8 4;
+ vector-effect: non-scaling-stroke;
+}
+
+/* ==================== */
+/* Warnings Area */
+/* ==================== */
+
+.hi-svg-edit-warnings {
+ position: relative;
+ z-index: 10;
+}
+.hi-svg-edit-warnings .alert {
+ border-left: none;
+ border-right: none;
+ border-radius: 0;
+}
+
+/* ==================== */
+/* Palette */
+/* ==================== */
+
+.hi-palette-container {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ padding: 0 0.5rem;
+ overflow-x: auto;
+ overflow-y: hidden;
+ min-width: 0;
+ scrollbar-width: thin;
+}
+.hi-svg-edit-buttons {
+ flex-shrink: 0;
+ padding: 0 0.25rem;
+ white-space: nowrap;
+}
+
+.hi-palette-category {
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+}
+
+.hi-palette-category-label {
+ font-size: 0.65rem;
+ font-weight: 700;
+ text-transform: uppercase;
+ color: var(--edit-mode-text-color, #888);
+ writing-mode: vertical-rl;
+ text-orientation: mixed;
+ letter-spacing: 0.05em;
+}
+
+.hi-palette-items {
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+}
+
+.hi-palette-item {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ cursor: grab;
+ padding: 2px;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ transition: border-color 0.15s, background-color 0.15s;
+}
+
+.hi-palette-item:hover {
+ border-color: var(--edit-mode-dash-color, #d4775e);
+ background-color: rgba(212, 119, 94, 0.08);
+}
+
+.hi-palette-label {
+ font-size: 0.55rem;
+ color: var(--edit-mode-text-color, #aaa);
+ text-align: center;
+ line-height: 1;
+ margin-top: 1px;
+ white-space: nowrap;
+}
+
+.hi-palette-swatch {
+ display: block;
+ border: 1px solid rgba(128, 128, 128, 0.3);
+ border-radius: 2px;
+ background: #fff;
+}
+
+/* ==================== */
+/* Palette Swatch Fills */
+/* ==================== */
+/* Flat-color overrides for palette swatches since fill patterns
+ from the main SVG are not available in separate mini-SVGs.
+ Colors are the dominant color from each pattern definition. */
+
+.hi-palette-swatch path.grass { fill: #d0ffd0; stroke: none; }
+.hi-palette-swatch path.ground { fill: #e8dcc3; stroke: none; }
+.hi-palette-swatch path.pavement { fill: #e8e8e8; stroke: none; }
+.hi-palette-swatch path.wood-decks { fill: #f2e7d9; stroke: none; }
+.hi-palette-swatch path.interior-floors { fill: #f8f8f8; stroke: #d0d0d0; stroke-width: 1; }
+.hi-palette-swatch path.exterior-wall-stroke { fill: none; stroke: black; stroke-width: 16; }
+.hi-palette-swatch path.interior-wall-stroke { fill: none; stroke: #202020; stroke-width: 8; }
+.hi-palette-swatch path.windows { fill: #78e3df; stroke: black; stroke-width: 1; }
+.hi-palette-swatch path.doors { fill: none; stroke: black; stroke-width: 4.5; }
+.hi-palette-swatch path.door-arcs { fill: none; stroke: black; stroke-width: 1; }
+.hi-palette-swatch path.countertops { fill: #e0e0e0; stroke: black; stroke-width: 1; }
+.hi-palette-swatch path.fireplaces { fill: #fff0f0; stroke: black; stroke-width: 1; }
+.hi-palette-swatch path.stairs { fill: #f0f0f0; stroke: black; stroke-width: 1; }
+.hi-palette-swatch path.shelves { fill: #fffff0; stroke: black; stroke-width: 1; }
+.hi-palette-swatch path.cabinets { fill: #c8a882; stroke: black; stroke-width: 1; }
+.hi-palette-swatch path.sliding-doors { fill: #c0c0c0; stroke: black; stroke-width: 1; }
+.hi-palette-swatch line.sliding-doors-center { stroke: black; stroke-width: 2; }
+.hi-palette-swatch path.dead-space { fill: #f0f0c0; stroke: #b0b080; stroke-width: 1; }
+.hi-palette-swatch path.transitions { fill: none; stroke: #808080; stroke-width: 2; }
+.hi-palette-swatch path.tiles { fill: #f5f5f5; stroke: #c0c0c0; stroke-width: 1; }
+.hi-palette-swatch path.asphalt { fill: #2F4F4F; stroke: none; }
+.hi-palette-swatch path.stone { fill: #b0c4de; stroke: none; }
+.hi-palette-swatch path.brick { fill: #A0522D; stroke: none; }
+.hi-palette-swatch path.mulch { fill: #d2a679; stroke: none; }
+.hi-palette-swatch path.rock-beds { fill: #f0e4d2; stroke: none; }
+.hi-palette-swatch path.gravel { fill: #D3D3D3; stroke: none; }
+.hi-palette-swatch path.fencing { fill: none; stroke: #432b0f; stroke-width: 8; }
+.hi-palette-swatch path.property-lines { fill: none; stroke: black; stroke-width: 3; stroke-dasharray: 8,3; }
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index 7756b91b..9f33bb73 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -1,5 +1,5 @@
/* Home Information
- Copyright 2024 by POMDP, Inc.
+ Copyright 2024-2026 by POMDP, LLC
All Rights Reserved.
*/
:root {
@@ -1033,6 +1033,13 @@ g[hover] {
margin-top: 0.25rem;
line-height: 1.3;
}
+.getting-started-guide a:not(.plain) {
+ color: var(--primary-color);
+ text-decoration: underline;
+}
+.getting-started-guide a:not(.plain):hover {
+ color: var(--primary-highlight-color);
+}
.getting-started-guide .help-hint {
display: flex;
@@ -1121,6 +1128,16 @@ g[hover] {
font-size: 1rem;
}
+.editing-help-guide .help-category-wide {
+ grid-column: 1 / -1;
+}
+
+.editing-help-guide .help-actions-columns {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0 1.5rem;
+}
+
.editing-help-guide .help-actions {
list-style: none;
padding: 0;
@@ -1993,3 +2010,32 @@ g[hover] {
font-size: 0.875rem;
background-color: var(--white);
}
+
+/* ==================== */
+/* SVG Template Cards */
+/* ==================== */
+
+.hi-svg-template-card {
+ width: 180px;
+ cursor: pointer;
+ transition: border-color 0.15s, box-shadow 0.15s;
+}
+.hi-svg-template-card:hover {
+ border-color: var(--primary-color) !important;
+ box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb, 13, 110, 253), 0.25);
+}
+.hi-svg-template-thumbnail {
+ width: 160px;
+ height: 120px;
+ background: #f8f9fa;
+ border: 1px solid #dee2e6;
+ border-radius: 4px;
+ overflow: hidden;
+ margin: 0 auto;
+}
+.hi-svg-template-name {
+ font-size: 0.8rem;
+ font-weight: 600;
+ text-align: center;
+ margin-top: 0.25rem;
+}
diff --git a/src/hi/static/css/simulator.css b/src/hi/static/css/simulator.css
index 8001bd5a..30f132d2 100644
--- a/src/hi/static/css/simulator.css
+++ b/src/hi/static/css/simulator.css
@@ -1,5 +1,5 @@
/* Home Information
- Copyright 2024 by POMDP, Inc.
+ Copyright 2024-2026 by POMDP, LLC
All Rights Reserved.
*/
:root {
diff --git a/src/hi/static/css/svg-location-color.css b/src/hi/static/css/svg-location-color.css
index 02ad3c72..ace2f0ed 100644
--- a/src/hi/static/css/svg-location-color.css
+++ b/src/hi/static/css/svg-location-color.css
@@ -13,7 +13,8 @@ svg.hi-location-view-svg path.rock-beds {
stroke: black;
stroke-width: 1;
}
-svg.hi-location-view-svg path.stone-walls {
+svg.hi-location-view-svg path.stone-walls,
+svg.hi-location-view-svg path.stone {
fill: url(#stone-pattern);
stroke: black;
stroke-width: 1;
@@ -25,7 +26,7 @@ svg.hi-location-view-svg path.landscape-transitions {
}
svg.hi-location-view-svg path.brick {
fill: url(#brick-pattern);
- stroke: #606060;
+ stroke: #805040;
stroke-width: 4;
}
svg.hi-location-view-svg path.mulch {
@@ -74,7 +75,7 @@ svg.hi-location-view-svg path.pool-coping {
stroke-width: 1;
}
svg.hi-location-view-svg path.property-lines {
- fill: none;
+ fill: #e8e8e8;
stroke: black;
stroke-width: 5;
stroke-dasharray: 50,10,50,10,10,10;
@@ -106,9 +107,14 @@ svg.hi-location-view-svg path.utilities {
}
svg.hi-location-view-svg path.interior-floors {
fill: #f8f8f8;
- stroke: none;
+ stroke: #d0d0d0;
stroke-width: 1;
}
+svg.hi-location-view-svg path.transitions {
+ fill: none;
+ stroke: #808080;
+ stroke-width: 2;
+}
svg.hi-location-view-svg path.floor-transitions {
fill: none;
stroke: #404040;
@@ -154,7 +160,16 @@ svg.hi-location-view-svg path.door-arcs {
svg.hi-location-view-svg path.doors {
fill: none;
stroke: black;
- stroke-width: 3;
+ stroke-width: 4.5;
+}
+svg.hi-location-view-svg path.sliding-doors {
+ fill: #c0c0c0;
+ stroke: black;
+ stroke-width: 1;
+}
+svg.hi-location-view-svg line.sliding-doors-center {
+ stroke: black;
+ stroke-width: 2;
}
svg.hi-location-view-svg path.countertops {
fill: #e0e0e0;
@@ -191,3 +206,32 @@ svg.hi-location-view-svg path.sinks {
stroke: black;
stroke-width: 1;
}
+svg.hi-location-view-svg path.cabinets {
+ fill: #c8a882;
+ stroke: black;
+ stroke-width: 1;
+}
+
+/* Open-path stroke-based wall styles for editor-compatible SVGs */
+svg.hi-location-view-svg path.exterior-wall-stroke {
+ fill: none;
+ stroke: black;
+ stroke-width: 16;
+}
+svg.hi-location-view-svg path.interior-wall-stroke {
+ fill: none;
+ stroke: #202020;
+ stroke-width: 8;
+}
+
+/* Hit areas for editor-compatible background elements */
+svg.hi-location-view-svg path.hi-bg-hit-area {
+ stroke: transparent;
+ stroke-width: 30;
+ fill: none;
+ pointer-events: stroke;
+}
+svg.hi-location-view-svg rect.hi-bg-hit-area {
+ fill: transparent;
+ pointer-events: all;
+}
diff --git a/src/hi/static/img/location-default.svg b/src/hi/static/img/location-default.svg
deleted file mode 100644
index 3b990b39..00000000
--- a/src/hi/static/img/location-default.svg
+++ /dev/null
@@ -1,2 +0,0 @@
-<?xml version='1.0' encoding='utf-8'?>
-<svg xmlns:ns0="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000"><g><ns0:path d="M 64.00,81.00 C 64.00,81.00 1905.00,78.00 1905.00,78.00 1905.00,78.00 1905.00,1903.00 1905.00,1903.00 1905.00,1903.00 64.00,1907.00 65.00,1906.00 66.00,1905.00 64.00,81.00 64.00,81.00 Z" class="grass" /><ns0:path d="M 926.25,1605.50 C 926.25,1605.50 1077.00,1605.25 1077.00,1605.25 1077.00,1605.25 1077.00,1922.00 1077.00,1922.00 1077.00,1922.00 924.50,1925.25 924.25,1924.75 924.50,1925.00 926.25,1605.50 926.25,1605.50 Z M 805.33,483.33 C 805.33,483.33 1194.67,483.00 1194.67,483.00 1194.67,483.00 1194.00,611.00 1194.00,611.00 1194.00,611.00 805.67,611.33 804.67,610.33 803.67,609.33 805.33,483.33 805.33,483.33 Z" class="pavement" /><ns0:path d="M 64.00,81.00 C 64.00,81.00 1905.00,78.00 1905.00,78.00 1905.00,78.00 1905.00,1903.00 1905.00,1903.00 1905.00,1903.00 64.00,1907.00 65.00,1906.00 66.00,1905.00 64.00,81.00 64.00,81.00 Z" class="property-lines" /><ns0:path d="M 153.00,618.00 C 153.00,618.00 1853.00,620.00 1853.00,620.00 1853.00,620.00 1852.00,1599.00 1852.00,1599.00 1852.00,1599.00 154.00,1596.00 154.00,1596.00 154.00,1596.00 153.00,618.00 153.00,618.00 Z" class="interior-floors" /><ns0:path d="M 149.00,1020.75 C 149.00,1020.75 157.75,1021.25 157.75,1021.25 157.75,1021.25 158.75,1127.00 158.75,1127.00 158.75,1127.00 149.75,1127.50 149.75,1127.50 149.75,1127.50 149.00,1020.75 149.00,1020.75 Z M 490.50,619.00 C 490.50,619.00 594.25,619.25 594.25,619.25 594.25,619.25 594.75,627.50 594.75,627.50 594.75,627.50 490.50,627.50 490.50,627.50 490.50,627.50 490.50,619.00 490.50,619.00 Z M 1405.50,619.00 C 1405.50,619.00 1510.00,619.00 1510.00,619.00 1510.00,619.00 1510.75,627.50 1510.75,627.50 1510.75,627.50 1405.50,627.75 1405.50,627.75 1405.50,627.75 1405.50,619.00 1405.50,619.00 Z M 1851.75,1021.50 C 1851.75,1021.50 1852.25,1127.75 1852.25,1127.75 1852.25,1127.75 1843.50,1127.25 1843.50,1127.25 1843.50,1127.25 1844.00,1021.25 1844.00,1021.25 1844.00,1021.25 1851.75,1021.50 1851.75,1021.50 Z M 1566.50,1597.75 C 1566.50,1597.75 1461.25,1598.25 1461.25,1598.25 1461.25,1598.25 1461.50,1588.50 1461.50,1588.50 1461.50,1588.50 1566.25,1588.75 1566.25,1588.75 1566.25,1588.75 1566.50,1597.75 1566.50,1597.75 Z M 1343.50,1589.50 C 1343.50,1589.50 1448.00,1588.75 1448.00,1588.75 1448.00,1588.75 1447.75,1598.50 1447.75,1598.50 1447.75,1598.50 1343.75,1599.00 1343.75,1599.00 1343.75,1599.00 1343.50,1589.50 1343.50,1589.50 Z M 433.25,1589.50 C 433.25,1589.50 539.25,1590.00 539.25,1590.00 539.25,1590.00 539.50,1597.75 539.50,1597.75 539.50,1597.75 433.00,1598.00 433.00,1598.00 433.00,1598.00 433.25,1589.50 433.25,1589.50 Z M 552.50,1589.50 C 552.50,1589.50 656.75,1590.00 656.75,1590.00 656.75,1590.00 656.75,1597.75 656.75,1597.75 656.75,1597.75 551.50,1597.75 551.50,1597.75 551.50,1597.75 552.50,1589.50 552.50,1589.50 Z" class="windows" /><ns0:path d="M 536.25,1589.75 C 536.25,1589.75 553.75,1589.50 553.75,1589.50 553.75,1589.50 553.50,1604.25 553.50,1604.25 553.50,1604.25 535.75,1603.50 535.75,1603.50 535.75,1603.50 536.25,1589.75 536.25,1589.75 Z M 1445.75,1588.50 C 1445.75,1588.50 1463.75,1588.25 1463.75,1588.25 1463.75,1588.25 1463.75,1604.00 1463.75,1604.00 1463.75,1604.00 1446.00,1603.50 1446.00,1603.50 1446.00,1603.50 1445.75,1588.50 1445.75,1588.50 Z M 1844.00,1025.15 C 1844.00,1025.15 1844.00,626.00 1844.00,626.00 1844.00,626.00 1507.46,627.49 1507.46,627.49 1507.46,627.49 1507.26,609.42 1507.26,609.42 1507.26,609.42 1859.00,608.00 1859.00,608.00 1859.00,608.00 1859.42,1024.92 1859.42,1024.92 1859.42,1024.92 1844.00,1025.15 1844.00,1025.15 Z M 592.18,610.27 C 592.18,610.27 944.50,610.75 944.50,610.75 944.50,610.75 945.00,629.50 945.00,629.50 945.00,629.50 592.07,627.93 592.07,627.93 592.07,627.93 592.18,610.27 592.18,610.27 Z M 653.50,1589.75 C 653.50,1589.75 946.00,1589.00 946.00,1589.00 946.00,1589.00 945.75,1606.00 945.75,1606.00 945.75,1606.00 654.00,1607.00 654.00,1607.00 654.00,1607.00 653.50,1589.75 653.50,1589.75 Z M 1408.14,627.93 C 1408.14,627.93 1055.00,629.50 1055.00,629.50 1055.00,629.50 1054.75,611.25 1054.75,611.25 1054.75,611.25 1408.39,609.82 1408.39,609.82 1408.39,609.82 1408.14,627.93 1408.14,627.93 Z M 1564.25,1589.00 C 1564.25,1589.00 1844.00,1589.50 1844.00,1589.50 1844.00,1589.50 1844.00,1124.66 1844.00,1124.66 1844.00,1124.66 1859.50,1124.75 1859.50,1124.75 1859.50,1124.75 1860.00,1607.41 1860.00,1607.00 1860.00,1606.82 1563.67,1606.45 1563.67,1606.45 1563.67,1606.45 1564.25,1589.00 1564.25,1589.00 Z M 1346.25,1606.00 C 1346.25,1606.00 1054.50,1606.00 1054.50,1606.00 1054.50,1606.00 1055.00,1588.00 1055.00,1588.00 1055.00,1588.00 1346.75,1589.50 1346.75,1589.50 1346.75,1589.50 1346.25,1606.00 1346.25,1606.00 Z M 142.25,1025.00 C 142.25,1025.00 142.00,609.67 142.00,609.67 142.00,609.67 492.94,610.14 492.94,610.14 492.94,610.14 493.03,627.49 493.03,627.49 493.03,627.49 157.00,626.00 157.00,626.00 157.00,626.00 158.24,1024.67 158.24,1024.67 158.24,1024.67 142.25,1025.00 142.25,1025.00 Z M 158.55,1124.14 C 158.55,1124.14 160.00,1590.00 160.00,1590.00 160.00,1590.00 435.85,1589.65 435.85,1589.65 435.85,1589.65 436.00,1606.50 436.00,1606.50 436.00,1606.50 141.04,1607.33 141.33,1607.33 142.15,1607.33 142.50,1124.25 142.50,1124.25 142.50,1124.25 158.55,1124.14 158.55,1124.14 Z" class="exterior-walls" /><ns0:path d="M 946.58,629.83 C 957.43,696.37 1000.14,714.36 1052.00,717.00M 1053.75,1592.50 C 1060.75,1555.50 1021.25,1517.75 974.25,1519.75" class="door-arcs" /><ns0:path d="M 1057.25,626.00 C 1057.25,626.00 983.00,690.00 983.00,690.00M 944.75,1594.25 C 944.75,1594.25 1019.00,1537.25 1019.00,1537.25" class="doors" /></g></svg>
\ No newline at end of file
diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.js
index fcec0ef1..c45f0049 100644
--- a/src/hi/static/js/antinode.js
+++ b/src/hi/static/js/antinode.js
@@ -1,7 +1,7 @@
// Anti-Node - Less Javascript is Better
// Server-side rendering for asynchronous interactions
//
-// Copyright 2020-2025 by POMDP, Inc. - All rights reserved
+// Copyright 2020-2026 by POMDP, LLC - All rights reserved
// ====================
// OVERVIEW
@@ -287,7 +287,19 @@
});
},
- addAfterAsyncRenderFunction: addAfterAsyncRenderFunction
+ addAfterAsyncRenderFunction: addAfterAsyncRenderFunction,
+
+ // Display modal content that was rendered server-side.
+ // Creates a modal wrapper, appends the content, and shows it.
+ //
+ // Usage:
+ // AN.displayModal('<div class="modal-dialog">...</div>');
+ //
+ displayModal: function( modalContent ) {
+ let targetObj = getNewModal();
+ targetObj.append( modalContent );
+ showModal( targetObj );
+ }
}
window.AN = AN;
@@ -346,7 +358,7 @@ function asyncSubmitHandlerHelper( $form ) {
if (( $($form).attr('method') )
&& ( $($form).attr('method').toUpperCase() == 'GET' )) {
- let formData = $form.serializeArray();
+ formData = $form.serializeArray();
if ( lastButtonName ) {
formData.push( { name: lastButtonName, value: lastButtonValue } );
}
@@ -547,6 +559,7 @@ function asyncUpdateData( $target, $mode, data, xhr ) {
$target.html(data);
}
handleNewContentAdded( $target );
+ afterAsyncRender();
}
}
if (ct.indexOf('json') > -1) {
@@ -562,7 +575,11 @@ function asyncUpdateData( $target, $mode, data, xhr ) {
}
asyncUpdateDataFromJson( $target, $mode, json );
- }
+ }
+
+ if ( typeof handlePostAsyncUpdate === "function") {
+ handlePostAsyncUpdate();
+ }
};
//====================
@@ -693,12 +710,8 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {
console.warn('AntiNode scrollTo: Target element not found:', targetId);
}
}
-
- if ( typeof handlePostAsyncUpdate === "function") {
- handlePostAsyncUpdate();
- }
};
-
+
//====================
function handleSetAttributes( attributesMap ) {
for ( let selector in attributesMap ) {
@@ -874,7 +887,17 @@ function showModal( modalObj ) {
if ( modalHideStartMs ) {
deferredModalShowObj = modalObj;
} else {
- $(modalObj).modal("show");
+ // Check if modal content requests protection (no dismiss on backdrop click or Escape)
+ var protectedEl = $(modalObj).find('[data-modal-protected]').first();
+ var isProtected = protectedEl.length > 0 && protectedEl.data('modal-protected');
+ if (isProtected) {
+ $(modalObj).modal({
+ backdrop: 'static',
+ keyboard: false
+ });
+ } else {
+ $(modalObj).modal("show");
+ }
}
};
@@ -983,16 +1006,16 @@ function lastButtonClickHandler(event) {
$(theForm).data('lastSubmitButtonValue', this.value);
};
-function showLoadingIniterstitial() {
+function showLoadingInterstitial() {
$('#antinode-loader').show();
};
-function hideLoadingIniterstitial() {
+function hideLoadingInterstitial() {
$('#antinode-loader').hide();
};
function synchronousSubmitHandler() {
- $('#antinode-loader').show();
+ showLoadingInterstitial();
$( this ).find( 'button[type="submit"]' ).prop('disabled', true);
}
@@ -1052,11 +1075,11 @@ $.ajaxSuppressLoader = false;
$(document)
.ajaxStart(function () {
if ( ! $.ajaxSuppressLoader ) {
- $('#antinode-loader').show();
+ showLoadingInterstitial();
}
})
.ajaxStop(function () {
- $('#antinode-loader').hide();
+ hideLoadingInterstitial();
});
-})();
\ No newline at end of file
+})();
diff --git a/src/hi/static/js/edit-dragdrop.js b/src/hi/static/js/edit-dragdrop.js
index 2ac29f56..c8a14425 100644
--- a/src/hi/static/js/edit-dragdrop.js
+++ b/src/hi/static/js/edit-dragdrop.js
@@ -6,8 +6,6 @@
// Externally accessible functions here.
};
- window.Hi.edit.path = HiEditDragDrop;
-
/*
DRAG AND DROP EDITING
diff --git a/src/hi/static/js/edit.js b/src/hi/static/js/edit.js
deleted file mode 100644
index 8e2ca95f..00000000
--- a/src/hi/static/js/edit.js
+++ /dev/null
@@ -1,41 +0,0 @@
-(function() {
-
- window.Hi = window.Hi || {};
-
- const HiEdit = {
- /*
- Used for various editing sub-modules to track which one made the last
- selection so others can clear their selections.
- */
- SELECTION_MADE_EVENT_NAME: 'event.selectionMade'
-
- };
-
- window.Hi.edit = HiEdit;
-
- /*
- We use this event bus to allow the editing submodules to coordinate.
- We want submodules to be independent, but since they need to share
- the same event space, we need some means of comunicating in a
- decoupled way.
- */
- const eventBus = {
- events: {},
-
- subscribe: function( eventName, callback ) {
- if (!this.events[eventName]) {
- this.events[eventName] = [];
- }
- this.events[eventName].push(callback);
- },
-
- emit: function( eventName, data ) {
- if (this.events[eventName]) {
- this.events[eventName].forEach( callback => callback(data) );
- }
- }
- };
-
- window.Hi.edit.eventBus = eventBus;
-
-})();
diff --git a/src/hi/static/js/svg-bg-edit.js b/src/hi/static/js/svg-bg-edit.js
new file mode 100644
index 00000000..5ba67b0b
--- /dev/null
+++ b/src/hi/static/js/svg-bg-edit.js
@@ -0,0 +1,642 @@
+/* Location SVG Editor Javascript */
+
+(function() {
+
+ window.Hi = window.Hi || {};
+ window.Hi.SvgEdit = window.Hi.SvgEdit || {};
+ window.Hi.SvgEdit.snapGridPixels = 5;
+
+ const SVG_NS = 'http://www.w3.org/2000/svg';
+
+ /* Element IDs (must match DIVID values in constants.py and templates) */
+ const PALETTE_CONTAINER_ID = 'hi-svg-edit-palette';
+ const CANVAS_SVG_ID = 'hi-svg-edit-svg';
+ const CANVAS_AREA_ID = 'hi-svg-edit-canvas';
+ const CANVAS_CONTAINER_ID = 'hi-svg-edit-canvas-container';
+ const CONFORMANCE_WARNING_ID = 'hi-svg-edit-conformance-warning';
+
+ /* SVG element attributes and classes (shared with SVG templates and saved files) */
+ const BG_ELEMENT_CLASS = 'hi-bg-element';
+ const BG_HIT_AREA_CLASS = 'hi-bg-hit-area';
+ const BG_EDITOR_ATTR = 'data-hi-editor';
+ const BG_TYPE_ATTR = 'data-bg-type';
+ const BG_EDIT_TYPE_ATTR = 'data-bg-edit-type';
+ const BG_LAYER_ATTR = 'data-bg-layer';
+
+ /* Palette template attributes (read from <defs>) */
+ const BG_LABEL_ATTR = 'data-bg-label';
+ const BG_CATEGORY_ATTR = 'data-bg-category';
+ const BG_TEMPLATE_ID_ATTR = 'data-bg-template-id';
+
+ /* Palette CSS classes (JS-generated DOM + location-svg-edit.css) */
+ const PALETTE_CATEGORY_CLASS = 'hi-palette-category';
+ const PALETTE_CATEGORY_LABEL_CLASS = 'hi-palette-category-label';
+ const PALETTE_ITEMS_CLASS = 'hi-palette-items';
+ const PALETTE_ITEM_CLASS = 'hi-palette-item';
+ const PALETTE_LABEL_CLASS = 'hi-palette-label';
+ const PALETTE_SWATCH_CLASS = 'hi-palette-swatch';
+
+ const CATEGORY_ORDER = ['structural', 'features', 'exterior'];
+ const CATEGORY_LABELS = {
+ structural: 'Structural',
+ features: 'Features',
+ exterior: 'Exterior',
+ };
+
+ /* Viewbox dimensions for palette swatch mini-SVGs by edit type. */
+ const SWATCH_VIEWBOX = {
+ closed: { padding: 4 },
+ open: { height: 20, padding: 4 },
+ icon: { padding: 4 },
+ };
+
+ const SWATCH_WIDTH = 44;
+ const SWATCH_HEIGHT = 32;
+
+ function buildPalette() {
+ var canvasSvg = document.getElementById(CANVAS_SVG_ID);
+ if (!canvasSvg) {
+ return;
+ }
+
+ /* Find the palette defs — the <defs> that contains <g> children
+ with data-bg-edit-type attributes (as opposed to the fill pattern defs). */
+ var defsElement = null;
+ var allDefs = canvasSvg.querySelectorAll('defs');
+ for (var di = 0; di < allDefs.length; di++) {
+ if (allDefs[di].querySelector('g[' + BG_EDIT_TYPE_ATTR + ']')) {
+ defsElement = allDefs[di];
+ break;
+ }
+ }
+ if (!defsElement) {
+ return;
+ }
+
+ var templates = [];
+ $(defsElement).children('g').each(function() {
+ var editType = $(this).attr(BG_EDIT_TYPE_ATTR);
+ if (!editType) {
+ return;
+ }
+ templates.push({
+ id: $(this).attr('id'),
+ editType: editType,
+ label: $(this).attr(BG_LABEL_ATTR) || '',
+ category: $(this).attr(BG_CATEGORY_ATTR) || '',
+ layer: parseInt($(this).attr(BG_LAYER_ATTR) || '0', 10),
+ element: this,
+ });
+ });
+
+ /* Group by category. */
+ var categories = {};
+ for (var i = 0; i < templates.length; i++) {
+ var tmpl = templates[i];
+ if (!categories[tmpl.category]) {
+ categories[tmpl.category] = [];
+ }
+ categories[tmpl.category].push(tmpl);
+ }
+
+ var container = document.getElementById(PALETTE_CONTAINER_ID);
+ if (!container) {
+ return;
+ }
+
+ for (var ci = 0; ci < CATEGORY_ORDER.length; ci++) {
+ var catKey = CATEGORY_ORDER[ci];
+ var catTemplates = categories[catKey];
+ if (!catTemplates || catTemplates.length === 0) {
+ continue;
+ }
+
+ var catDiv = document.createElement('div');
+ catDiv.className = PALETTE_CATEGORY_CLASS;
+
+ var catLabel = document.createElement('span');
+ catLabel.className = PALETTE_CATEGORY_LABEL_CLASS;
+ catLabel.textContent = CATEGORY_LABELS[catKey] || catKey;
+ catDiv.appendChild(catLabel);
+
+ var itemsDiv = document.createElement('div');
+ itemsDiv.className = PALETTE_ITEMS_CLASS;
+
+ for (var ti = 0; ti < catTemplates.length; ti++) {
+ var tmpl = catTemplates[ti];
+ var itemDiv = createPaletteItem(tmpl);
+ itemsDiv.appendChild(itemDiv);
+ }
+
+ catDiv.appendChild(itemsDiv);
+ container.appendChild(catDiv);
+ }
+ }
+
+ function createPaletteItem(tmpl) {
+ var itemDiv = document.createElement('div');
+ itemDiv.className = PALETTE_ITEM_CLASS;
+ itemDiv.setAttribute(BG_TEMPLATE_ID_ATTR, tmpl.id);
+ itemDiv.setAttribute('draggable', 'true');
+ itemDiv.setAttribute('title', tmpl.label);
+
+ itemDiv.addEventListener('dragstart', function(event) {
+ event.dataTransfer.setData('text/plain', tmpl.id);
+ event.dataTransfer.effectAllowed = 'copy';
+ });
+
+ var swatchSvg = createSwatchSvg(tmpl);
+ itemDiv.appendChild(swatchSvg);
+
+ var label = document.createElement('span');
+ label.className = PALETTE_LABEL_CLASS;
+ label.textContent = tmpl.label;
+ itemDiv.appendChild(label);
+
+ return itemDiv;
+ }
+
+ function createSwatchSvg(tmpl) {
+ var svg = document.createElementNS(SVG_NS, 'svg');
+ svg.setAttribute('class', PALETTE_SWATCH_CLASS);
+ svg.setAttribute('width', SWATCH_WIDTH);
+ svg.setAttribute('height', SWATCH_HEIGHT);
+
+ /* Clone the template content into the swatch. */
+ var paths = tmpl.element.querySelectorAll('path');
+ for (var i = 0; i < paths.length; i++) {
+ var clone = paths[i].cloneNode(true);
+ svg.appendChild(clone);
+ }
+
+ /* Compute viewBox from template geometry. */
+ var viewBox = computeSwatchViewBox(tmpl);
+ svg.setAttribute('viewBox', viewBox);
+
+ return svg;
+ }
+
+ function computeSwatchViewBox(tmpl) {
+ var pad = SWATCH_VIEWBOX[tmpl.editType]
+ ? SWATCH_VIEWBOX[tmpl.editType].padding
+ : 4;
+
+ /* Parse all path d attributes to find bounding box. */
+ var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ var paths = tmpl.element.querySelectorAll('path');
+ for (var i = 0; i < paths.length; i++) {
+ var coords = paths[i].getAttribute('d').match(/[\d.]+/g);
+ if (!coords) {
+ continue;
+ }
+ for (var j = 0; j < coords.length; j += 2) {
+ var x = parseFloat(coords[j]);
+ var y = parseFloat(coords[j + 1]);
+ if (!isNaN(x) && !isNaN(y)) {
+ if (x < minX) { minX = x; }
+ if (y < minY) { minY = y; }
+ if (x > maxX) { maxX = x; }
+ if (y > maxY) { maxY = y; }
+ }
+ }
+ }
+
+ if (minX === Infinity) {
+ return '0 0 100 100';
+ }
+
+ /* For open paths (lines), ensure minimum height for visibility. */
+ var width = maxX - minX;
+ var height = maxY - minY;
+ if (tmpl.editType === 'open' && height < 20) {
+ var midY = (minY + maxY) / 2;
+ minY = midY - 10;
+ height = 20;
+ }
+
+ return (minX - pad) + ' ' + (minY - pad) + ' ' + (width + pad * 2) + ' ' + (height + pad * 2);
+ }
+
+ /* ==================== */
+ /* Element Delete */
+ /* ==================== */
+
+ Hi.SvgEdit.onElementDeleted = function() {
+ saveDraft();
+ };
+
+ /* ==================== */
+ /* Undo */
+ /* ==================== */
+
+ var UNDO_STACK_MAX = 20;
+ var gUndoStack = [];
+ var gLastSavedSnapshot = null;
+
+ function getCleanSnapshot() {
+ var canvasSvg = document.getElementById( CANVAS_SVG_ID );
+ if ( ! canvasSvg ) { return null; }
+
+ var editorGroup = canvasSvg.querySelector( 'g[' + BG_EDITOR_ATTR + ']' );
+ if ( ! editorGroup ) { return null; }
+
+ var clone = editorGroup.cloneNode( true );
+ cleanCloneForSave( clone );
+ return clone.outerHTML;
+ }
+
+ function pushUndoSnapshot() {
+ var snapshot = gLastSavedSnapshot;
+ if ( ! snapshot ) {
+ snapshot = getCleanSnapshot();
+ }
+ if ( ! snapshot ) { return; }
+
+ if ( gUndoStack.length >= UNDO_STACK_MAX ) {
+ gUndoStack.shift();
+ }
+ gUndoStack.push( snapshot );
+ }
+
+ Hi.SvgEdit.undo = function() {
+ if ( gUndoStack.length === 0 ) { return false; }
+
+ Hi.SvgIconCore.clearSelection();
+ Hi.SvgPathCore.clearSelection();
+
+ var snapshot = gUndoStack.pop();
+ var canvasSvg = document.getElementById( CANVAS_SVG_ID );
+ if ( ! canvasSvg ) { return false; }
+
+ var editorGroup = canvasSvg.querySelector( 'g[' + BG_EDITOR_ATTR + ']' );
+ if ( ! editorGroup ) { return false; }
+
+ editorGroup.outerHTML = snapshot;
+ gLastSavedSnapshot = snapshot;
+
+ /* Persist the restored state to the draft file. */
+ if ( Hi.SvgEdit.saveUrl ) {
+ $.post( Hi.SvgEdit.saveUrl, {
+ svg_content: snapshot,
+ csrfmiddlewaretoken: Hi.SvgEdit.csrfToken,
+ });
+ }
+ return true;
+ };
+
+ Hi.SvgEdit.hasUndo = function() {
+ return gUndoStack.length > 0;
+ };
+
+ /* ==================== */
+ /* Draft Save */
+ /* ==================== */
+
+ function cleanCloneForSave( clone ) {
+ /* Remove proxy path editing containers. */
+ var proxies = clone.querySelectorAll( '#' + Hi.SvgPathCore.PROXY_PATH_CONTAINER_ID );
+ for ( var i = 0; i < proxies.length; i++ ) {
+ proxies[i].parentNode.removeChild( proxies[i] );
+ }
+
+ /* Remove editing highlight classes. */
+ var highlighted = clone.querySelectorAll( '.' + Hi.HIGHLIGHTED_CLASS );
+ for ( var i = 0; i < highlighted.length; i++ ) {
+ highlighted[i].classList.remove( Hi.HIGHLIGHTED_CLASS );
+ }
+
+ /* Remove action-state attributes. */
+ var withActionState = clone.querySelectorAll( '[action-state]' );
+ for ( var i = 0; i < withActionState.length; i++ ) {
+ withActionState[i].removeAttribute( 'action-state' );
+ }
+
+ /* Remove any display:none from hidden path groups (during proxy editing). */
+ var hidden = clone.querySelectorAll( '[style*="display"]' );
+ for ( var i = 0; i < hidden.length; i++ ) {
+ hidden[i].style.removeProperty( 'display' );
+ if ( ! hidden[i].getAttribute( 'style' ) ) {
+ hidden[i].removeAttribute( 'style' );
+ }
+ }
+ }
+
+ function saveDraft() {
+ var canvasSvg = document.getElementById( CANVAS_SVG_ID );
+ if ( ! canvasSvg ) { return; }
+
+ var editorGroup = canvasSvg.querySelector( 'g[' + BG_EDITOR_ATTR + ']' );
+ if ( ! editorGroup ) { return; }
+
+ pushUndoSnapshot();
+
+ /* Clone and clean: serialize a pristine copy without editing artifacts. */
+ var clone = editorGroup.cloneNode( true );
+ cleanCloneForSave( clone );
+ var svgContent = clone.outerHTML;
+
+ gLastSavedSnapshot = svgContent;
+
+ if ( ! Hi.SvgEdit.saveUrl ) { return; }
+
+ $.post( Hi.SvgEdit.saveUrl, {
+ svg_content: svgContent,
+ csrfmiddlewaretoken: Hi.SvgEdit.csrfToken,
+ });
+ }
+
+ /* ==================== */
+ /* Palette Drop */
+ /* ==================== */
+
+ function initPaletteDrop() {
+ var $canvas = $( '#' + CANVAS_AREA_ID );
+
+ $canvas.on( 'dragover', function( event ) {
+ event.preventDefault();
+ event.originalEvent.dataTransfer.dropEffect = 'copy';
+ });
+
+ $canvas.on( 'drop', function( event ) {
+ event.preventDefault();
+ var templateId = event.originalEvent.dataTransfer.getData( 'text/plain' );
+ if ( ! templateId ) { return; }
+
+ var templateElement = document.getElementById( templateId );
+ if ( ! templateElement ) { return; }
+
+ var canvasSvg = document.getElementById( CANVAS_SVG_ID );
+ if ( ! canvasSvg ) { return; }
+
+ /* Convert drop screen coordinates to SVG coordinates. */
+ var svgPoint = Hi.svgUtils.toSvgPoint(
+ $( canvasSvg ), event.originalEvent.clientX, event.originalEvent.clientY
+ );
+
+ var editType = $( templateElement ).attr( BG_EDIT_TYPE_ATTR );
+ var bgType = templateId.replace( /^hi-/, '' );
+ var layer = parseInt( $( templateElement ).attr( BG_LAYER_ATTR ) || '0', 10 );
+
+ var newElement = createElementFromTemplate( templateElement, bgType, editType, layer, svgPoint );
+ if ( newElement ) {
+ insertAtLayer( canvasSvg, newElement, layer );
+ saveDraft();
+ }
+ });
+ }
+
+ function generateBgId() {
+ var hex = Math.random().toString(16).substring(2, 10);
+ return 'bg-' + hex;
+ }
+
+ function createElementFromTemplate( templateElement, bgType, editType, layer, svgPoint ) {
+ var SVG_NS = 'http://www.w3.org/2000/svg';
+ var group = document.createElementNS( SVG_NS, 'g' );
+ group.setAttribute( 'id', generateBgId() );
+ group.setAttribute( 'class', BG_ELEMENT_CLASS );
+ group.setAttribute( BG_TYPE_ATTR, bgType );
+ group.setAttribute( BG_EDIT_TYPE_ATTR, editType );
+ group.setAttribute( BG_LAYER_ATTR, layer );
+
+ /* Clone template content (paths, rects) into the new group. */
+ var children = templateElement.childNodes;
+ for ( var i = 0; i < children.length; i++ ) {
+ if ( children[i].nodeType === 1 ) {
+ group.appendChild( children[i].cloneNode( true ) );
+ }
+ }
+
+ if ( editType === 'icon' ) {
+ /* Icon: position via transform. */
+ group.setAttribute( 'transform',
+ 'scale(1 1) translate(' + svgPoint.x + ',' + svgPoint.y + ') rotate(0, 0, 0)' );
+
+ /* Add hit-area rect from bounding box of template content. */
+ var bbox = getTemplateBBox( templateElement );
+ var hitRect = document.createElementNS( SVG_NS, 'rect' );
+ hitRect.setAttribute( 'x', bbox.x );
+ hitRect.setAttribute( 'y', bbox.y );
+ hitRect.setAttribute( 'width', bbox.width );
+ hitRect.setAttribute( 'height', bbox.height );
+ hitRect.setAttribute( 'fill', 'transparent' );
+ hitRect.setAttribute( 'class', BG_HIT_AREA_CLASS );
+ group.appendChild( hitRect );
+
+ } else if ( editType === 'open' ) {
+ /* Open path: offset the template path to the drop point. */
+ var path = group.querySelector( 'path' );
+ if ( path ) {
+ var offsetD = offsetPathData( path.getAttribute( 'd' ), svgPoint.x, svgPoint.y );
+ path.setAttribute( 'd', offsetD );
+
+ /* Add hit-area path with same data. */
+ var hitPath = document.createElementNS( SVG_NS, 'path' );
+ hitPath.setAttribute( 'd', offsetD );
+ hitPath.setAttribute( 'class', BG_HIT_AREA_CLASS );
+ group.appendChild( hitPath );
+ }
+
+ } else if ( editType === 'closed' ) {
+ /* Closed path: offset the template path to the drop point. */
+ var path = group.querySelector( 'path' );
+ if ( path ) {
+ var offsetD = offsetPathData( path.getAttribute( 'd' ), svgPoint.x, svgPoint.y );
+ path.setAttribute( 'd', offsetD );
+ }
+ }
+
+ return group;
+ }
+
+ function offsetPathData( d, offsetX, offsetY ) {
+ /* Offset all coordinates in an M/L/Z path by the given amounts. */
+ return d.replace( /([\d.]+),([\d.]+)/g, function( match, x, y ) {
+ var newX = parseFloat( x ) + offsetX;
+ var newY = parseFloat( y ) + offsetY;
+ return newX.toFixed(1) + ',' + newY.toFixed(1);
+ });
+ }
+
+ function getTemplateBBox( templateElement ) {
+ /* Parse path coordinates to compute bounding box. */
+ var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ var paths = templateElement.querySelectorAll( 'path' );
+ for ( var i = 0; i < paths.length; i++ ) {
+ var coords = paths[i].getAttribute( 'd' ).match( /[\d.]+/g );
+ if ( ! coords ) { continue; }
+ for ( var j = 0; j < coords.length; j += 2 ) {
+ var x = parseFloat( coords[j] );
+ var y = parseFloat( coords[j + 1] );
+ if ( ! isNaN( x ) && ! isNaN( y ) ) {
+ if ( x < minX ) { minX = x; }
+ if ( y < minY ) { minY = y; }
+ if ( x > maxX ) { maxX = x; }
+ if ( y > maxY ) { maxY = y; }
+ }
+ }
+ }
+ if ( minX === Infinity ) { return { x: 0, y: 0, width: 50, height: 50 }; }
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
+ }
+
+ function insertAtLayer( canvasSvg, newElement, layer ) {
+ /* Insert the element at the correct position based on layer ordering.
+ Elements with higher layer numbers come later in the DOM (render on top). */
+ var editorGroup = canvasSvg.querySelector( 'g[' + BG_EDITOR_ATTR + ']' );
+ if ( ! editorGroup ) { return; }
+
+ var elements = editorGroup.querySelectorAll( 'g.' + BG_ELEMENT_CLASS );
+ var insertBefore = null;
+ for ( var i = 0; i < elements.length; i++ ) {
+ var elemLayer = parseInt( elements[i].getAttribute( BG_LAYER_ATTR ) || '0', 10 );
+ if ( elemLayer > layer ) {
+ insertBefore = elements[i];
+ break;
+ }
+ }
+
+ if ( insertBefore ) {
+ editorGroup.insertBefore( newElement, insertBefore );
+ } else {
+ editorGroup.appendChild( newElement );
+ }
+ }
+
+ /* ==================== */
+ /* Core Initialization */
+ /* ==================== */
+
+ function initCores() {
+ Hi.SvgPanZoomCore.init({
+ baseSvgSelector: '#' + CANVAS_SVG_ID,
+ areaSelector: '#' + CANVAS_AREA_ID,
+ onSave: null,
+ shouldSave: function() { return false; },
+ });
+
+ Hi.SvgIconCore.init({
+ identifyElement: function( event ) {
+ var target = event.target || event.srcElement;
+ var group = $( target ).closest( 'g.' + BG_ELEMENT_CLASS );
+ if ( group.length > 0 && group.attr( BG_EDIT_TYPE_ATTR ) === 'icon' ) {
+ return group[0];
+ }
+ return null;
+ },
+ onSelect: function( element ) {
+ Hi.SvgPathCore.clearSelection();
+ },
+ onDeselect: function() {
+ /* Future: clear element info in editor UI */
+ },
+ onSave: function( element, positionData ) {
+ saveDraft();
+ },
+ baseSvgSelector: '#' + CANVAS_SVG_ID,
+ areaSelector: '#' + CANVAS_AREA_ID,
+ highlightClass: Hi.HIGHLIGHTED_CLASS,
+ });
+
+ Hi.SvgPathCore.init({
+ identifyElement: function( event ) {
+ var target = event.target || event.srcElement;
+ var group = $( target ).closest( 'g.' + BG_ELEMENT_CLASS );
+ if ( group.length > 0 ) {
+ var editType = group.attr( BG_EDIT_TYPE_ATTR );
+ if ( editType === 'open' || editType === 'closed' ) {
+ return group[0];
+ }
+ }
+ return null;
+ },
+ onSelect: function( element ) {
+ Hi.SvgIconCore.clearSelection();
+ },
+ onDeselect: function() {
+ saveDraft();
+ },
+ onSave: function( element, svgPathString ) {
+ /* Update the hidden path element's d attribute so
+ saveDraft() serializes the current geometry. */
+ $( element ).find( 'path' ).not( '.hi-bg-hit-area' ).attr( 'd', svgPathString );
+ $( element ).find( 'path.hi-bg-hit-area' ).attr( 'd', svgPathString );
+ saveDraft();
+ },
+ allowDeleteAll: true,
+ onDeleteAll: function() {
+ Hi.SvgEdit.onElementDeleted();
+ },
+ baseSvgSelector: '#' + CANVAS_SVG_ID,
+ highlightClass: Hi.HIGHLIGHTED_CLASS,
+ });
+ }
+
+ /* ==================== */
+ /* Conformance Check */
+ /* ==================== */
+
+ function checkConformance() {
+ var canvasSvg = document.getElementById( CANVAS_SVG_ID );
+ if ( ! canvasSvg ) { return; }
+
+ var baseGroup = canvasSvg.querySelector( Hi.LOCATION_VIEW_BASE_SELECTOR );
+ if ( ! baseGroup ) { return; }
+
+ var editorGroup = baseGroup.querySelector( 'g[' + BG_EDITOR_ATTR + ']' );
+ if ( ! editorGroup ) {
+ /* Wrap existing content in an editor group so palette items can be added. */
+ editorGroup = document.createElementNS( 'http://www.w3.org/2000/svg', 'g' );
+ editorGroup.setAttribute( BG_EDITOR_ATTR, '1' );
+ while ( baseGroup.firstChild ) {
+ editorGroup.appendChild( baseGroup.firstChild );
+ }
+ baseGroup.appendChild( editorGroup );
+
+ showConformanceWarning();
+ return;
+ }
+
+ /* Count direct child elements of the editor group (excluding defs). */
+ var children = editorGroup.children;
+ var totalElements = 0;
+ var editableElements = 0;
+ for ( var i = 0; i < children.length; i++ ) {
+ var child = children[i];
+ if ( child.tagName === 'defs' ) { continue; }
+ totalElements++;
+ if ( child.classList && child.classList.contains( BG_ELEMENT_CLASS )
+ && child.getAttribute( BG_EDIT_TYPE_ATTR ) ) {
+ editableElements++;
+ }
+ }
+
+ if ( totalElements > 0 && editableElements < totalElements ) {
+ showConformanceWarning();
+ }
+ }
+
+ function showConformanceWarning() {
+ $( '#' + CONFORMANCE_WARNING_ID ).show();
+ }
+
+ function refreshAfterAsyncRender() {
+ Hi.SvgPanZoomCore.refresh();
+ }
+
+ $(document).ready(function() {
+ buildPalette();
+ initPaletteDrop();
+ initCores();
+ checkConformance();
+ AN.addAfterAsyncRenderFunction( refreshAfterAsyncRender );
+
+ /* Seed undo cache so the first edit has a valid pre-edit state. */
+ gLastSavedSnapshot = getCleanSnapshot();
+
+ $( '#hi-svg-edit-snap-grid' ).on( 'change input', function() {
+ Hi.SvgEdit.snapGridPixels = parseInt( $( this ).val(), 10 ) || 0;
+ });
+ });
+
+})();
diff --git a/src/hi/static/js/svg-bg-event-listeners.js b/src/hi/static/js/svg-bg-event-listeners.js
new file mode 100644
index 00000000..8ef46eab
--- /dev/null
+++ b/src/hi/static/js/svg-bg-event-listeners.js
@@ -0,0 +1,434 @@
+/*
+ SVG Background Editor Event Listeners
+
+ Normalizes browser pointer/mouse/wheel/keyboard events and dispatches
+ them to the background editor's core modules. Modeled on
+ svg-entity-event-listeners.js but routes to pan-zoom-core, icon-core,
+ and path-core instead of entity modules.
+
+ Dispatch priority:
+ 1. Icon core (if an icon is selected or clicked)
+ 2. Path core (if a path is selected or clicked)
+ 3. Pan/zoom core (fallback — pan/zoom the whole canvas)
+*/
+
+(function() {
+
+ window.Hi = window.Hi || {};
+
+ const CANVAS_AREA_SELECTOR = '#hi-svg-edit-canvas';
+
+ const LAST_MOVE_THROTTLE_THRESHOLD_MS = 10;
+ const POINTER_MOVE_THRESHOLD_PIXELS = 2;
+ const POTENTIAL_CLICK_TIME_DELTA_THRESHOLD_MS = 150;
+ const POTENTIAL_CLICK_POSITION_DELTA_THRESHOLD = 5;
+ const POTENTIAL_CLICK_DELAY_MS = 50;
+
+ const activePointers = new Map();
+ const gLastMoveEventTimes = new Map();
+ let gCurrentSingleEvent = null;
+ let gCurrentDoubleEvent = null;
+ let gPotentialClickState = null;
+
+ /* ==================== */
+ /* Event Classes */
+ /* ==================== */
+
+ class SinglePointerEvent {
+ constructor( startEvent ) {
+ this.start = {
+ event: startEvent,
+ x: startEvent.clientX,
+ y: startEvent.clientY,
+ };
+ this.previous = { ...this.start };
+ this.last = { ...this.start };
+ }
+ get deltaXStart() { return this.last.x - this.start.x; }
+ get deltaXPrevious() { return this.last.x - this.previous.x; }
+ get deltaYStart() { return this.last.y - this.start.y; }
+ get deltaYPrevious() { return this.last.y - this.previous.y; }
+ update( newEvent ) {
+ this.previous = { ...this.last };
+ this.last.event = newEvent;
+ this.last.x = newEvent.clientX;
+ this.last.y = newEvent.clientY;
+ }
+ }
+
+ class DoublePointerEvent {
+ constructor( startEvent, pointersMap ) {
+ var points = this.sortedPointsFromPointersMap( pointersMap );
+ this.start = {
+ event: startEvent,
+ points: points,
+ distance: this.getDistance( points[1], points[0] ),
+ angle: this.getAngle( points[1], points[0] ),
+ };
+ this.previous = { ...this.start };
+ this.last = { ...this.start };
+ }
+ get deltaDistanceStart() { return this.last.distance - this.start.distance; }
+ get deltaDistancePrevious() { return this.last.distance - this.previous.distance; }
+ get deltaAngleStart() { return this.last.angle - this.start.angle; }
+ get deltaAnglePrevious() { return this.last.angle - this.previous.angle; }
+ sortedPointsFromPointersMap( pointersMap ) {
+ return Array.from( pointersMap.entries() )
+ .sort( function( a, b ) { return a[0] - b[0]; } )
+ .map( function( entry ) { return entry[1]; } );
+ }
+ getDistance( p1, p2 ) {
+ var dx = p1.x - p2.x;
+ var dy = p1.y - p2.y;
+ return Math.sqrt( dx * dx + dy * dy );
+ }
+ getAngle( p1, p2 ) {
+ return Math.atan2( p2.y - p1.y, p2.x - p1.x ) * ( 180 / Math.PI );
+ }
+ update( newEvent, pointersMap ) {
+ var points = this.sortedPointsFromPointersMap( pointersMap );
+ this.previous = { ...this.last };
+ this.last.event = newEvent;
+ this.last.points = points;
+ this.last.distance = this.getDistance( points[1], points[0] );
+ this.last.angle = this.getAngle( points[1], points[0] );
+ }
+ }
+
+ /* ==================== */
+ /* Event Filtering */
+ /* ==================== */
+
+ function shouldIgnoreEvent( event ) {
+ if ( event.pointerType === 'touch' || event.pointerType === 'pen' ) {
+ return false;
+ } else if ( event.pointerType === 'mouse' ) {
+ return event.buttons != 1;
+ }
+ return false;
+ }
+
+ /* ==================== */
+ /* Synthetic Click */
+ /* ==================== */
+
+ function startPotentialClickTracking( event ) {
+ gPotentialClickState = {
+ startTimeMs: performance.now(),
+ startPosition: { x: event.clientX, y: event.clientY },
+ pointerId: event.pointerId,
+ };
+ }
+
+ function checkAndHandlePotentialClick( event, initialSize, currentSize ) {
+ if ( ! gPotentialClickState
+ || event.pointerId !== gPotentialClickState.pointerId
+ || initialSize !== 1
+ || currentSize !== 0 ) {
+ return;
+ }
+
+ var timeDeltaMs = performance.now() - gPotentialClickState.startTimeMs;
+ var positionDeltaX = Math.abs( event.clientX - gPotentialClickState.startPosition.x );
+ var positionDeltaY = Math.abs( event.clientY - gPotentialClickState.startPosition.y );
+ var positionDeltaMax = Math.max( positionDeltaX, positionDeltaY );
+
+ if ( timeDeltaMs < POTENTIAL_CLICK_TIME_DELTA_THRESHOLD_MS
+ && positionDeltaMax < POTENTIAL_CLICK_POSITION_DELTA_THRESHOLD ) {
+
+ gPotentialClickState.waitingForClick = true;
+
+ setTimeout( function() {
+ if ( gPotentialClickState && gPotentialClickState.waitingForClick ) {
+ var clickEvent = new MouseEvent( 'click', {
+ bubbles: true,
+ cancelable: true,
+ clientX: event.clientX,
+ clientY: event.clientY,
+ button: event.button,
+ });
+ event.target.dispatchEvent( clickEvent );
+ gPotentialClickState = null;
+ }
+ }, POTENTIAL_CLICK_DELAY_MS );
+ } else {
+ gPotentialClickState = null;
+ }
+ }
+
+ /* ==================== */
+ /* Pointer Handlers */
+ /* ==================== */
+
+ function handlePointerDownEvent( event ) {
+ if ( shouldIgnoreEvent( event ) ) { return; }
+
+ var initialSize = activePointers.size;
+ activePointers.set( event.pointerId, { x: event.clientX, y: event.clientY } );
+ var currentSize = activePointers.size;
+
+ if ( currentSize === 1 ) {
+ startPotentialClickTracking( event );
+ }
+
+ if ( initialSize === 0 && currentSize === 1 ) {
+ gCurrentSingleEvent = new SinglePointerEvent( event );
+ dispatchSinglePointerEventStart( event, gCurrentSingleEvent );
+
+ } else if ( initialSize === 1 && currentSize === 2 ) {
+ dispatchSinglePointerEventEnd( null, gCurrentSingleEvent );
+ gCurrentSingleEvent = null;
+ gCurrentDoubleEvent = new DoublePointerEvent( event, activePointers );
+ dispatchDoublePointerEventStart( event, gCurrentDoubleEvent );
+ }
+
+ event.target.setPointerCapture( event.pointerId );
+ dispatchLastPointerPosition( event.clientX, event.clientY );
+ }
+
+ function handlePointerMoveEvent( event ) {
+ if ( shouldIgnoreEvent( event ) ) { return; }
+
+ var lastPointer = activePointers.get( event.pointerId );
+ if ( ! lastPointer ) { return; }
+
+ var now = Date.now();
+ if ( gLastMoveEventTimes.has( event.pointerId ) ) {
+ var deltaTimeMs = now - gLastMoveEventTimes.get( event.pointerId );
+ if ( deltaTimeMs < LAST_MOVE_THROTTLE_THRESHOLD_MS ) { return; }
+ }
+ gLastMoveEventTimes.set( event.pointerId, now );
+
+ var deltaX = event.clientX - lastPointer.x;
+ var deltaY = event.clientY - lastPointer.y;
+ if ( Math.abs( deltaX ) < POINTER_MOVE_THRESHOLD_PIXELS
+ && Math.abs( deltaY ) < POINTER_MOVE_THRESHOLD_PIXELS ) {
+ return;
+ }
+
+ activePointers.set( event.pointerId, { x: event.clientX, y: event.clientY } );
+
+ if ( activePointers.size === 1 ) {
+ if ( gCurrentSingleEvent ) {
+ gCurrentSingleEvent.update( event );
+ dispatchSinglePointerEventMove( event, gCurrentSingleEvent );
+ }
+ } else if ( activePointers.size === 2 ) {
+ if ( gCurrentDoubleEvent ) {
+ gCurrentDoubleEvent.update( event, activePointers );
+ dispatchDoublePointerEventMove( event, gCurrentDoubleEvent );
+ }
+ }
+ dispatchLastPointerPosition( event.clientX, event.clientY );
+ }
+
+ function handlePointerUpEvent( event ) {
+ var initialSize = activePointers.size;
+ var lastPointer = activePointers.get( event.pointerId );
+ if ( ! lastPointer ) { return; }
+ activePointers.delete( event.pointerId );
+ gLastMoveEventTimes.delete( event.pointerId );
+ var currentSize = activePointers.size;
+
+ if ( currentSize > 1 ) {
+ gPotentialClickState = null;
+ }
+
+ checkAndHandlePotentialClick( event, initialSize, currentSize );
+
+ if ( initialSize === 1 && currentSize === 0 ) {
+ if ( gCurrentSingleEvent ) {
+ gCurrentSingleEvent.update( event );
+ dispatchSinglePointerEventEnd( event, gCurrentSingleEvent );
+ }
+ } else if ( initialSize === 2 && currentSize === 1 ) {
+ dispatchDoublePointerEventEnd( null, gCurrentDoubleEvent );
+ gCurrentDoubleEvent = null;
+ gCurrentSingleEvent = new SinglePointerEvent( event );
+ dispatchSinglePointerEventStart( event, gCurrentSingleEvent );
+ }
+
+ event.target.releasePointerCapture( event.pointerId );
+ dispatchLastPointerPosition( event.clientX, event.clientY );
+ }
+
+ function handlePointerCancelEvent( event ) {
+ handlePointerUpEvent( event );
+ }
+
+ /* ==================== */
+ /* Dispatch */
+ /* ==================== */
+
+ function dispatchLastPointerPosition( x, y ) {
+ Hi.SvgIconCore.handleLastPointerLocation( x, y );
+ Hi.SvgPanZoomCore.handleLastPointerLocation( x, y );
+ /* Future: path-core position tracking */
+ }
+
+ function dispatchSinglePointerEventStart( currentEvent, singlePointerEvent ) {
+ var handled = Hi.SvgIconCore.handleSinglePointerEventStart( singlePointerEvent );
+ if ( handled ) {
+ Hi.SvgPathCore.clearSelection();
+ }
+ if ( ! handled ) {
+ handled = Hi.SvgPathCore.handleSinglePointerEventStart( singlePointerEvent );
+ if ( handled ) {
+ Hi.SvgIconCore.clearSelection();
+ }
+ }
+ if ( ! handled ) {
+ handled = Hi.SvgPanZoomCore.handleSinglePointerEventStart( singlePointerEvent.start.event );
+ }
+ if ( handled && currentEvent ) {
+ currentEvent.stopImmediatePropagation();
+ }
+ }
+
+ function dispatchSinglePointerEventMove( currentEvent, singlePointerEvent ) {
+ var handled = Hi.SvgIconCore.handleSinglePointerEventMove( singlePointerEvent );
+ if ( ! handled ) {
+ handled = Hi.SvgPathCore.handleSinglePointerEventMove( singlePointerEvent );
+ }
+ if ( ! handled ) {
+ handled = Hi.SvgPanZoomCore.handleSinglePointerEventMove(
+ singlePointerEvent.start.event, singlePointerEvent.last.event );
+ }
+ if ( handled && currentEvent ) {
+ currentEvent.stopImmediatePropagation();
+ }
+ }
+
+ function dispatchSinglePointerEventEnd( currentEvent, singlePointerEvent ) {
+ var handled = Hi.SvgIconCore.handleSinglePointerEventEnd( singlePointerEvent );
+ if ( ! handled ) {
+ handled = Hi.SvgPathCore.handleSinglePointerEventEnd( singlePointerEvent );
+ }
+ if ( ! handled ) {
+ handled = Hi.SvgPanZoomCore.handleSinglePointerEventEnd();
+ }
+ if ( handled && currentEvent ) {
+ currentEvent.preventDefault();
+ currentEvent.stopImmediatePropagation();
+ }
+ }
+
+ function dispatchDoublePointerEventStart( currentEvent, doublePointerEvent ) {
+ var handled = Hi.SvgIconCore.handleDoublePointerEventStart( doublePointerEvent );
+ if ( handled && currentEvent ) {
+ currentEvent.stopImmediatePropagation();
+ }
+ }
+
+ function dispatchDoublePointerEventMove( currentEvent, doublePointerEvent ) {
+ var handled = Hi.SvgIconCore.handleDoublePointerEventMove( doublePointerEvent );
+ if ( handled && currentEvent ) {
+ currentEvent.stopImmediatePropagation();
+ }
+ }
+
+ function dispatchDoublePointerEventEnd( currentEvent, doublePointerEvent ) {
+ var handled = Hi.SvgIconCore.handleDoublePointerEventEnd( doublePointerEvent );
+ if ( handled && currentEvent ) {
+ currentEvent.stopImmediatePropagation();
+ }
+ }
+
+ /* ==================== */
+ /* Registration Helpers */
+ /* ==================== */
+
+ function addPointerListener( eventType, selector, handler, passive ) {
+ if ( passive === undefined ) { passive = true; }
+ $( document ).each( function() {
+ this.addEventListener( eventType, function( event ) {
+ if ( event.target.closest( selector ) ) {
+ handler( event );
+ }
+ }, { passive: passive } );
+ });
+ }
+
+ /* ==================== */
+ /* Initialize */
+ /* ==================== */
+
+ $(document).ready(function() {
+
+ addPointerListener( 'pointerdown', CANVAS_AREA_SELECTOR, handlePointerDownEvent, false );
+ addPointerListener( 'pointermove', CANVAS_AREA_SELECTOR, handlePointerMoveEvent, false );
+ addPointerListener( 'pointerup', CANVAS_AREA_SELECTOR, handlePointerUpEvent, false );
+ addPointerListener( 'pointercancel', CANVAS_AREA_SELECTOR, handlePointerCancelEvent );
+
+ $( document ).on( 'wheel', CANVAS_AREA_SELECTOR, function( event ) {
+ var handled = Hi.SvgIconCore.handleMouseWheel( event );
+ if ( ! handled ) {
+ handled = Hi.SvgPanZoomCore.handleMouseWheel( event );
+ }
+ if ( handled ) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ });
+
+ $( document ).on( 'click', CANVAS_AREA_SELECTOR, function( event ) {
+ if ( gPotentialClickState && gPotentialClickState.waitingForClick ) {
+ gPotentialClickState = null;
+ }
+ /* Pan-zoom click suppression first — a completed pan drag
+ must not be interpreted as a selection by other cores. */
+ var handled = Hi.SvgPanZoomCore.handleClick( event );
+ if ( ! handled ) {
+ handled = Hi.SvgIconCore.handleClick( event );
+ }
+ if ( ! handled ) {
+ handled = Hi.SvgPathCore.handleClick( event );
+ }
+ if ( handled ) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ });
+
+ $( document ).on( 'keydown', function( event ) {
+ if ( $( event.target ).is( 'input, textarea' ) ) { return; }
+ if ( $( event.target ).closest( '.modal' ).length > 0 ) { return; }
+
+ /* Editor-level commands — before routing to cores. */
+ var handled = false;
+
+ if ( event.key === 'z' && ( event.ctrlKey || event.metaKey ) && ! event.shiftKey ) {
+ handled = Hi.SvgEdit.undo();
+ }
+
+ var isDeleteKey = ( event.key === 'x' || event.key === 'Delete' || event.key === 'Backspace' );
+
+ if ( isDeleteKey && ! event.ctrlKey && Hi.SvgIconCore.hasSelection() ) {
+ Hi.SvgIconCore.deleteSelectedElement();
+ Hi.SvgEdit.onElementDeleted();
+ handled = true;
+
+ } else if ( event.key === 'x' && event.ctrlKey && Hi.SvgPathCore.hasSelection() ) {
+ Hi.SvgPathCore.deleteSelectedElement();
+ Hi.SvgEdit.onElementDeleted();
+ handled = true;
+ }
+
+ /* Core-level commands. */
+ if ( ! handled ) {
+ handled = Hi.SvgIconCore.handleKeyDown( event );
+ }
+ if ( ! handled ) {
+ handled = Hi.SvgPathCore.handleKeyDown( event );
+ }
+ if ( ! handled ) {
+ handled = Hi.SvgPanZoomCore.handleKeyDown( event );
+ }
+ if ( handled ) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ });
+ });
+
+})();
diff --git a/src/hi/static/js/svg-entity-edit.js b/src/hi/static/js/svg-entity-edit.js
new file mode 100644
index 00000000..313fbf79
--- /dev/null
+++ b/src/hi/static/js/svg-entity-edit.js
@@ -0,0 +1,318 @@
+/*
+ Entity SVG Edit
+
+ Thin wrapper layer that initializes the shared SVG core modules
+ (svg-icon-core, svg-path-core, svg-pan-zoom-core) with entity-specific
+ configuration: edit mode guards, API persistence, cross-module selection
+ clearing, and non-edit-mode status view fetching.
+
+ Exposes the same public API as the original entity editing modules
+ (Hi.edit.icon, Hi.edit.path, Hi.location) so that
+ svg-entity-event-listeners.js requires minimal changes.
+*/
+
+(function() {
+
+ window.Hi = window.Hi || {};
+ window.Hi.edit = window.Hi.edit || {};
+ window.Hi.SvgEdit = window.Hi.SvgEdit || {};
+ window.Hi.SvgEdit.snapGridPixels = window.Hi.SvgEdit.snapGridPixels || 5;
+
+ var API_EDIT_LOCATION_ITEM_POSITION_URL = '/location/edit/item/position';
+
+ /* ==================== */
+ /* Icon Editing Wrapper */
+ /* ==================== */
+
+ var HiEditIcon = {
+
+ init: function() {
+ Hi.SvgIconCore.init({
+ identifyElement: function( event ) {
+ var target = event.target || event.srcElement;
+ var group = $( target ).closest( 'g' );
+ if ( group.length > 0 ) {
+ var svgDataType = group.attr( Hi.DATA_TYPE_ATTR );
+ if ( svgDataType === Hi.DATA_TYPE_ICON_VALUE ) {
+ return group[0];
+ }
+ }
+ return null;
+ },
+ onSelect: function( element ) {
+ var svgItemId = $( element ).attr( 'id' );
+ Hi.SvgPathCore.clearSelection();
+ AN.get( Hi.API_LOCATION_ITEM_EDIT_MODE_URL + '/' + svgItemId );
+ },
+ onDeselect: function() {},
+ onSave: function( element, positionData ) {
+ var svgItemId = $( element ).attr( 'id' );
+ AN.post( API_EDIT_LOCATION_ITEM_POSITION_URL + '/' + svgItemId,
+ positionData );
+ },
+ baseSvgSelector: Hi.BASE_SVG_SELECTOR,
+ areaSelector: Hi.LOCATION_VIEW_AREA_SELECTOR,
+ highlightClass: Hi.HIGHLIGHTED_CLASS,
+ enableMirror: false,
+ });
+
+ },
+
+ handleSinglePointerEventStart: function( singlePointerEvent ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgIconCore.handleSinglePointerEventStart( singlePointerEvent );
+ },
+ handleSinglePointerEventMove: function( singlePointerEvent ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgIconCore.handleSinglePointerEventMove( singlePointerEvent );
+ },
+ handleSinglePointerEventEnd: function( singlePointerEvent ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgIconCore.handleSinglePointerEventEnd( singlePointerEvent );
+ },
+
+ handleDoublePointerEventStart: function( doublePointerEvent ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgIconCore.handleDoublePointerEventStart( doublePointerEvent );
+ },
+ handleDoublePointerEventMove: function( doublePointerEvent ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgIconCore.handleDoublePointerEventMove( doublePointerEvent );
+ },
+ handleDoublePointerEventEnd: function( doublePointerEvent ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgIconCore.handleDoublePointerEventEnd( doublePointerEvent );
+ },
+
+ handleLastPointerLocation: function( x, y ) {
+ Hi.SvgIconCore.handleLastPointerLocation( x, y );
+ },
+ handleMouseWheel: function( event ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgIconCore.handleMouseWheel( event );
+ },
+ handleClick: function( event ) {
+ if ( Hi.isEditMode ) {
+ return Hi.SvgIconCore.handleClick( event );
+ }
+
+ /* Non-edit mode: fetch status view on icon click. */
+ var group = $( event.target ).closest( 'g' );
+ if ( group.length > 0 ) {
+ var svgDataType = group.attr( Hi.DATA_TYPE_ATTR );
+ if ( svgDataType === Hi.DATA_TYPE_ICON_VALUE ) {
+ var svgItemId = group.attr( 'id' );
+ if ( svgItemId ) {
+ AN.get( Hi.API_LOCATION_ITEM_STATUS_URL + '/' + svgItemId );
+ return true;
+ }
+ }
+ }
+ return false;
+ },
+ handleKeyDown: function( event ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgIconCore.handleKeyDown( event );
+ },
+
+ hasSelection: function() {
+ return Hi.SvgIconCore.hasSelection();
+ },
+
+ deleteSelectedElement: function() {
+ Hi.SvgIconCore.deleteSelectedElement();
+ },
+
+ mirrorSelected: function() {
+ Hi.SvgIconCore.mirrorSelected();
+ },
+ };
+
+ window.Hi.edit.icon = HiEditIcon;
+ HiEditIcon.init();
+
+ /* ==================== */
+ /* Path Editing Wrapper */
+ /* ==================== */
+
+ var API_EDIT_SVG_PATH_URL = '/location/edit/item/path';
+
+ var HiEditPath = {
+
+ init: function() {
+ Hi.SvgPathCore.init({
+ identifyElement: function( event ) {
+ var target = event.target || event.srcElement;
+ var group = $( target ).closest( 'g' );
+ if ( group.length > 0 ) {
+ var svgDataType = group.attr( Hi.DATA_TYPE_ATTR );
+ if ( svgDataType === Hi.DATA_TYPE_PATH_VALUE ) {
+ return group[0];
+ }
+ }
+ return null;
+ },
+ onSelect: function( element ) {
+ var svgItemId = $( element ).attr( 'id' );
+ Hi.SvgIconCore.clearSelection();
+ AN.get( Hi.API_LOCATION_ITEM_EDIT_MODE_URL + '/' + svgItemId );
+ },
+ onDeselect: function() {},
+ onSave: function( element, svgPathString ) {
+ var svgItemId = $( element ).attr( 'id' );
+ AN.post( API_EDIT_SVG_PATH_URL + '/' + svgItemId,
+ { svg_path: svgPathString } );
+ },
+ allowDeleteAll: false,
+ onDeleteAll: null,
+ baseSvgSelector: Hi.BASE_SVG_SELECTOR,
+ highlightClass: Hi.HIGHLIGHTED_CLASS,
+ });
+
+ },
+
+ handleSinglePointerEventStart: function( singlePointerEvent ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgPathCore.handleSinglePointerEventStart( singlePointerEvent );
+ },
+ handleSinglePointerEventMove: function( singlePointerEvent ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgPathCore.handleSinglePointerEventMove( singlePointerEvent );
+ },
+ handleSinglePointerEventEnd: function( singlePointerEvent ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgPathCore.handleSinglePointerEventEnd( singlePointerEvent );
+ },
+
+ handleClick: function( event ) {
+ if ( Hi.isEditMode ) {
+ return Hi.SvgPathCore.handleClick( event );
+ }
+
+ /* Non-edit mode: fetch status view on path click. */
+ var group = $( event.target ).closest( 'g' );
+ if ( group.length > 0 ) {
+ var svgDataType = group.attr( Hi.DATA_TYPE_ATTR );
+ if ( svgDataType === Hi.DATA_TYPE_PATH_VALUE ) {
+ var svgItemId = group.attr( 'id' );
+ if ( svgItemId ) {
+ AN.get( Hi.API_LOCATION_ITEM_STATUS_URL + '/' + svgItemId );
+ return true;
+ }
+ }
+ }
+ return false;
+ },
+ handleKeyDown: function( event ) {
+ if ( ! Hi.isEditMode ) { return false; }
+ return Hi.SvgPathCore.handleKeyDown( event );
+ },
+
+ hasSelection: function() {
+ return Hi.SvgPathCore.hasSelection();
+ },
+
+ deleteSelectedElement: function() {
+ Hi.SvgPathCore.deleteSelectedElement();
+ },
+
+ PROXY_PATH_CONTAINER_ID: Hi.SvgPathCore.PROXY_PATH_CONTAINER_ID,
+ };
+
+ window.Hi.edit.path = HiEditPath;
+ HiEditPath.init();
+
+ /* ==================== */
+ /* Pan/Zoom Wrapper */
+ /* ==================== */
+
+ var LOCATION_VIEW_EDIT_PANE_SELECTOR = '#hi-location-view-edit';
+ var API_EDIT_LOCATION_VIEW_GEOMETRY_URL = '/location/edit/view/geometry';
+
+ var HiSvgLocation = {
+
+ init: function() {
+ Hi.SvgPanZoomCore.init({
+ baseSvgSelector: Hi.BASE_SVG_SELECTOR,
+ areaSelector: Hi.LOCATION_VIEW_AREA_SELECTOR,
+ enableCanvasRotation: true,
+ onSave: function( saveData ) {
+ var svgElement = $( Hi.BASE_SVG_SELECTOR )[0];
+ if ( ! svgElement ) { return; }
+ var locationViewId = $( svgElement ).attr( 'location-view-id' );
+ if ( ! locationViewId ) { return; }
+ var data = {
+ svg_view_box_str: saveData.viewBoxStr,
+ svg_rotate: saveData.rotationAngle || 0,
+ };
+ AN.post( API_EDIT_LOCATION_VIEW_GEOMETRY_URL + '/' + locationViewId, data );
+ },
+ shouldSave: function() {
+ return ( Hi.isEditMode
+ && $( Hi.BASE_SVG_SELECTOR ).length > 0
+ && $( LOCATION_VIEW_EDIT_PANE_SELECTOR ).length > 0 );
+ },
+ });
+
+ },
+
+ handleSinglePointerEventStart: function( singlePointerEvent ) {
+ return Hi.SvgPanZoomCore.handleSinglePointerEventStart(
+ singlePointerEvent.start.event );
+ },
+ handleSinglePointerEventMove: function( singlePointerEvent ) {
+ return Hi.SvgPanZoomCore.handleSinglePointerEventMove(
+ singlePointerEvent.start.event, singlePointerEvent.last.event );
+ },
+ handleSinglePointerEventEnd: function( singlePointerEvent ) {
+ return Hi.SvgPanZoomCore.handleSinglePointerEventEnd();
+ },
+
+ handleDoublePointerEventStart: function( doublePointerEvent ) {
+ return Hi.SvgPanZoomCore.handleDoublePointerEventStart( doublePointerEvent );
+ },
+ handleDoublePointerEventMove: function( doublePointerEvent ) {
+ return Hi.SvgPanZoomCore.handleDoublePointerEventMove( doublePointerEvent );
+ },
+ handleDoublePointerEventEnd: function( doublePointerEvent ) {
+ return Hi.SvgPanZoomCore.handleDoublePointerEventEnd( doublePointerEvent );
+ },
+
+ handleLastPointerLocation: function( x, y ) {
+ Hi.SvgPanZoomCore.handleLastPointerLocation( x, y );
+ },
+ handleMouseWheel: function( event ) {
+ return Hi.SvgPanZoomCore.handleMouseWheel( event );
+ },
+ handleClick: function( event ) {
+ /* Pan-zoom click suppression (after drag) must be checked first. */
+ var suppressed = Hi.SvgPanZoomCore.handleClick( event );
+ if ( suppressed ) { return true; }
+
+ /* Select the location view SVG on background click — clear other selections. */
+ if ( $( event.target ).closest( Hi.LOCATION_VIEW_BASE_SELECTOR ).length > 0 ) {
+ var closest = $( event.target ).closest( Hi.LOCATION_VIEW_SVG_SELECTOR );
+ if ( closest.length > 0 ) {
+ Hi.SvgIconCore.clearSelection();
+ Hi.SvgPathCore.clearSelection();
+ return true;
+ }
+ }
+ return false;
+ },
+ handleKeyDown: function( event ) {
+ return Hi.SvgPanZoomCore.handleKeyDown( event );
+ },
+
+ };
+
+ window.Hi.location = HiSvgLocation;
+ HiSvgLocation.init();
+
+ $(document).ready(function() {
+ $( '#hi-entity-snap-grid' ).on( 'change input', function() {
+ Hi.SvgEdit.snapGridPixels = parseInt( $( this ).val(), 10 ) || 0;
+ });
+ });
+
+})();
diff --git a/src/hi/static/js/svg-event-listeners.js b/src/hi/static/js/svg-entity-event-listeners.js
similarity index 95%
rename from src/hi/static/js/svg-event-listeners.js
rename to src/hi/static/js/svg-entity-event-listeners.js
index ce465e88..05f77a3c 100644
--- a/src/hi/static/js/svg-event-listeners.js
+++ b/src/hi/static/js/svg-entity-event-listeners.js
@@ -297,6 +297,15 @@
function dispatchSinglePointerEventStart( currentEvent, singlePointerEvent ) {
let handled = Hi.edit.icon.handleSinglePointerEventStart( singlePointerEvent );
+ if ( handled ) {
+ Hi.SvgPathCore.clearSelection();
+ }
+ if ( ! handled) {
+ handled = Hi.edit.path.handleSinglePointerEventStart( singlePointerEvent );
+ if ( handled ) {
+ Hi.SvgIconCore.clearSelection();
+ }
+ }
if ( ! handled) {
handled = Hi.location.handleSinglePointerEventStart( singlePointerEvent );
}
@@ -307,6 +316,9 @@
function dispatchSinglePointerEventMove( currentEvent, singlePointerEvent ) {
let handled = Hi.edit.icon.handleSinglePointerEventMove( singlePointerEvent );
+ if ( ! handled) {
+ handled = Hi.edit.path.handleSinglePointerEventMove( singlePointerEvent );
+ }
if ( ! handled) {
handled = Hi.location.handleSinglePointerEventMove( singlePointerEvent );
}
@@ -314,9 +326,12 @@
currentEvent.stopImmediatePropagation();
}
}
-
+
function dispatchSinglePointerEventEnd( currentEvent, singlePointerEvent ) {
let handled = Hi.edit.icon.handleSinglePointerEventEnd( singlePointerEvent );
+ if ( ! handled) {
+ handled = Hi.edit.path.handleSinglePointerEventEnd( singlePointerEvent );
+ }
if ( ! handled) {
handled = Hi.location.handleSinglePointerEventEnd( singlePointerEvent );
}
@@ -397,12 +412,14 @@
gPotentialClickState = null;
}
- let handled = Hi.edit.icon.handleClick( event );
+ /* Pan-zoom click suppression first — a completed pan drag
+ must not be interpreted as a selection by other modules. */
+ let handled = Hi.location.handleClick( event );
if ( ! handled ) {
- handled = Hi.edit.path.handleClick( event );
+ handled = Hi.edit.icon.handleClick( event );
}
if ( ! handled ) {
- handled = Hi.location.handleClick( event );
+ handled = Hi.edit.path.handleClick( event );
}
if ( handled ) {
event.preventDefault();
diff --git a/src/hi/static/js/svg-icon-core.js b/src/hi/static/js/svg-icon-core.js
new file mode 100644
index 00000000..146c0361
--- /dev/null
+++ b/src/hi/static/js/svg-icon-core.js
@@ -0,0 +1,628 @@
+/*
+ SVG Icon Core
+
+ Provides drag/scale/rotate editing for positioned SVG icon elements.
+ Initialized with a configuration object. See DEFAULT_CONFIG for all
+ available options and their defaults.
+*/
+
+(function() {
+
+ window.Hi = window.Hi || {};
+ window.Hi.svgUtils = window.Hi.svgUtils || {};
+
+ const MODULE_NAME = 'svg-icon-core';
+
+ const ICON_ACTION_SCALE_KEY = 's';
+ const ICON_ACTION_ROTATE_KEY = 'r';
+ const ICON_ACTION_ZOOM_IN_KEY = '+';
+ const ICON_ACTION_ZOOM_OUT_KEY = '-';
+
+ const POINTER_EVENTS_SCALE_FACTOR = 250.0;
+ const POINTER_EVENTS_ROTATE_FACTOR = 0.1;
+ const POINTER_MOVE_ZOOM_SCALE_FACTOR = 175.0;
+ const KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT = 10.0;
+ const MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT = 10.0;
+ const MOUSE_WHEEL_ROTATE_DEGREES = 10.0;
+ const KEYPRESS_ROTATE_DEGREES = 10.0;
+ const SAVE_DEBOUNCE_MS = 400;
+
+ const SvgActionStateType = {
+ MOVE: 'move',
+ SCALE: 'scale',
+ ROTATE: 'rotate',
+ };
+
+ var DEFAULT_CONFIG = {
+ identifyElement: null, /* function(event) — return SVG group element or null */
+ onSelect: null, /* function(element) — called on icon selection */
+ onDeselect: null, /* function() — called when selection is cleared */
+ onSave: null, /* function(element, positionData) — called after position changes */
+ baseSvgSelector: null, /* CSS selector for the containing SVG element */
+ areaSelector: null, /* CSS selector for the editing area container */
+ highlightClass: 'highlighted', /* CSS class for selected icon */
+ enableMirror: true, /* allow 'm' key to mirror icon horizontally */
+ };
+
+ let gConfig = null;
+ let gActionState = SvgActionStateType.MOVE;
+ let gSelectedGroup = null;
+ let gDragData = null;
+ let gActionEditData = null;
+ let gLastPointerPosition = { x: 0, y: 0 };
+ let gIgnoreClick = false;
+
+ let saveDebounceTimer = null;
+
+ const HiSvgIconCore = {
+
+ init: function( config ) {
+ gConfig = $.extend( {}, DEFAULT_CONFIG, config );
+ },
+
+ handleSinglePointerEventStart: function( singlePointerEvent ) {
+ if ( gActionEditData ) {
+ if ( gActionState === SvgActionStateType.SCALE ) {
+ gActionEditData.isScaling = true;
+ } else if ( gActionState === SvgActionStateType.ROTATE ) {
+ gActionEditData.isRotating = true;
+ }
+ return true;
+ }
+
+ var element = gConfig.identifyElement( singlePointerEvent.start.event );
+ if ( element ) {
+ var $element = $( element );
+ if ( ! gSelectedGroup || $element.attr('id') !== $( gSelectedGroup ).attr('id') ) {
+ clearSelection();
+ gSelectedGroup = element;
+ }
+ startDrag( singlePointerEvent, $element );
+ return true;
+ }
+ return false;
+ },
+
+ handleSinglePointerEventMove: function( singlePointerEvent ) {
+ var handled = false;
+
+ if ( gActionEditData ) {
+ if ( gActionEditData.isScaling ) {
+ updateScaleFromPointerMove( singlePointerEvent );
+ handled = true;
+ } else if ( gActionEditData.isRotating ) {
+ updateRotateFromPointerMove( singlePointerEvent );
+ handled = true;
+ }
+ }
+
+ if ( gDragData ) {
+ gDragData.isDragging = true;
+ setActionStateAttr( SvgActionStateType.MOVE );
+ updateDrag( singlePointerEvent );
+ handled = true;
+ }
+ return handled;
+ },
+
+ handleSinglePointerEventEnd: function( singlePointerEvent ) {
+ return endSinglePointerEvent();
+ },
+
+ handleDoublePointerEventStart: function( doublePointerEvent ) {
+ if ( ! gSelectedGroup ) { return false; }
+ endSinglePointerEvent();
+ return true;
+ },
+
+ handleDoublePointerEventMove: function( doublePointerEvent ) {
+ if ( ! gSelectedGroup ) { return false; }
+
+ var scaleMultiplier = 1.0 + ( doublePointerEvent.deltaDistancePrevious
+ / POINTER_EVENTS_SCALE_FACTOR );
+ var deltaAngle = doublePointerEvent.deltaAngleStart * POINTER_EVENTS_ROTATE_FACTOR;
+
+ updateScale( gSelectedGroup, scaleMultiplier );
+ updateRotate( gSelectedGroup, deltaAngle );
+ return true;
+ },
+
+ handleDoublePointerEventEnd: function( doublePointerEvent ) {
+ if ( ! gSelectedGroup ) { return false; }
+ debouncedSave( gSelectedGroup );
+ return true;
+ },
+
+ handleLastPointerLocation: function( x, y ) {
+ gLastPointerPosition.x = x;
+ gLastPointerPosition.y = y;
+ },
+
+ handleMouseWheel: function( event ) {
+ if ( gDragData ) { return false; }
+
+ if ( gActionEditData ) {
+ if ( gActionState === SvgActionStateType.SCALE ) {
+ updateScaleFromMouseWheel( event );
+ return true;
+ } else if ( gActionState === SvgActionStateType.ROTATE ) {
+ updateRotateFromMouseWheel( event );
+ return true;
+ }
+ }
+ return false;
+ },
+
+ handleClick: function( event ) {
+ if ( gIgnoreClick ) {
+ gIgnoreClick = false;
+ return true;
+ }
+ gIgnoreClick = false;
+
+ var element = gConfig.identifyElement( event );
+ if ( element ) {
+ handleIconClick( event, element );
+ return true;
+ }
+ return false;
+ },
+
+ handleKeyDown: function( event ) {
+ if ( $( event.target ).is( 'input, textarea' ) ) { return false; }
+ if ( $( event.target ).closest( '.modal' ).length > 0 ) { return false; }
+
+ if ( ! gSelectedGroup ) { return false; }
+ if ( ! isPointerInArea() ) { return false; }
+
+ 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 || event.key === '=' ) {
+ if ( gActionState === SvgActionStateType.SCALE ) {
+ scaleUpFromKeypress();
+ } else if ( gActionState === SvgActionStateType.ROTATE ) {
+ rotateRightFromKeypress();
+ }
+
+ } else if ( event.key === ICON_ACTION_ZOOM_OUT_KEY ) {
+ if ( gActionState === SvgActionStateType.SCALE ) {
+ scaleDownFromKeypress();
+ } else if ( gActionState === SvgActionStateType.ROTATE ) {
+ rotateLeftFromKeypress();
+ }
+
+ } else if ( event.key === 'm' && gConfig.enableMirror ) {
+ mirrorSelectedIcon();
+
+ } else if ( event.key === 'Escape' ) {
+ scaleAbort();
+ rotateAbort();
+ gActionState = SvgActionStateType.MOVE;
+ setActionStateAttr( '' );
+ clearSelection();
+ } else {
+ return false;
+ }
+
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+ },
+
+ clearSelection: function() {
+ clearSelection();
+ },
+
+ hasSelection: function() {
+ return gSelectedGroup !== null;
+ },
+
+ deleteSelectedElement: function() {
+ if ( ! gSelectedGroup ) { return; }
+ var element = gSelectedGroup;
+ clearSelection();
+ $( element ).remove();
+ },
+
+ mirrorSelected: function() {
+ if ( ! gSelectedGroup ) { return; }
+ mirrorSelectedIcon();
+ },
+ };
+
+ window.Hi.SvgIconCore = HiSvgIconCore;
+
+ /* ==================== */
+ /* Selection */
+ /* ==================== */
+
+ function handleIconClick( event, element ) {
+ clearSelection();
+ gSelectedGroup = element;
+ $( element ).addClass( gConfig.highlightClass || 'highlighted' );
+ gActionState = SvgActionStateType.MOVE;
+ if ( gConfig.onSelect ) {
+ gConfig.onSelect( element );
+ }
+ }
+
+ function clearSelection() {
+ if ( gSelectedGroup ) {
+ $( gSelectedGroup ).removeClass( gConfig.highlightClass || 'highlighted' );
+ gSelectedGroup = null;
+ if ( gConfig.onDeselect ) {
+ gConfig.onDeselect();
+ }
+ }
+ }
+
+ /* ==================== */
+ /* Mirror */
+ /* ==================== */
+
+ function mirrorSelectedIcon() {
+ if ( ! gSelectedGroup ) { return; }
+
+ var transformStr = $( gSelectedGroup ).attr( 'transform' );
+ var parsed = Hi.svgUtils.getSvgTransformValues( transformStr );
+
+ /* Find the element's center in parent SVG space before mirroring. */
+ var baseSvgElement = $( gConfig.baseSvgSelector );
+ var centerBefore = Hi.svgUtils.getSvgCenterPoint( gSelectedGroup, baseSvgElement );
+
+ /* Negate scale.x and translate.x to mirror horizontally. */
+ var newScale = {
+ x: -1.0 * parsed.scale.x,
+ y: parsed.scale.y,
+ };
+ var newTranslate = {
+ x: -1.0 * parsed.translate.x,
+ y: parsed.translate.y,
+ };
+
+ /* Apply the mirror, then find the new center. */
+ setSvgTransformAttr( gSelectedGroup, newScale, newTranslate, parsed.rotate );
+ var centerAfter = Hi.svgUtils.getSvgCenterPoint( gSelectedGroup, baseSvgElement );
+
+ /* Adjust translate to compensate for center shift. */
+ if ( centerBefore && centerAfter ) {
+ var deltaCenterX = centerBefore.x - centerAfter.x;
+ var deltaCenterY = centerBefore.y - centerAfter.y;
+ newTranslate.x += deltaCenterX / newScale.x;
+ newTranslate.y += deltaCenterY / newScale.y;
+ setSvgTransformAttr( gSelectedGroup, newScale, newTranslate, parsed.rotate );
+ }
+
+ debouncedSave( gSelectedGroup );
+ }
+
+ /* ==================== */
+ /* Drag */
+ /* ==================== */
+
+ function startDrag( singlePointerEvent, $element ) {
+ var baseSvgElement = $( gConfig.baseSvgSelector );
+
+ var transform = $element.attr( 'transform' ) || '';
+ var parsed = Hi.svgUtils.getSvgTransformValues( transform );
+ var cursorSvgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement,
+ singlePointerEvent.last.x,
+ singlePointerEvent.last.y );
+
+ var cursorSvgOffset = {
+ x: ( cursorSvgPoint.x / parsed.scale.x ) - parsed.translate.x,
+ y: ( cursorSvgPoint.y / parsed.scale.y ) - parsed.translate.y,
+ };
+
+ gDragData = {
+ element: $element,
+ baseSvgElement: baseSvgElement,
+ cursorSvgOffset: cursorSvgOffset,
+ originalSvgScale: parsed.scale,
+ originalSvgRotate: parsed.rotate,
+ isDragging: false,
+ };
+ }
+
+ function updateDrag( singlePointerEvent ) {
+ if ( ! gDragData ) { return; }
+
+ var svgElement = gDragData.baseSvgElement;
+ var cursorSvgPoint = Hi.svgUtils.toSvgPoint( svgElement,
+ singlePointerEvent.last.x,
+ singlePointerEvent.last.y );
+ var shiftHeld = singlePointerEvent.last.event ? singlePointerEvent.last.event.shiftKey : false;
+ var snappedX = Hi.svgUtils.snapToGrid( svgElement, cursorSvgPoint.x, shiftHeld );
+ var snappedY = Hi.svgUtils.snapToGrid( svgElement, cursorSvgPoint.y, shiftHeld );
+
+ var scale = gDragData.originalSvgScale;
+ var rotate = gDragData.originalSvgRotate;
+ var translate = {
+ x: ( snappedX / scale.x ) - gDragData.cursorSvgOffset.x,
+ y: ( snappedY / scale.y ) - gDragData.cursorSvgOffset.y,
+ };
+
+ setSvgTransformAttr( gDragData.element, scale, translate, rotate );
+ }
+
+ function endDrag() {
+ if ( ! gDragData ) { return; }
+ debouncedSave( gDragData.element );
+ gDragData = null;
+ }
+
+ /* ==================== */
+ /* Pointer Event End */
+ /* ==================== */
+
+ function endSinglePointerEvent() {
+ if ( gActionEditData ) {
+ if ( gActionState === SvgActionStateType.SCALE ) {
+ gActionEditData.isScaling = false;
+ endScale();
+ } else if ( gActionState === SvgActionStateType.ROTATE ) {
+ gActionEditData.isRotating = false;
+ endRotate();
+ }
+ gActionState = SvgActionStateType.MOVE;
+ setActionStateAttr( '' );
+ gActionEditData = null;
+ gIgnoreClick = true;
+ return true;
+ }
+
+ if ( gDragData ) {
+ if ( gDragData.isDragging ) {
+ endDrag();
+ gIgnoreClick = true;
+ setActionStateAttr( '' );
+ }
+ gDragData = null;
+ return true;
+ }
+ return false;
+ }
+
+ /* ==================== */
+ /* Scale */
+ /* ==================== */
+
+ function startScale() {
+ startIconAction( SvgActionStateType.SCALE );
+ }
+
+ function updateScaleFromMouseWheel( event ) {
+ var e = event.originalEvent || event;
+ var 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 );
+ }
+ updateScale( gActionEditData.element, scaleMultiplier );
+ debouncedSave( gSelectedGroup );
+ }
+
+ function scaleUpFromKeypress() {
+ if ( gSelectedGroup ) {
+ var scaleMultiplier = 1.0 + ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
+ updateScale( gSelectedGroup, scaleMultiplier );
+ debouncedSave( gSelectedGroup );
+ }
+ }
+
+ function scaleDownFromKeypress() {
+ if ( gSelectedGroup ) {
+ var scaleMultiplier = 1.0 - ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
+ updateScale( gSelectedGroup, scaleMultiplier );
+ debouncedSave( gSelectedGroup );
+ }
+ }
+
+ function updateScaleFromPointerMove( singlePointerEvent ) {
+ var center = Hi.getScreenCenterPoint( gActionEditData.element );
+ var startX = singlePointerEvent.previous.x;
+ var startY = singlePointerEvent.previous.y;
+ var endX = singlePointerEvent.last.x;
+ var endY = singlePointerEvent.last.y;
+ var startDistance = Math.sqrt( Math.pow( startX - center.x, 2 ) + Math.pow( startY - center.y, 2 ) );
+ var endDistance = Math.sqrt( Math.pow( endX - center.x, 2 ) + Math.pow( endY - center.y, 2 ) );
+ var moveDistance = Math.abs( endDistance - startDistance );
+
+ var scaleMultiplier = 1.0;
+ if ( endDistance > startDistance ) {
+ scaleMultiplier = Math.pow( 2, moveDistance / POINTER_MOVE_ZOOM_SCALE_FACTOR );
+ } else {
+ scaleMultiplier = Math.pow( 2, -1.0 * moveDistance / POINTER_MOVE_ZOOM_SCALE_FACTOR );
+ }
+
+ updateScale( gActionEditData.element, scaleMultiplier );
+ }
+
+ function updateScale( svgElement, scaleMultiplier ) {
+ var transformStr = $( svgElement ).attr( 'transform' );
+ var oldTransform = Hi.svgUtils.getSvgTransformValues( transformStr );
+ var newScale = {
+ x: oldTransform.scale.x * scaleMultiplier,
+ y: oldTransform.scale.y * scaleMultiplier,
+ };
+ var newTranslate = {
+ x: oldTransform.translate.x * oldTransform.scale.x / newScale.x,
+ y: oldTransform.translate.y * oldTransform.scale.y / newScale.y,
+ };
+
+ setSvgTransformAttr( svgElement, newScale, newTranslate, oldTransform.rotate );
+ }
+
+ function endScale() {
+ savePosition( gActionEditData.element );
+ }
+
+ function scaleAbort() {
+ if ( gActionState !== SvgActionStateType.SCALE ) { return; }
+ endIconAction();
+ }
+
+ /* ==================== */
+ /* Rotate */
+ /* ==================== */
+
+ function startRotate() {
+ startIconAction( SvgActionStateType.ROTATE );
+ }
+
+ function updateRotateFromPointerMove( singlePointerEvent ) {
+ var center = Hi.getScreenCenterPoint( gActionEditData.element );
+ var deltaAngle = Hi.getRotationAngle( center.x, center.y,
+ singlePointerEvent.previous.x, singlePointerEvent.previous.y,
+ singlePointerEvent.last.x, singlePointerEvent.last.y );
+
+ var transformStr = $( gActionEditData.element ).attr( 'transform' );
+ var oldTransform = Hi.svgUtils.getSvgTransformValues( transformStr );
+ var shiftHeld = singlePointerEvent.last.event ? singlePointerEvent.last.event.shiftKey : false;
+
+ var newRotate = { angle: oldTransform.rotate.angle + deltaAngle,
+ cx: oldTransform.rotate.cx,
+ cy: oldTransform.rotate.cy };
+ newRotate.angle = Hi.svgUtils.snapAngle( Hi.normalizeAngle( newRotate.angle ), shiftHeld );
+
+ setSvgTransformAttr( gActionEditData.element,
+ oldTransform.scale, oldTransform.translate, newRotate );
+ }
+
+ function updateRotateFromMouseWheel( event ) {
+ var e = event.originalEvent || event;
+ var deltaAngle = MOUSE_WHEEL_ROTATE_DEGREES;
+ if ( e.deltaY > 0 ) {
+ deltaAngle = -1.0 * MOUSE_WHEEL_ROTATE_DEGREES;
+ }
+ updateRotate( gActionEditData.element, deltaAngle );
+ debouncedSave( gSelectedGroup );
+ }
+
+ function rotateRightFromKeypress() {
+ updateRotate( gSelectedGroup, KEYPRESS_ROTATE_DEGREES );
+ debouncedSave( gSelectedGroup );
+ }
+
+ function rotateLeftFromKeypress() {
+ updateRotate( gSelectedGroup, -1.0 * KEYPRESS_ROTATE_DEGREES );
+ debouncedSave( gSelectedGroup );
+ }
+
+ function updateRotate( svgElement, deltaAngle ) {
+ var transformStr = $( svgElement ).attr( 'transform' );
+ var oldTransform = Hi.svgUtils.getSvgTransformValues( transformStr );
+
+ var newRotate = { angle: oldTransform.rotate.angle + deltaAngle,
+ cx: oldTransform.rotate.cx,
+ cy: oldTransform.rotate.cy };
+ newRotate.angle = Hi.svgUtils.snapAngle( Hi.normalizeAngle( newRotate.angle ), false );
+
+ setSvgTransformAttr( svgElement,
+ oldTransform.scale, oldTransform.translate, newRotate );
+ }
+
+ function endRotate() {
+ savePosition( gActionEditData.element );
+ }
+
+ function rotateAbort() {
+ if ( gActionState !== SvgActionStateType.ROTATE ) { return; }
+ endIconAction();
+ }
+
+ /* ==================== */
+ /* Action Helpers */
+ /* ==================== */
+
+ function startIconAction( actionState ) {
+ if ( ! gSelectedGroup ) { return; }
+
+ var transform = $( gSelectedGroup ).attr( 'transform' );
+ var parsed = Hi.svgUtils.getSvgTransformValues( transform );
+
+ gActionEditData = {
+ element: gSelectedGroup,
+ scaleStart: parsed.scale,
+ translateStart: parsed.translate,
+ rotateStart: parsed.rotate,
+ isScaling: false,
+ isRotating: false,
+ };
+
+ gActionState = actionState;
+ setActionStateAttr( actionState );
+ }
+
+ function endIconAction() {
+ gActionEditData = null;
+ }
+
+ function setActionStateAttr( actionState ) {
+ if ( gConfig && gConfig.baseSvgSelector ) {
+ $( gConfig.baseSvgSelector ).attr( 'action-state', actionState || '' );
+ }
+ }
+
+ /* ==================== */
+ /* Transform */
+ /* ==================== */
+
+ function setSvgTransformAttr( element, scale, translate, rotate ) {
+ var newTransform = 'scale(' + scale.x + ' ' + scale.y + ') '
+ + 'translate(' + translate.x + ', ' + translate.y + ') '
+ + 'rotate(' + rotate.angle + ', ' + rotate.cx + ', ' + rotate.cy + ')';
+ $( element ).attr( 'transform', newTransform );
+ }
+
+ /* ==================== */
+ /* Save */
+ /* ==================== */
+
+ function savePosition( element ) {
+ if ( ! gConfig || ! gConfig.onSave ) { return; }
+
+ var transform = $( element ).attr( 'transform' );
+ var parsed = Hi.svgUtils.getSvgTransformValues( transform );
+ var baseSvgElement = $( gConfig.baseSvgSelector );
+ var center = Hi.svgUtils.getSvgCenterPoint( element, baseSvgElement );
+
+ var positionData = {
+ svg_x: center.x,
+ svg_y: center.y,
+ svg_scale: parsed.scale.x,
+ svg_rotate: parsed.rotate.angle,
+ };
+ gConfig.onSave( element, positionData );
+ }
+
+ function debouncedSave( element ) {
+ clearTimeout( saveDebounceTimer );
+ saveDebounceTimer = setTimeout( function() {
+ savePosition( element );
+ }, SAVE_DEBOUNCE_MS );
+ }
+
+ /* ==================== */
+ /* Utilities */
+ /* ==================== */
+
+ function isPointerInArea() {
+ if ( ! gConfig || ! gConfig.areaSelector ) { return true; }
+ var $area = $( gConfig.areaSelector );
+ if ( $area.length === 0 ) { return false; }
+ var offset = $area.offset();
+ var width = $area.outerWidth();
+ var height = $area.outerHeight();
+ return ( gLastPointerPosition.x >= offset.left
+ && gLastPointerPosition.x <= ( offset.left + width )
+ && gLastPointerPosition.y >= offset.top
+ && gLastPointerPosition.y <= ( offset.top + height ) );
+ }
+
+})();
diff --git a/src/hi/static/js/svg-icon.js b/src/hi/static/js/svg-icon.js
deleted file mode 100644
index ab395de5..00000000
--- a/src/hi/static/js/svg-icon.js
+++ /dev/null
@@ -1,679 +0,0 @@
-(function() {
-
- window.Hi = window.Hi || {};
- window.Hi.edit = window.Hi.edit || {};
- window.Hi.svgUtils = window.Hi.svgUtils || {};
-
- const MODULE_NAME = 'svg-icon';
- let gCurrentSelectionModule = null;
-
- const HiEditSvgIcon = {
- init: function() {
- Hi.edit.eventBus.subscribe( Hi.edit.SELECTION_MADE_EVENT_NAME,
- 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 );
- },
- clearSelection: function( data ) {
- gCurrentSelectionModule = data.moduleName;
- if ( data.moduleName != MODULE_NAME ) {
- clearSelectedIconSvgGroup();
- }
- }
- };
-
- window.Hi.edit.icon = HiEditSvgIcon;
- HiEditSvgIcon.init();
-
- /*
- SVG ICON EDITING
-
- - Icons can be selected to show the entity details in the side edit panel.
- - Icons can be dragged to change their location.
- - Selected icons can be rotated and scaled to change their appearance.
- */
-
- const SELECTABLE_CLASS = 'selectable';
- const SELECTABLE_SELECTOR = '.' + SELECTABLE_CLASS;
-
- const ICON_ACTION_SCALE_KEY = 's';
- const ICON_ACTION_ROTATE_KEY = 'r';
- const ICON_ACTION_ZOOM_IN_KEY = '+';
- const ICON_ACTION_ZOOM_OUT_KEY = '-';
-
- const POINTER_EVENTS_SCALE_FACTOR = 250.0;
- const POINTER_EVENTS_ROTATE_FACTOR = 0.1;
- const POINTER_MOVE_ZOOM_SCALE_FACTOR = 175.0; // Number of pixels moved to double or halve size
- const KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT = 10.0;
- const MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT = 10.0;
- const MOUSE_WHEEL_ROTATE_DEGREES = 10.0;
- const KEYPRESS_ROTATE_DEGREES = 10.0;
- const POSITION_API_CALL_DEBOUNCE_MS = 400;
-
- const API_EDIT_LOCATION_ITEM_POSITION_URL = '/location/edit/item/position';
-
- const SvgActionStateType = {
- MOVE: 'move',
- SCALE: 'scale',
- ROTATE: 'rotate'
- };
-
- let gSvgIconActionState = SvgActionStateType.MOVE;
- let gSelectedIconSvgGroup = null;
- let gSvgIconDragData = null;
- let gSvgIconActionEditData = null; // For scale and rotate actions
-
- let gLastPointerPosition = { x: 0, y: 0 };
- let gIgnoreCLick = false; // Set by pointer event handling when no click handling should be done
-
- let positionApiCallDebounceTimer = null;
- 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;
- }
-
- 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;
- }
-
- function _handleSinglePointerEventEnd( singlePointerEvent ) {
- 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;
- }
-
- 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;
- }
-
- function _handleDoublePointerEventStart( doublePointerEvent ) {
- 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;
-
- 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;
- }
-
- function endDoublePointerEvent() {
- if ( ! Hi.isEditMode ) { return false; }
- if ( ! gSelectedIconSvgGroup ) { return false; }
- saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
- return true;
- }
-
- function _handleLastPointerLocation( x, 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;
- }
-
- 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 ) {
- if ( Hi.DEBUG ) { 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') ) {
- return false;
- }
- if ($(event.target).closest('.modal').length > 0) {
- return false;
- }
- 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;
- }
-
- function handleSvgIconClick( event, enclosingSvgGroup ) {
- const svgItemId = $(enclosingSvgGroup).attr('id');
-
- 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_EDIT_MODE_URL}/${svgItemId}` );
-
- } else {
- AN.get( `${Hi.API_LOCATION_ITEM_STATUS_URL}/${svgItemId}` );
- }
- }
-
- function clearSelectedIconSvgGroup() {
- if ( gSelectedIconSvgGroup ) {
- if ( Hi.DEBUG ) { console.log('Clearing svg icon selection'); }
- $( SELECTABLE_SELECTOR ).removeClass( Hi.HIGHLIGHTED_CLASS );
- gSelectedIconSvgGroup = null;
- }
- }
-
- function startDrag( singlePointerEvent, enclosingSvgGroup ) {
-
- const dragElement = enclosingSvgGroup;
- Hi.displayElementInfo( 'Drag Element', dragElement );
-
- 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:
- SVG Cursor Point: ( ${cursorSvgPoint.x}, ${cursorSvgPoint.y} ),
- SVG Cursor Offset: ( ${gSvgIconDragData.cursorSvgOffset.x}, ${gSvgIconDragData.cursorSvgOffset.y} )`);
- }
-
- }
-
- function updateDrag( singlePointerEvent ) {
- if ( gSvgIconDragData == null ) {
- 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 );
-
- 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 );
- }
-
- function endDrag() {
- if ( gSvgIconDragData == null ) {
- return;
- }
-
- Hi.displayElementInfo( 'End Drag Element', gSvgIconDragData.element );
- saveIconSvgPositionDebouncer( gSvgIconDragData.element );
- gSvgIconDragData = null;
- }
-
- function startIconAction( actionState ) {
- 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
- };
-
- gSvgIconActionState = actionState;
- $(Hi.BASE_SVG_SELECTOR).attr( Hi.SVG_ACTION_STATE_ATTR_NAME, actionState );
- }
- }
-
- function endIconAction( element ) {
- if ( gSvgIconActionEditData ) {
- gSvgIconActionEditData = null;
- }
- }
-
- function startScale() {
- 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 );
- }
- if ( Hi.DEBUG ) { 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 );
- }
- }
-
- function scaleDownFromKeypress() {
- 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;
- }
-
- 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:
-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 );
- }
-
- function endScale() {
- if ( Hi.DEBUG ) { console.log( 'Scale End' ); }
- saveIconSvgPosition( gSvgIconActionEditData.element );
- }
-
- function scaleAbort() {
- if ( gSvgIconActionState != SvgActionStateType.SCALE ) {
- return;
- }
- endIconAction();
- }
-
- function startRotate() {
- startIconAction( SvgActionStateType.ROTATE );
- }
-
- function updateRotateFromPointerMove( singlePointerEvent ) {
- if ( Hi.DEBUG ) { console.log( `updateRotation [${MODULE_NAME}]` ); }
-
- 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 transformStr = $(gSvgIconActionEditData.element).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 );
-
- 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 );
- }
-
- function rotateRightFromKeypress() {
- let deltaAngle = KEYPRESS_ROTATE_DEGREES;
- updateRotate( gSelectedIconSvgGroup, deltaAngle );
- saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
- }
-
- function rotateLeftFromKeypress() {
- 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:
-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 );
- }
-
- function endRotate() {
- saveIconSvgPosition( gSvgIconActionEditData.element );
- }
-
- function rotateAbort() {
- 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);
- }
-
- function saveIconSvgPositionDebouncer( element ) {
- const currentTime = Date.now();
- const timeSinceLastApiCall = currentTime - lastPositionApiCallTime;
-
- clearTimeout( positionApiCallDebounceTimer );
- positionApiCallDebounceTimer = setTimeout(() => {
- saveIconSvgPosition( element );
- lastPositionApiCallTime = Date.now();
- }, POSITION_API_CALL_DEBOUNCE_MS );
- }
-
- function saveIconSvgPosition( element ) {
-
- 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 );
- }
-
-
-})();
diff --git a/src/hi/static/js/svg-location.js b/src/hi/static/js/svg-location.js
deleted file mode 100644
index 7bf9258a..00000000
--- a/src/hi/static/js/svg-location.js
+++ /dev/null
@@ -1,696 +0,0 @@
-(function() {
-
- window.Hi = window.Hi || {};
- window.Hi.edit = window.Hi.edit || {};
- window.Hi.svgUtils = window.Hi.svgUtils || {};
-
- const MODULE_NAME = 'svg-location';
- let gCurrentSelectionModule = null;
-
- const HiSvgLocation = {
- init: function() {
- Hi.edit.eventBus.subscribe( Hi.edit.SELECTION_MADE_EVENT_NAME,
- 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 );
- },
- clearSelection: function( data ) {
- gCurrentSelectionModule = data.moduleName;
- if ( data.moduleName != MODULE_NAME ) {
- clearSelectedLocationViewSvg();
- }
- }
- };
-
- window.Hi.location = HiSvgLocation;
- HiSvgLocation.init();
-
- /*
- SVG LOCATION
-
- - For panning, zooming and rotating of the underlying background SVG of a location view.
- */
-
- const SVG_TRANSFORM_ACTION_SCALE_KEY = 's';
- const SVG_TRANSFORM_ACTION_ROTATE_KEY = 'r';
- const SVG_TRANSFORM_ACTION_INCREASE_KEY = '+';
- const SVG_TRANSFORM_ACTION_DECREASE_KEY = '-';
-
- const KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT = 10.0;
- const KEYPRESS_ROTATE_DEGREES = 10.0;
- const MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT = 10.0;
- const MOUSE_WHEEL_ROTATE_ANGLE = 3.0;
- const SINGLE_POINTER_EVENTS_SCALE_FACTOR = 250.0;
- const DOUBLE_POINTER_EVENTS_SCALE_FACTOR = 250.0;
- const SINGLE_POINTER_EVENTS_ROTATE_FACTOR = 0.5;
- const DOUBLE_POINTER_EVENTS_ROTATE_FACTOR = 0.5;
- 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/view/geometry';
-
- const SvgTransformType = {
- MOVE: 'move',
- SCALE: 'scale',
- ROTATE: 'rotate'
- };
- let gSvgTransformType = SvgTransformType.MOVE;
-
- let gSelectedLocationViewSvg = null;
- let gSvgTransformData = null;
- let gLastPointerPosition = { x: 0, y: 0 };
- let gIgnoreCLick = false; // Set by pointer event handling when no click handling should be done
-
- let zoomApiCallDebounceTimer = null;
- 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;
- }
-
- 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;
- }
-
- function _handleSinglePointerEventEnd( singlePointerEvent ) {
-
- const event = singlePointerEvent.last.event;
-
- let eventWasHandled = false;
- if ( gSvgTransformData ) {
- if ( gSvgTransformType == SvgTransformType.SCALE ) {
- endScale();
- 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;
- }
-
- 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;
- }
-
- 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;
- }
-
- function _handleDoublePointerEventEnd( doublePointerEvent ) {
- if ( ! gSvgTransformData ) {
- return false;
- }
- saveSvgGeometryDebouncer();
- abortScale();
- abortRotation();
- return true;
- }
-
- function _handleLastPointerLocation( x, 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;
- }
-
- 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;
- }
-
- function _handleKeyDown( event ) {
- if ( $(event.target).is('input, textarea') ) {
- return false;
- }
- if ($(event.target).closest('.modal').length > 0) {
- return false;
- }
- if ( gSelectedLocationViewSvg ) {
-
- 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;
- }
-
- function isEventInLocationArea( event ) {
-
- if ( $(event.target).is('input, textarea') ) {
- return false;
- }
- if ($(event.target).closest('.modal').length > 0) {
- return false;
- }
- return $(event.target).closest(Hi.LOCATION_VIEW_AREA_SELECTOR).length > 0;
- }
-
- 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;
- }
-
- function clearSelectedLocationViewSvg() {
- if ( gSelectedLocationViewSvg ) {
- if ( Hi.DEBUG ) { console.log('Clearing location view svg transform data'); }
- 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 );
- let deltaSvgUnits = {
- x: ( singlePointerEvent.last.x - singlePointerEvent.start.x ) / pixelsPerSvgUnit.scaleX,
- y: ( singlePointerEvent.last.y - singlePointerEvent.start.y ) / pixelsPerSvgUnit.scaleX
- };
-
- 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;
-
- adjustSvgViewBox( gSvgTransformData.start.viewBox,
- gSvgTransformData.start.viewBox.width,
- gSvgTransformData.start.viewBox.height,
- newX,
- newY );
-
- return;
- }
-
- function endDrag( event ) {
- 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();
- }
-
- function zoomOutFromKeypress( event ) {
- let scaleFactor = 1.0 + ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
- zoom( scaleFactor );
- saveSvgGeometryDebouncer();
- }
-
- function zoomFromMouseWheel( event ) {
-
- const e = event.originalEvent;
-
- // Immediately update the visual
- 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 );
- }
- zoom( scaleFactor );
- saveSvgGeometryDebouncer();
- }
-
- function zoom( 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 );
- }
-
- function updateScaleFromPointerMove( event ) {
- if ( Hi.DEBUG ) { console.log( `updateScale [${MODULE_NAME}]` ); }
-
- 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 scaleFactor = ( 1.0 - ( vectorLengthDelta / SINGLE_POINTER_EVENTS_SCALE_FACTOR ));
-
- 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();
- }
-
- function abortScale() {
- 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;
- }
-
- function startRotation( event ) {
- 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}]` ); }
-
- 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 );
-
- deltaAngle *= SINGLE_POINTER_EVENTS_ROTATE_FACTOR;
- rotate( deltaAngle );
- }
-
- function rotateRightFromKeypress( event ) {
- let deltaAngle = KEYPRESS_ROTATE_DEGREES;
- rotate( deltaAngle );
- saveSvgGeometryDebouncer();
- }
-
- function rotateLeftFromKeypress( event ) {
- let deltaAngle = -1.0 * KEYPRESS_ROTATE_DEGREES;
- rotate( deltaAngle );
- saveSvgGeometryDebouncer();
- }
-
- function rotateFromMouseWheel( event ) {
-
- const e = event.originalEvent;
-
- // Immediately update the visual
- let deltaAngle = MOUSE_WHEEL_ROTATE_ANGLE;
- if ( e.deltaY > 0 ) {
- deltaAngle *= -1.0;
- }
- 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})`;
- $(gSelectedLocationViewSvg).attr( 'transform', newTransform );
-
- // 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();
- }
-
- function abortRotation( ) {
- 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
- 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) {
- newX = extentsSvgViewBox.x;
- }
- if (newY < extentsSvgViewBox.y) {
- newY = extentsSvgViewBox.y;
- }
- if (( newX + newWidth ) > ( extentsSvgViewBox.x + extentsSvgViewBox.width )) {
- newX = extentsSvgViewBox.x + extentsSvgViewBox.width - newWidth;
- }
- if (( newY + newHeight ) > ( extentsSvgViewBox.y + extentsSvgViewBox.height )) {
- newY = extentsSvgViewBox.y + extentsSvgViewBox.height - newHeight;
- }
-
- Hi.svgUtils.setSvgViewBox( gSelectedLocationViewSvg, newX, newY, newWidth, newHeight );
- }
-
- function calculateRotatedRectangle( initialRect, rotationAngle ) {
-
- 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) => {
- 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)),
- };
- });
-
- // 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 };
- }
-
- function saveSvgGeometryDebouncer() {
- if ( ! shouldSaveGeometry() ) {
- return;
- }
- const currentTime = Date.now();
- const timeSinceLastApiCall = currentTime - lastZoomApiCallTime;
-
- clearTimeout( zoomApiCallDebounceTimer );
- zoomApiCallDebounceTimer = setTimeout(() => {
- saveSvgGeometryIfNeeded();
- lastZoomApiCallTime = Date.now();
- }, ZOOM_API_CALL_DEBOUNCE_MS );
- }
-
- function saveSvgGeometryIfNeeded( ) {
- 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 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 );
- }
-
- 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 ));
- }
-
-})();
diff --git a/src/hi/static/js/svg-pan-zoom-core.js b/src/hi/static/js/svg-pan-zoom-core.js
new file mode 100644
index 00000000..0d6b665d
--- /dev/null
+++ b/src/hi/static/js/svg-pan-zoom-core.js
@@ -0,0 +1,578 @@
+/*
+ SVG Pan/Zoom Core
+
+ Provides viewBox-based pan and zoom for an SVG element, with optional
+ canvas rotation and scale-mode support.
+ Initialized with a configuration object. See DEFAULT_CONFIG for all
+ available options and their defaults.
+*/
+
+(function() {
+
+ window.Hi = window.Hi || {};
+ window.Hi.svgUtils = window.Hi.svgUtils || {};
+
+ var MODULE_NAME = 'svg-pan-zoom-core';
+
+ var KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT = 10.0;
+ var KEYPRESS_ROTATE_DEGREES = 10.0;
+ var MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT = 10.0;
+ var MOUSE_WHEEL_ROTATE_ANGLE = 3.0;
+ var SINGLE_POINTER_SCALE_FACTOR = 250.0;
+ var SINGLE_POINTER_ROTATE_FACTOR = 0.5;
+ var DOUBLE_POINTER_SCALE_FACTOR = 250.0;
+ var DOUBLE_POINTER_ROTATE_FACTOR = 0.5;
+ var ZOOM_SAVE_DEBOUNCE_MS = 400;
+
+ var SCALE_KEY = 's';
+ var ROTATE_KEY = 'r';
+
+ var SvgTransformType = {
+ MOVE: 'move',
+ SCALE: 'scale',
+ ROTATE: 'rotate',
+ };
+
+ var DEFAULT_CONFIG = {
+ baseSvgSelector: null, /* CSS selector for the target SVG element */
+ areaSelector: null, /* CSS selector for the container area */
+ onSave: null, /* function(saveData) — called after changes */
+ shouldSave: null, /* function() — return true to enable saving */
+ enableCanvasRotation: false, /* enable S/R key modes for scale and rotation */
+ };
+
+ var gConfig = null;
+ var gSvgElement = null;
+ var gTransformType = SvgTransformType.MOVE;
+ var gTransformData = null;
+ var gIgnoreClick = false;
+ var gLastPointerPosition = { x: 0, y: 0 };
+
+ var saveDebounceTimer = null;
+ var lastSaveTime = 0;
+
+ var HiSvgPanZoomCore = {
+
+ init: function( config ) {
+ gConfig = $.extend( {}, DEFAULT_CONFIG, config );
+ gSvgElement = $( gConfig.baseSvgSelector )[0] || null;
+ },
+
+ refresh: function() {
+ gSvgElement = gConfig ? $( gConfig.baseSvgSelector )[0] || null : null;
+ },
+
+ handleSinglePointerEventStart: function( event ) {
+ if ( ! gSvgElement ) { return false; }
+
+ var svgViewBox = Hi.svgUtils.getSvgViewBox( gSvgElement );
+ gTransformData = {
+ isDragging: false,
+ start: {
+ x: event.clientX,
+ y: event.clientY,
+ viewBox: svgViewBox,
+ },
+ last: {
+ x: event.clientX,
+ y: event.clientY,
+ },
+ };
+ return true;
+ },
+
+ handleSinglePointerEventMove: function( startEvent, lastEvent ) {
+ if ( ! gTransformData ) { return false; }
+
+ gTransformData.isDragging = true;
+
+ if ( gConfig.enableCanvasRotation && gTransformType === SvgTransformType.SCALE ) {
+ updateScaleFromPointerMove( lastEvent );
+ } else if ( gConfig.enableCanvasRotation && gTransformType === SvgTransformType.ROTATE ) {
+ updateRotateFromPointerMove( startEvent, lastEvent );
+ } else {
+ updatePan( startEvent, lastEvent );
+ }
+
+ gTransformData.last = { x: lastEvent.clientX, y: lastEvent.clientY };
+ return true;
+ },
+
+ handleSinglePointerEventEnd: function() {
+ if ( ! gTransformData ) { return false; }
+
+ var wasDragging = gTransformData.isDragging;
+
+ if ( wasDragging ) {
+ if ( gConfig.enableCanvasRotation && gTransformType === SvgTransformType.SCALE ) {
+ endScale();
+ } else if ( gConfig.enableCanvasRotation && gTransformType === SvgTransformType.ROTATE ) {
+ endRotation();
+ } else {
+ debouncedSave();
+ }
+ gIgnoreClick = true;
+ }
+
+ gTransformData = null;
+
+ if ( wasDragging ) {
+ return true;
+ }
+ return false;
+ },
+
+ handleDoublePointerEventStart: function( doublePointerEvent ) {
+ if ( ! gSvgElement ) { return false; }
+
+ var svgViewBox = Hi.svgUtils.getSvgViewBox( gSvgElement );
+ gTransformData = {
+ isDragging: false,
+ start: {
+ x: doublePointerEvent.start.event.clientX,
+ y: doublePointerEvent.start.event.clientY,
+ viewBox: svgViewBox,
+ },
+ last: {
+ x: doublePointerEvent.start.event.clientX,
+ y: doublePointerEvent.start.event.clientY,
+ },
+ };
+ return true;
+ },
+
+ handleDoublePointerEventMove: function( doublePointerEvent ) {
+ if ( ! gTransformData ) { return false; }
+
+ var scaleFactor = 1.0 - ( doublePointerEvent.deltaDistancePrevious
+ / DOUBLE_POINTER_SCALE_FACTOR );
+ zoom( scaleFactor );
+
+ if ( gConfig.enableCanvasRotation ) {
+ var deltaAngle = doublePointerEvent.deltaAnglePrevious * DOUBLE_POINTER_ROTATE_FACTOR;
+ rotateCanvas( deltaAngle );
+ }
+ return true;
+ },
+
+ handleDoublePointerEventEnd: function( doublePointerEvent ) {
+ if ( ! gTransformData ) { return false; }
+ debouncedSave();
+ if ( gConfig.enableCanvasRotation ) {
+ abortScale();
+ abortRotation();
+ }
+ gTransformData = null;
+ return true;
+ },
+
+ handleMouseWheel: function( event ) {
+ if ( ! gSvgElement ) { return false; }
+ if ( ! isEventInArea( event ) ) { return false; }
+
+ if ( gConfig.enableCanvasRotation && gTransformType === SvgTransformType.ROTATE ) {
+ rotateFromMouseWheel( event );
+ } else {
+ if ( gConfig.enableCanvasRotation ) {
+ abortScale();
+ abortRotation();
+ }
+ var e = event.originalEvent || event;
+ var 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 );
+ }
+ zoom( scaleFactor );
+ }
+ debouncedSave();
+
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+ },
+
+ handleKeyDown: function( event ) {
+ if ( ! gSvgElement ) { return false; }
+ if ( $( event.target ).is( 'input, textarea' ) ) { return false; }
+ if ( $( event.target ).closest( '.modal' ).length > 0 ) { return false; }
+ if ( ! isEventInArea( event ) ) { return false; }
+
+ if ( gConfig.enableCanvasRotation && event.key === SCALE_KEY ) {
+ abortRotation();
+ startScale();
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+
+ } else if ( gConfig.enableCanvasRotation && event.key === ROTATE_KEY ) {
+ abortScale();
+ startRotation();
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+
+ } else if ( event.key === '+' || event.key === '=' ) {
+ if ( gConfig.enableCanvasRotation && gTransformType === SvgTransformType.ROTATE ) {
+ rotateRightFromKeypress();
+ } else {
+ zoomIn();
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+
+ } else if ( event.key === '-' ) {
+ if ( gConfig.enableCanvasRotation && gTransformType === SvgTransformType.ROTATE ) {
+ rotateLeftFromKeypress();
+ } else {
+ zoomOut();
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+
+ } else if ( gConfig.enableCanvasRotation && event.key === 'Escape' ) {
+ abortScale();
+ abortRotation();
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+ }
+ return false;
+ },
+
+ handleClick: function( event ) {
+ if ( gIgnoreClick ) {
+ gIgnoreClick = false;
+ return true;
+ }
+ return false;
+ },
+
+ handleLastPointerLocation: function( x, y ) {
+ gLastPointerPosition.x = x;
+ gLastPointerPosition.y = y;
+ },
+
+ isDragging: function() {
+ return gTransformData && gTransformData.isDragging;
+ },
+
+ getRotationAngle: function() {
+ if ( ! gSvgElement ) { return 0; }
+ var transform = $( gSvgElement ).attr( 'transform' ) || '';
+ var parsed = Hi.svgUtils.getSvgTransformValues( transform );
+ return parsed.rotate.angle;
+ },
+ };
+
+ window.Hi.SvgPanZoomCore = HiSvgPanZoomCore;
+
+ /* ==================== */
+ /* Pan */
+ /* ==================== */
+
+ function updatePan( startEvent, lastEvent ) {
+ if ( ! gSvgElement || ! gTransformData ) { return; }
+
+ var pixelsPerSvgUnit = Hi.svgUtils.getPixelsPerSvgUnit( gSvgElement );
+ var deltaSvgUnits = {
+ x: ( lastEvent.clientX - startEvent.clientX ) / pixelsPerSvgUnit.scaleX,
+ y: ( lastEvent.clientY - startEvent.clientY ) / pixelsPerSvgUnit.scaleX,
+ };
+
+ /* Account for canvas rotation when panning. */
+ if ( gConfig.enableCanvasRotation ) {
+ var transform = $( gSvgElement ).attr( 'transform' ) || '';
+ var parsed = Hi.svgUtils.getSvgTransformValues( transform );
+ deltaSvgUnits = rotateVector( deltaSvgUnits, -1.0 * parsed.rotate.angle );
+ }
+
+ var newX = gTransformData.start.viewBox.x - deltaSvgUnits.x;
+ var newY = gTransformData.start.viewBox.y - deltaSvgUnits.y;
+
+ adjustViewBox(
+ gTransformData.start.viewBox,
+ gTransformData.start.viewBox.width,
+ gTransformData.start.viewBox.height,
+ newX,
+ newY
+ );
+ }
+
+ /* ==================== */
+ /* Zoom */
+ /* ==================== */
+
+ function zoom( scaleFactor ) {
+ var currentViewBox = Hi.svgUtils.getSvgViewBox( gSvgElement );
+ var newWidth = scaleFactor * currentViewBox.width;
+ var newHeight = scaleFactor * currentViewBox.height;
+ adjustViewBox( currentViewBox, newWidth, newHeight );
+ }
+
+ function zoomIn() {
+ var scaleFactor = 1.0 / ( 1.0 + ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 ) );
+ zoom( scaleFactor );
+ debouncedSave();
+ }
+
+ function zoomOut() {
+ var scaleFactor = 1.0 + ( KEYPRESS_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
+ zoom( scaleFactor );
+ debouncedSave();
+ }
+
+ /* ==================== */
+ /* Canvas Scale Mode */
+ /* ==================== */
+
+ function startScale() {
+ gTransformType = SvgTransformType.SCALE;
+ $( gSvgElement ).attr( 'action-state', gTransformType );
+ }
+
+ function updateScaleFromPointerMove( event ) {
+ if ( ! gTransformData ) { return; }
+
+ var screenCenter = Hi.getScreenCenterPoint( gSvgElement );
+ var startVector = {
+ x: gTransformData.start.x - screenCenter.x,
+ y: gTransformData.start.y - screenCenter.y,
+ };
+ var endVector = {
+ x: event.clientX - screenCenter.x,
+ y: event.clientY - screenCenter.y,
+ };
+ var startDistance = Math.sqrt( startVector.x * startVector.x + startVector.y * startVector.y );
+ var endDistance = Math.sqrt( endVector.x * endVector.x + endVector.y * endVector.y );
+ var delta = endDistance - startDistance;
+
+ var scaleFactor = 1.0 - ( delta / SINGLE_POINTER_SCALE_FACTOR );
+ var currentViewBox = gTransformData.start.viewBox;
+ var newWidth = scaleFactor * currentViewBox.width;
+ var newHeight = scaleFactor * currentViewBox.height;
+ adjustViewBox( currentViewBox, newWidth, newHeight );
+ }
+
+ function endScale() {
+ gTransformType = SvgTransformType.MOVE;
+ $( gSvgElement ).attr( 'action-state', '' );
+ debouncedSave();
+ }
+
+ function abortScale() {
+ if ( gTransformType !== SvgTransformType.SCALE ) { return; }
+ gTransformType = SvgTransformType.MOVE;
+ gTransformData = null;
+ $( gSvgElement ).attr( 'action-state', '' );
+ }
+
+ /* ==================== */
+ /* Canvas Rotation */
+ /* ==================== */
+
+ function startRotation() {
+ gTransformType = SvgTransformType.ROTATE;
+ $( gSvgElement ).attr( 'action-state', gTransformType );
+ }
+
+ function rotateCanvas( deltaAngle ) {
+ var transform = $( gSvgElement ).attr( 'transform' ) || '';
+ var parsed = Hi.svgUtils.getSvgTransformValues( transform );
+ var newAngle = Hi.normalizeAngle( parsed.rotate.angle + deltaAngle );
+ var newTransform = 'rotate(' + newAngle + ', ' + parsed.rotate.cx + ', ' + parsed.rotate.cy + ')';
+ $( gSvgElement ).attr( 'transform', newTransform );
+
+ /* CSS transform for browser rendering compatibility. */
+ gSvgElement.style.transform = 'rotate(' + newAngle + 'deg)';
+ }
+
+ function updateRotateFromPointerMove( startEvent, lastEvent ) {
+ var screenCenter = Hi.getScreenCenterPoint( gSvgElement );
+ var deltaAngle = Hi.getRotationAngle(
+ screenCenter.x, screenCenter.y,
+ gTransformData.last.x, gTransformData.last.y,
+ lastEvent.clientX, lastEvent.clientY
+ );
+ deltaAngle *= SINGLE_POINTER_ROTATE_FACTOR;
+ rotateCanvas( deltaAngle );
+ }
+
+ function rotateFromMouseWheel( event ) {
+ var e = event.originalEvent || event;
+ var deltaAngle = MOUSE_WHEEL_ROTATE_ANGLE;
+ if ( e.deltaY > 0 ) {
+ deltaAngle *= -1.0;
+ }
+ rotateCanvas( deltaAngle );
+ }
+
+ function rotateRightFromKeypress() {
+ rotateCanvas( KEYPRESS_ROTATE_DEGREES );
+ debouncedSave();
+ }
+
+ function rotateLeftFromKeypress() {
+ rotateCanvas( -1.0 * KEYPRESS_ROTATE_DEGREES );
+ debouncedSave();
+ }
+
+ function endRotation() {
+ gTransformType = SvgTransformType.MOVE;
+ $( gSvgElement ).attr( 'action-state', '' );
+ debouncedSave();
+ }
+
+ function abortRotation() {
+ if ( gTransformType !== SvgTransformType.ROTATE ) { return; }
+ gTransformType = SvgTransformType.MOVE;
+ gTransformData = null;
+ $( gSvgElement ).attr( 'action-state', '' );
+ }
+
+ /* ==================== */
+ /* ViewBox Adjustment */
+ /* ==================== */
+
+ function adjustViewBox( initialViewBox, newWidth, newHeight, newX, newY ) {
+ if ( ! gSvgElement ) { return; }
+
+ /* Adjust aspect ratio to match container. */
+ var areaElement = $( gConfig.areaSelector )[0];
+ if ( areaElement ) {
+ var containerRect = areaElement.getBoundingClientRect();
+ var containerAspectRatio = containerRect.width / containerRect.height;
+ var newAspectRatio = newWidth / newHeight;
+
+ if ( newAspectRatio > containerAspectRatio ) {
+ newHeight = newWidth / containerAspectRatio;
+ } else if ( newAspectRatio < containerAspectRatio ) {
+ newWidth = newHeight * containerAspectRatio;
+ }
+ }
+
+ /* Clamp within extents, accounting for canvas rotation if enabled. */
+ var extents = Hi.svgUtils.getExtentsSvgViewBox( gSvgElement );
+ if ( extents && extents.width ) {
+ if ( gConfig.enableCanvasRotation ) {
+ var transform = $( gSvgElement ).attr( 'transform' ) || '';
+ var parsed = Hi.svgUtils.getSvgTransformValues( transform );
+ extents = calculateRotatedRectangle( extents, parsed.rotate.angle );
+ }
+
+ newWidth = Math.min( newWidth, extents.width );
+ newHeight = Math.min( newHeight, extents.height );
+
+ if ( newX === undefined || newX === null ) {
+ newX = initialViewBox.x + ( initialViewBox.width - newWidth ) / 2.0;
+ }
+ if ( newY === undefined || newY === null ) {
+ newY = initialViewBox.y + ( initialViewBox.height - newHeight ) / 2.0;
+ }
+
+ if ( newX < extents.x ) { newX = extents.x; }
+ if ( newY < extents.y ) { newY = extents.y; }
+ if ( ( newX + newWidth ) > ( extents.x + extents.width ) ) {
+ newX = extents.x + extents.width - newWidth;
+ }
+ if ( ( newY + newHeight ) > ( extents.y + extents.height ) ) {
+ newY = extents.y + extents.height - newHeight;
+ }
+ } else {
+ if ( newX === undefined || newX === null ) {
+ newX = initialViewBox.x + ( initialViewBox.width - newWidth ) / 2.0;
+ }
+ if ( newY === undefined || newY === null ) {
+ newY = initialViewBox.y + ( initialViewBox.height - newHeight ) / 2.0;
+ }
+ }
+
+ Hi.svgUtils.setSvgViewBox( gSvgElement, newX, newY, newWidth, newHeight );
+ }
+
+ /* ==================== */
+ /* Rotation Geometry */
+ /* ==================== */
+
+ function calculateRotatedRectangle( rect, rotationAngle ) {
+ var corners = [
+ { x: rect.x, y: rect.y },
+ { x: rect.x + rect.width, y: rect.y },
+ { x: rect.x, y: rect.y + rect.height },
+ { x: rect.x + rect.width, y: rect.y + rect.height },
+ ];
+
+ var centerX = rect.x + ( rect.width / 2.0 );
+ var centerY = rect.y + ( rect.height / 2.0 );
+ var radians = ( Math.PI / 180 ) * rotationAngle;
+
+ var rotatedCorners = corners.map( function( corner ) {
+ var dx = corner.x - centerX;
+ var 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 ) ),
+ };
+ });
+
+ var minX = Math.min.apply( null, rotatedCorners.map( function( c ) { return c.x; } ) );
+ var minY = Math.min.apply( null, rotatedCorners.map( function( c ) { return c.y; } ) );
+ var maxX = Math.max.apply( null, rotatedCorners.map( function( c ) { return c.x; } ) );
+ var maxY = Math.max.apply( null, rotatedCorners.map( function( c ) { return c.y; } ) );
+
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
+ }
+
+ function rotateVector( point, rotationAngle ) {
+ var radians = ( Math.PI / 180 ) * rotationAngle;
+ return {
+ x: point.x * Math.cos( radians ) - point.y * Math.sin( radians ),
+ y: point.x * Math.sin( radians ) + point.y * Math.cos( radians ),
+ };
+ }
+
+ /* ==================== */
+ /* Utilities */
+ /* ==================== */
+
+ function isEventInArea( event ) {
+ if ( ! gConfig || ! gConfig.areaSelector ) {
+ return true;
+ }
+ if ( event.type === 'keydown' || event.type === 'keyup' ) {
+ var $area = $( gConfig.areaSelector );
+ if ( $area.length === 0 ) { return false; }
+ var offset = $area.offset();
+ var width = $area.outerWidth();
+ var height = $area.outerHeight();
+ return ( gLastPointerPosition.x >= offset.left
+ && gLastPointerPosition.x <= ( offset.left + width )
+ && gLastPointerPosition.y >= offset.top
+ && gLastPointerPosition.y <= ( offset.top + height ) );
+ }
+ return $( event.target ).closest( gConfig.areaSelector ).length > 0;
+ }
+
+ function debouncedSave() {
+ if ( ! gConfig || ! gConfig.onSave ) { return; }
+ if ( gConfig.shouldSave && ! gConfig.shouldSave() ) { return; }
+
+ clearTimeout( saveDebounceTimer );
+ saveDebounceTimer = setTimeout( function() {
+ if ( ! gSvgElement ) { return; }
+ var viewBoxStr = $( gSvgElement ).attr( 'viewBox' );
+ var saveData = { viewBoxStr: viewBoxStr };
+
+ if ( gConfig.enableCanvasRotation ) {
+ var transform = $( gSvgElement ).attr( 'transform' ) || '';
+ var parsed = Hi.svgUtils.getSvgTransformValues( transform );
+ saveData.rotationAngle = parsed.rotate.angle;
+ }
+
+ gConfig.onSave( saveData );
+ lastSaveTime = Date.now();
+ }, ZOOM_SAVE_DEBOUNCE_MS );
+ }
+
+})();
diff --git a/src/hi/static/js/svg-path-core.js b/src/hi/static/js/svg-path-core.js
new file mode 100644
index 00000000..aa46758b
--- /dev/null
+++ b/src/hi/static/js/svg-path-core.js
@@ -0,0 +1,951 @@
+/*
+ SVG Path Core
+
+ Provides proxy-point-based path editing for open and closed SVG paths.
+ Initialized with a configuration object. See DEFAULT_CONFIG for all
+ available options and their defaults.
+*/
+
+(function() {
+
+ window.Hi = window.Hi || {};
+ window.Hi.svgUtils = window.Hi.svgUtils || {};
+
+ const MODULE_NAME = 'svg-path-core';
+
+ const PROXY_PATH_CONTAINER_ID = 'hi-proxy-path-container';
+ const PROXY_PATH_CLASS = 'hi-proxy-path';
+ const PROXY_PATH_GROUP_SELECTOR = 'g.' + PROXY_PATH_CLASS;
+ const PROXY_POINTS_CLASS = 'hi-proxy-points';
+ const PROXY_POINTS_GROUP_SELECTOR = 'g.' + PROXY_POINTS_CLASS;
+ const PROXY_LINES_CLASS = 'hi-proxy-lines';
+ const PROXY_LINES_GROUP_SELECTOR = 'g.' + PROXY_LINES_CLASS;
+ const PROXY_ITEM_CLASS = 'proxy';
+ const PROXY_POINT_CLASS = 'proxy-point';
+ const PROXY_LINE_CLASS = 'proxy-line';
+ const PROXY_POINT_SELECTOR = 'circle.' + PROXY_POINT_CLASS;
+ const PROXY_LINE_SELECTOR = 'line.' + PROXY_LINE_CLASS;
+ const PROXY_PATH_TYPE_ATTR = 'hi-proxy-path-type';
+ const BEFORE_PROXY_POINT_ID = 'before-proxy-point-id';
+ const AFTER_PROXY_POINT_ID = 'after-proxy-point-id';
+
+ const PATH_ACTION_DELETE_KEY_CODES = [ 88, 8, 46 ]; // x, Backspace, Delete
+ const PATH_ACTION_INSERT_KEY_CODES = [ 73, 45 ]; // i, Insert
+ const PATH_ACTION_ADD_KEY_CODES = [ 65, 61 ]; // a, +
+ const PATH_ACTION_END_KEY_CODES = [ 27 ]; // Escape
+
+ const CURSOR_MOVEMENT_THRESHOLD_PIXELS = 3;
+ const PATH_EDIT_PROXY_POINT_RADIUS_PIXELS = 8;
+ const PATH_EDIT_PROXY_LINE_WIDTH_PIXELS = 5;
+ const PATH_EDIT_NEW_PATH_RADIUS_PERCENT = 5;
+ const PATH_EDIT_PROXY_LINE_COLOR = 'red';
+ const PATH_EDIT_PROXY_POINT_COLOR = 'red';
+
+ const ProxyPathType = {
+ OPEN: 'open',
+ CLOSED: 'closed',
+ };
+
+ var DEFAULT_CONFIG = {
+ identifyElement: null, /* function(event) — return SVG group element or null */
+ onSelect: null, /* function(element) — called on path selection */
+ onDeselect: null, /* function() — called when selection is cleared */
+ onSave: null, /* function(element, svgPathString) — called after path changes */
+ onDeleteAll: null, /* function() — called after entire element deletion */
+ baseSvgSelector: null, /* CSS selector for the containing SVG element */
+ highlightClass: 'highlighted', /* CSS class for selected proxy elements */
+ allowDeleteAll: false, /* allow delete key to remove entire element */
+ };
+
+ let gConfig = null;
+ let gSelectedPathSvgGroup = null;
+ let gSvgPathEditData = null;
+ let gDragData = null;
+ let gIgnoreClick = false;
+
+ let uniqueIdCounter = 0;
+
+ function generateUniqueId() {
+ uniqueIdCounter += 1;
+ return 'svg-path-core-' + uniqueIdCounter + '-' + Date.now();
+ }
+
+ const HiSvgPathCore = {
+
+ init: function( config ) {
+ gConfig = $.extend( {}, DEFAULT_CONFIG, config );
+ },
+
+ handleSinglePointerEventStart: function( singlePointerEvent ) {
+ return _handleSinglePointerEventStart( singlePointerEvent );
+ },
+
+ handleSinglePointerEventMove: function( singlePointerEvent ) {
+ return _handleSinglePointerEventMove( singlePointerEvent );
+ },
+
+ handleSinglePointerEventEnd: function( singlePointerEvent ) {
+ return _handleSinglePointerEventEnd( singlePointerEvent );
+ },
+
+ handleClick: function( event ) {
+ return _handleClick( event );
+ },
+
+ handleKeyDown: function( event ) {
+ return _handleKeyDown( event );
+ },
+
+ clearSelection: function() {
+ clearSelectedPathSvgGroup();
+ },
+
+ hasSelection: function() {
+ return gSelectedPathSvgGroup !== null;
+ },
+
+ PROXY_PATH_CONTAINER_ID: PROXY_PATH_CONTAINER_ID,
+
+ deleteSelectedElement: function() {
+ if ( ! gSelectedPathSvgGroup ) { return; }
+ /* Remove proxy editing UI. */
+ var proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
+ $( proxyPathContainer ).remove();
+ /* Remove the actual element. */
+ var element = gSelectedPathSvgGroup;
+ gSelectedPathSvgGroup = null;
+ gSvgPathEditData = null;
+ $( element ).remove();
+ },
+ };
+
+ window.Hi.SvgPathCore = HiSvgPathCore;
+
+ /* ==================== */
+ /* Pointer Event Handling */
+ /* ==================== */
+
+ function _handleSinglePointerEventStart( singlePointerEvent ) {
+ if ( ! gSvgPathEditData ) { return false; }
+
+ var target = singlePointerEvent.start.event.target;
+ if ( ! $( target ).hasClass( PROXY_POINT_CLASS ) ) { return false; }
+
+ var baseSvgElement = $( gConfig.baseSvgSelector );
+ var eventSvgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement,
+ singlePointerEvent.start.x,
+ singlePointerEvent.start.y );
+
+ var proxyPoint = target;
+ var offsetX = eventSvgPoint.x - parseFloat( $( proxyPoint ).attr( 'cx' ) );
+ var offsetY = eventSvgPoint.y - parseFloat( $( proxyPoint ).attr( 'cy' ) );
+
+ var beforeProxyLine = getPrecedingProxyLine( proxyPoint );
+ var afterProxyLine = getFollowingProxyLine( proxyPoint );
+
+ gDragData = {
+ proxyPoint: proxyPoint,
+ baseSvgElement: baseSvgElement,
+ offsetX: offsetX,
+ offsetY: offsetY,
+ beforeProxyLine: beforeProxyLine,
+ afterProxyLine: afterProxyLine,
+ isDragging: false,
+ lastSvgPoint: null,
+ };
+ return true;
+ }
+
+ function _handleSinglePointerEventMove( singlePointerEvent ) {
+ if ( ! gDragData ) { return false; }
+
+ var baseSvgElement = gDragData.baseSvgElement;
+ var eventSvgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement,
+ singlePointerEvent.last.x,
+ singlePointerEvent.last.y );
+
+ var distanceX = Math.abs( singlePointerEvent.last.x - singlePointerEvent.start.x );
+ var distanceY = Math.abs( singlePointerEvent.last.y - singlePointerEvent.start.y );
+
+ if ( ! gDragData.isDragging
+ && distanceX <= CURSOR_MOVEMENT_THRESHOLD_PIXELS
+ && distanceY <= CURSOR_MOVEMENT_THRESHOLD_PIXELS ) {
+ return true;
+ }
+
+ gDragData.isDragging = true;
+ gSvgPathEditData.dragProxyPoint = gDragData.proxyPoint;
+
+ var proxyPoint = gDragData.proxyPoint;
+ var lastEvent = singlePointerEvent.last.event;
+ var ctrlKey = lastEvent ? lastEvent.ctrlKey : false;
+ var shiftHeld = lastEvent ? lastEvent.shiftKey : false;
+
+ if ( ctrlKey ) {
+ if ( ! gDragData.lastSvgPoint ) {
+ gDragData.lastSvgPoint = {
+ x: eventSvgPoint.x - gDragData.offsetX,
+ y: eventSvgPoint.y - gDragData.offsetY,
+ };
+ }
+ var newPos = {
+ x: Hi.svgUtils.snapToGrid( baseSvgElement, eventSvgPoint.x - gDragData.offsetX, shiftHeld ),
+ y: Hi.svgUtils.snapToGrid( baseSvgElement, eventSvgPoint.y - gDragData.offsetY, shiftHeld ),
+ };
+ var deltaCx = newPos.x - gDragData.lastSvgPoint.x;
+ var deltaCy = newPos.y - gDragData.lastSvgPoint.y;
+ gDragData.lastSvgPoint = newPos;
+ moveAllProxyPoints( deltaCx, deltaCy );
+ setActionStateAttr( 'move' );
+ } else {
+ var newCx = Hi.svgUtils.snapToGrid( baseSvgElement, eventSvgPoint.x - gDragData.offsetX, shiftHeld );
+ var newCy = Hi.svgUtils.snapToGrid( baseSvgElement, eventSvgPoint.y - gDragData.offsetY, shiftHeld );
+ $( proxyPoint ).attr( 'cx', newCx ).attr( 'cy', newCy );
+
+ if ( gDragData.beforeProxyLine.length > 0 ) {
+ gDragData.beforeProxyLine.attr( 'x2', newCx ).attr( 'y2', newCy );
+ }
+ if ( gDragData.afterProxyLine.length > 0 ) {
+ gDragData.afterProxyLine.attr( 'x1', newCx ).attr( 'y1', newCy );
+ }
+ setActionStateAttr( '' );
+ }
+
+ setSelectedProxyElement( proxyPoint );
+ return true;
+ }
+
+ function _handleSinglePointerEventEnd( singlePointerEvent ) {
+ if ( ! gDragData ) { return false; }
+
+ saveSvgPath();
+ gSvgPathEditData.dragProxyPoint = null;
+ setActionStateAttr( '' );
+ if ( gDragData.isDragging ) {
+ gIgnoreClick = true;
+ }
+ gDragData = null;
+ return true;
+ }
+
+ /* ==================== */
+ /* Click Handling */
+ /* ==================== */
+
+ function _handleClick( event ) {
+ if ( gSelectedPathSvgGroup && gIgnoreClick ) {
+ gIgnoreClick = false;
+ return true;
+ }
+ gIgnoreClick = false;
+
+ /* Check if clicked on a path element. */
+ var element = gConfig.identifyElement( event );
+ var handled = false;
+ if ( element ) {
+ handleSvgPathClick( event, element );
+ handled = true;
+ }
+
+ /* If a path is being edited, check for proxy element clicks or extension clicks. */
+ if ( ! handled && gSelectedPathSvgGroup ) {
+ var baseSvg = $( gConfig.baseSvgSelector );
+ if ( $( event.target ).closest( baseSvg ).length > 0 ) {
+ handleProxyPathClick( event );
+ handled = true;
+ }
+ }
+
+ return handled;
+ }
+
+ /* ==================== */
+ /* KeyDown Handling */
+ /* ==================== */
+
+ function _handleKeyDown( event ) {
+ if ( $( event.target ).is( 'input[type="text"], textarea' ) ) { return false; }
+ if ( $( event.target ).closest( '.modal' ).length > 0 ) { return false; }
+ if ( ! gSvgPathEditData ) { return false; }
+
+ if ( PATH_ACTION_ADD_KEY_CODES.indexOf( event.keyCode ) >= 0 ) {
+ addProxyPath();
+ return true;
+
+ } else if ( PATH_ACTION_END_KEY_CODES.indexOf( event.keyCode ) >= 0 ) {
+ clearSelectedPathSvgGroup();
+ return true;
+
+ } else {
+ if ( ! gSvgPathEditData.selectedProxyElement ) {
+ if ( PATH_ACTION_DELETE_KEY_CODES.indexOf( event.keyCode ) >= 0
+ && gConfig.allowDeleteAll ) {
+ deleteEntireElement();
+ return true;
+ }
+ return false;
+ }
+
+ if ( PATH_ACTION_DELETE_KEY_CODES.indexOf( event.keyCode ) >= 0 ) {
+ 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.indexOf( event.keyCode ) >= 0 ) {
+ if ( $( gSvgPathEditData.selectedProxyElement ).hasClass( PROXY_LINE_CLASS ) ) {
+ divideProxyLine( gSvgPathEditData.selectedProxyElement );
+ return true;
+ } else if ( $( gSvgPathEditData.selectedProxyElement ).hasClass( PROXY_POINT_CLASS ) ) {
+ var svgProxyLine = getPrecedingProxyLine( gSvgPathEditData.selectedProxyElement );
+ if ( svgProxyLine.length > 0 ) {
+ divideProxyLine( svgProxyLine );
+ return true;
+ } else {
+ svgProxyLine = getFollowingProxyLine( gSvgPathEditData.selectedProxyElement );
+ if ( svgProxyLine.length > 0 ) {
+ divideProxyLine( svgProxyLine );
+ return true;
+ }
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ /* ==================== */
+ /* Selection */
+ /* ==================== */
+
+ function handleSvgPathClick( event, element ) {
+ clearSelectedPathSvgGroup();
+ gSelectedPathSvgGroup = $( element );
+ expandSvgPath( gSelectedPathSvgGroup );
+ if ( gConfig.onSelect ) {
+ gConfig.onSelect( element );
+ }
+ }
+
+ function clearSelectedPathSvgGroup() {
+ if ( gSelectedPathSvgGroup ) {
+ collapseSvgPath();
+ gSelectedPathSvgGroup = null;
+ if ( gConfig.onDeselect ) {
+ gConfig.onDeselect();
+ }
+ }
+ }
+
+ function handleProxyPathClick( event ) {
+ var 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( gConfig.highlightClass || 'highlighted' );
+ if ( proxyElement ) {
+ $( proxyElement ).addClass( gConfig.highlightClass || 'highlighted' );
+ }
+ gSvgPathEditData.selectedProxyElement = proxyElement;
+ }
+
+ /* ==================== */
+ /* Expand / Collapse */
+ /* ==================== */
+
+ function expandSvgPath( pathSvgGroup ) {
+ pathSvgGroup.hide();
+
+ var baseSvgElement = $( gConfig.baseSvgSelector )[0];
+ var 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,
+ };
+
+ var svgPathElement = $( pathSvgGroup ).find( 'path' ).not( '.hi-bg-hit-area' );
+ var pathData = svgPathElement.attr( 'd' );
+ var segments = pathData.match( /[ML][^MLZ]+|Z/g );
+
+ /* Create all proxy points. */
+ var currentProxyPathGroup = null;
+ for ( var i = 0; i < segments.length; i++ ) {
+ var command = segments[i].charAt(0);
+ var coords = segments[i].substring(1).trim().split( /[\s,]+/ ).map( Number );
+
+ if ( command === 'M' ) {
+ currentProxyPathGroup = createProxyPathGroup( ProxyPathType.OPEN );
+ $( proxyPathContainer ).append( currentProxyPathGroup );
+ var newProxyPoint = createProxyPathProxyPoint( coords[0], coords[1] );
+ $( currentProxyPathGroup ).find( PROXY_POINTS_GROUP_SELECTOR ).append( newProxyPoint );
+
+ } else if ( command === 'L' && currentProxyPathGroup ) {
+ var 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;
+ }
+ }
+
+ /* Create lines and event handlers. */
+ $( proxyPathContainer ).find( PROXY_PATH_GROUP_SELECTOR ).each( function( index, proxyPathGroup ) {
+ var previousProxyPoint = null;
+ var firstLine = null;
+ var previousLine = null;
+
+ var proxyLinesGroup = $( proxyPathGroup ).find( PROXY_LINES_GROUP_SELECTOR );
+ var proxyPoints = $( proxyPathGroup ).find( PROXY_POINT_SELECTOR );
+
+ $( proxyPoints ).each( function( index, currentProxyPoint ) {
+ if ( previousProxyPoint ) {
+ var x1 = parseFloat( previousProxyPoint.getAttribute( 'cx' ) );
+ var y1 = parseFloat( previousProxyPoint.getAttribute( 'cy' ) );
+ var x2 = parseFloat( currentProxyPoint.getAttribute( 'cx' ) );
+ var y2 = parseFloat( currentProxyPoint.getAttribute( 'cy' ) );
+ var 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;
+ });
+
+ if ( proxyPoints.length < 2 ) {
+ addProxyPointEventHandler( previousProxyPoint, null, null );
+ return;
+ }
+
+ var firstProxyPoint = proxyPoints[0];
+ var lastProxyPoint = proxyPoints[ proxyPoints.length - 1 ];
+
+ if ( $( proxyPathGroup ).attr( PROXY_PATH_TYPE_ATTR ) === ProxyPathType.OPEN ) {
+ addProxyPointEventHandler( firstProxyPoint, null, firstLine );
+ addProxyPointEventHandler( lastProxyPoint, previousLine, null );
+ } else {
+ var x1 = parseFloat( lastProxyPoint.getAttribute( 'cx' ) );
+ var y1 = parseFloat( lastProxyPoint.getAttribute( 'cy' ) );
+ var x2 = parseFloat( firstProxyPoint.getAttribute( 'cx' ) );
+ var y2 = parseFloat( firstProxyPoint.getAttribute( 'cy' ) );
+ var closureLine = createProxyPathLine( lastProxyPoint, firstProxyPoint,
+ x1, y1, x2, y2 );
+ $( proxyLinesGroup ).append( closureLine );
+ addProxyPointEventHandler( firstProxyPoint, closureLine, firstLine );
+ addProxyPointEventHandler( lastProxyPoint, previousLine, closureLine );
+ }
+ });
+ }
+
+ function collapseSvgPath() {
+ var newSvgPath = getSvgPathStringFromProxyPaths();
+ $( gSelectedPathSvgGroup ).find( 'path' ).not( '.hi-bg-hit-area' ).attr( 'd', newSvgPath );
+
+ /* Also update the hit-area path if present. */
+ var hitAreaPath = $( gSelectedPathSvgGroup ).find( 'path.hi-bg-hit-area' );
+ if ( hitAreaPath.length > 0 ) {
+ hitAreaPath.attr( 'd', newSvgPath );
+ }
+
+ var proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
+ $( proxyPathContainer ).remove();
+
+ gSelectedPathSvgGroup.show();
+ gSvgPathEditData = null;
+ }
+
+ /* ==================== */
+ /* Extend Path */
+ /* ==================== */
+
+ function extendProxyPath( event ) {
+ var baseSvgElement = $( gConfig.baseSvgSelector );
+ var svgViewBox = Hi.svgUtils.getSvgViewBox( baseSvgElement );
+ var svgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement, event.clientX, event.clientY );
+
+ if ( svgPoint.x < svgViewBox.x
+ || svgPoint.x > ( svgViewBox.x + svgViewBox.width )
+ || svgPoint.y < svgViewBox.y
+ || svgPoint.y > ( svgViewBox.y + svgViewBox.height ) ) {
+ return;
+ }
+
+ var referenceElement = getReferenceElementForExtendingProxyPath();
+ var proxyPathGroup = $( referenceElement ).closest( PROXY_PATH_GROUP_SELECTOR );
+ var 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 {
+ var followingProxyLine = getFollowingProxyLine( referenceElement );
+ newProxyPoint = insertNewProxyPoint( svgPoint, followingProxyLine );
+ }
+ } else if ( $( referenceElement ).hasClass( PROXY_LINE_CLASS ) ) {
+ newProxyPoint = insertNewProxyPoint( svgPoint, referenceElement );
+ }
+
+ if ( newProxyPoint ) {
+ setSelectedProxyElement( newProxyPoint );
+ saveSvgPath();
+ }
+ }
+
+ /* ==================== */
+ /* Add / Insert Points */
+ /* ==================== */
+
+ function prependNewProxyPoint( newSvgPoint, proxyPathGroup ) {
+ var firstProxyPoint = proxyPathGroup.find( PROXY_POINT_SELECTOR ).first();
+ var firstLine = proxyPathGroup.find( PROXY_LINE_SELECTOR ).first();
+
+ var firstX = parseFloat( $( firstProxyPoint ).attr( 'cx' ) );
+ var firstY = parseFloat( $( firstProxyPoint ).attr( 'cy' ) );
+
+ var newProxyPoint = createProxyPathProxyPoint( newSvgPoint.x, newSvgPoint.y );
+ var newLine = createProxyPathLine( newProxyPoint, firstProxyPoint,
+ newSvgPoint.x, newSvgPoint.y, firstX, firstY );
+
+ var proxyPointsGroup = $( proxyPathGroup ).find( PROXY_POINTS_GROUP_SELECTOR );
+ var proxyLinesGroup = $( proxyPathGroup ).find( PROXY_LINES_GROUP_SELECTOR );
+ $( proxyPointsGroup ).prepend( newProxyPoint );
+ $( proxyLinesGroup ).prepend( newLine );
+
+ $( firstProxyPoint ).off();
+ addProxyPointEventHandler( firstProxyPoint, newLine, firstLine );
+ addProxyPointEventHandler( newProxyPoint, null, newLine );
+
+ return newProxyPoint;
+ }
+
+ function appendNewProxyPoint( newSvgPoint, proxyPathGroup ) {
+ var lastProxyPoint = proxyPathGroup.find( PROXY_POINT_SELECTOR ).last();
+ var lastLine = proxyPathGroup.find( PROXY_LINE_SELECTOR ).last();
+
+ var lastX = parseFloat( $( lastProxyPoint ).attr( 'cx' ) );
+ var lastY = parseFloat( $( lastProxyPoint ).attr( 'cy' ) );
+
+ var newProxyPoint = createProxyPathProxyPoint( newSvgPoint.x, newSvgPoint.y );
+ var newLine = createProxyPathLine( lastProxyPoint, newProxyPoint,
+ lastX, lastY, newSvgPoint.x, newSvgPoint.y );
+
+ var proxyPointsGroup = $( proxyPathGroup ).find( PROXY_POINTS_GROUP_SELECTOR );
+ var proxyLinesGroup = $( proxyPathGroup ).find( PROXY_LINES_GROUP_SELECTOR );
+ $( proxyPointsGroup ).append( newProxyPoint );
+ $( proxyLinesGroup ).append( newLine );
+
+ $( lastProxyPoint ).off();
+ addProxyPointEventHandler( lastProxyPoint, lastLine, newLine );
+ addProxyPointEventHandler( newProxyPoint, newLine, null );
+
+ return newProxyPoint;
+ }
+
+ function insertNewProxyPoint( newSvgPoint, referenceProxyLine ) {
+ var beforeProxyPointId = $( referenceProxyLine ).attr( BEFORE_PROXY_POINT_ID );
+ var afterProxyPointId = $( referenceProxyLine ).attr( AFTER_PROXY_POINT_ID );
+
+ var beforeProxyPoint = $( '#' + beforeProxyPointId );
+ var afterProxyPoint = $( '#' + afterProxyPointId );
+ var followingProxyLine = getFollowingProxyLine( afterProxyPoint );
+
+ var afterX = parseFloat( $( afterProxyPoint ).attr( 'cx' ) );
+ var afterY = parseFloat( $( afterProxyPoint ).attr( 'cy' ) );
+
+ var newProxyPoint = createProxyPathProxyPoint( newSvgPoint.x, newSvgPoint.y );
+ var 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 );
+
+ $( beforeProxyPoint ).after( newProxyPoint );
+ $( referenceProxyLine ).after( newLine );
+
+ $( afterProxyPoint ).off();
+ addProxyPointEventHandler( afterProxyPoint, newLine, followingProxyLine );
+ addProxyPointEventHandler( newProxyPoint, referenceProxyLine, newLine );
+
+ return newProxyPoint;
+ }
+
+ /* ==================== */
+ /* Delete Entire Element */
+ /* ==================== */
+
+ function deleteEntireElement() {
+ if ( ! gSelectedPathSvgGroup ) { return; }
+ var proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
+ $( proxyPathContainer ).remove();
+ var element = gSelectedPathSvgGroup;
+ gSelectedPathSvgGroup = null;
+ gSvgPathEditData = null;
+ $( element ).remove();
+ if ( gConfig.onDeleteAll ) {
+ gConfig.onDeleteAll();
+ }
+ }
+
+ /* ==================== */
+ /* Delete Points */
+ /* ==================== */
+
+ function deleteProxyPoint( svgProxyPoint ) {
+ var proxyPathGroup = $( svgProxyPoint ).closest( PROXY_PATH_GROUP_SELECTOR );
+ var proxyPathType = $( proxyPathGroup ).attr( PROXY_PATH_TYPE_ATTR );
+ var proxyPointsGroup = $( svgProxyPoint ).closest( PROXY_POINTS_GROUP_SELECTOR );
+ var minPoints = ( proxyPathType === ProxyPathType.CLOSED ) ? 3 : 2;
+
+ if ( $( proxyPointsGroup ).children().length <= minPoints ) {
+ removeProxyPathIfAllowed( proxyPathGroup );
+ return;
+ }
+
+ var beforeProxyLine = getPrecedingProxyLine( svgProxyPoint );
+ var afterProxyLine = getFollowingProxyLine( svgProxyPoint );
+
+ if ( beforeProxyLine.length > 0 && afterProxyLine.length > 0 ) {
+ var afterProxyPointId = $( afterProxyLine ).attr( AFTER_PROXY_POINT_ID );
+ var afterProxyPoint = $( '#' + afterProxyPointId );
+ var followingProxyLine = getFollowingProxyLine( afterProxyPoint );
+
+ var afterX = parseFloat( $( afterProxyPoint ).attr( 'cx' ) );
+ var afterY = parseFloat( $( afterProxyPoint ).attr( 'cy' ) );
+ $( beforeProxyLine ).attr( AFTER_PROXY_POINT_ID, $( afterProxyPoint ).attr( 'id' ) );
+ $( beforeProxyLine ).attr( 'x2', afterX );
+ $( beforeProxyLine ).attr( 'y2', afterY );
+
+ $( afterProxyPoint ).off();
+ addProxyPointEventHandler( afterProxyPoint, beforeProxyLine, followingProxyLine );
+
+ $( svgProxyPoint ).remove();
+ $( afterProxyLine ).remove();
+ setSelectedProxyElement( afterProxyPoint );
+
+ } else if ( afterProxyLine.length > 0 ) {
+ var afterProxyPointId = $( afterProxyLine ).attr( AFTER_PROXY_POINT_ID );
+ var afterProxyPoint = $( '#' + afterProxyPointId );
+ var followingProxyLine = getFollowingProxyLine( afterProxyPoint );
+
+ $( afterProxyPoint ).off();
+ addProxyPointEventHandler( afterProxyPoint, null, followingProxyLine );
+
+ $( svgProxyPoint ).remove();
+ $( afterProxyLine ).remove();
+ setSelectedProxyElement( afterProxyPoint );
+
+ } else if ( beforeProxyLine.length > 0 ) {
+ var beforeProxyPointId = $( beforeProxyLine ).attr( BEFORE_PROXY_POINT_ID );
+ var beforeProxyPoint = $( '#' + beforeProxyPointId );
+ var precedingProxyLine = getPrecedingProxyLine( beforeProxyPoint );
+
+ $( beforeProxyPoint ).off();
+ addProxyPointEventHandler( beforeProxyPoint, precedingProxyLine, null );
+
+ $( svgProxyPoint ).remove();
+ $( beforeProxyLine ).remove();
+ setSelectedProxyElement( beforeProxyPoint );
+
+ } else {
+ $( svgProxyPoint ).remove();
+ setSelectedProxyElement( null );
+ }
+
+ saveSvgPath();
+ }
+
+ function deleteProxyLine( svgProxyLine ) {
+ var beforeProxyPointId = $( svgProxyLine ).attr( BEFORE_PROXY_POINT_ID );
+ var beforeProxyPoint = $( '#' + beforeProxyPointId );
+ deleteProxyPoint( beforeProxyPoint );
+ }
+
+ function divideProxyLine( svgProxyLine ) {
+ var beforeProxyPointId = $( svgProxyLine ).attr( BEFORE_PROXY_POINT_ID );
+ var afterProxyPointId = $( svgProxyLine ).attr( AFTER_PROXY_POINT_ID );
+ var beforeProxyPoint = $( '#' + beforeProxyPointId );
+ var afterProxyPoint = $( '#' + afterProxyPointId );
+
+ var beforeX = parseFloat( $( beforeProxyPoint ).attr( 'cx' ) );
+ var beforeY = parseFloat( $( beforeProxyPoint ).attr( 'cy' ) );
+ var afterX = parseFloat( $( afterProxyPoint ).attr( 'cx' ) );
+ var afterY = parseFloat( $( afterProxyPoint ).attr( 'cy' ) );
+
+ var midSvgPoint = {
+ x: ( beforeX + afterX ) / 2,
+ y: ( beforeY + afterY ) / 2,
+ };
+ insertNewProxyPoint( midSvgPoint, svgProxyLine );
+ saveSvgPath();
+ }
+
+ /* ==================== */
+ /* Add Path Segment */
+ /* ==================== */
+
+ function addProxyPath() {
+ var proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
+ var firstProxyPath = $( proxyPathContainer ).find( PROXY_PATH_GROUP_SELECTOR ).first();
+ var proxyPathType = $( firstProxyPath ).attr( PROXY_PATH_TYPE_ATTR );
+ var newProxyPathGroup = createProxyPathGroup( proxyPathType );
+ $( proxyPathContainer ).append( newProxyPathGroup );
+
+ var baseSvgElement = $( gConfig.baseSvgSelector );
+ var svgViewBox = Hi.svgUtils.getSvgViewBox( baseSvgElement );
+ var svgCenter = {
+ x: svgViewBox.x + ( svgViewBox.width / 2 ),
+ y: svgViewBox.y + ( svgViewBox.height / 2 ),
+ };
+ var svgUnitRadius = {
+ x: svgViewBox.width * ( PATH_EDIT_NEW_PATH_RADIUS_PERCENT / 100.0 ),
+ y: svgViewBox.height * ( PATH_EDIT_NEW_PATH_RADIUS_PERCENT / 100.0 ),
+ };
+
+ var proxyPointsGroup = $( newProxyPathGroup ).find( PROXY_POINTS_GROUP_SELECTOR );
+ var proxyLinesGroup = $( newProxyPathGroup ).find( PROXY_LINES_GROUP_SELECTOR );
+
+ if ( proxyPathType === ProxyPathType.OPEN ) {
+ var leftPoint = { x: svgCenter.x - svgUnitRadius.x, y: svgCenter.y };
+ var rightPoint = { x: svgCenter.x + svgUnitRadius.x, y: svgCenter.y };
+
+ var beforePP = createProxyPathProxyPoint( leftPoint.x, leftPoint.y );
+ var afterPP = createProxyPathProxyPoint( rightPoint.x, rightPoint.y );
+ proxyPointsGroup.append( beforePP );
+ proxyPointsGroup.append( afterPP );
+
+ var newLine = createProxyPathLine( beforePP, afterPP,
+ leftPoint.x, leftPoint.y, rightPoint.x, rightPoint.y );
+ $( proxyLinesGroup ).append( newLine );
+
+ addProxyPointEventHandler( beforePP, null, newLine );
+ addProxyPointEventHandler( afterPP, newLine, null );
+
+ } else if ( proxyPathType === ProxyPathType.CLOSED ) {
+ var tl = { x: svgCenter.x - svgUnitRadius.x, y: svgCenter.y - svgUnitRadius.y };
+ var tr = { x: svgCenter.x + svgUnitRadius.x, y: svgCenter.y - svgUnitRadius.y };
+ var br = { x: svgCenter.x + svgUnitRadius.x, y: svgCenter.y + svgUnitRadius.y };
+ var bl = { x: svgCenter.x - svgUnitRadius.x, y: svgCenter.y + svgUnitRadius.y };
+
+ var tlPP = createProxyPathProxyPoint( tl.x, tl.y );
+ var trPP = createProxyPathProxyPoint( tr.x, tr.y );
+ var brPP = createProxyPathProxyPoint( br.x, br.y );
+ var blPP = createProxyPathProxyPoint( bl.x, bl.y );
+ proxyPointsGroup.append( tlPP );
+ proxyPointsGroup.append( trPP );
+ proxyPointsGroup.append( brPP );
+ proxyPointsGroup.append( blPP );
+
+ var topLine = createProxyPathLine( tlPP, trPP, tl.x, tl.y, tr.x, tr.y );
+ var rightLine = createProxyPathLine( trPP, brPP, tr.x, tr.y, br.x, br.y );
+ var bottomLine = createProxyPathLine( brPP, blPP, br.x, br.y, bl.x, bl.y );
+ var leftLine = createProxyPathLine( blPP, tlPP, bl.x, bl.y, tl.x, tl.y );
+ $( proxyLinesGroup ).append( topLine );
+ $( proxyLinesGroup ).append( rightLine );
+ $( proxyLinesGroup ).append( bottomLine );
+ $( proxyLinesGroup ).append( leftLine );
+
+ addProxyPointEventHandler( tlPP, leftLine, topLine );
+ addProxyPointEventHandler( trPP, topLine, rightLine );
+ addProxyPointEventHandler( brPP, rightLine, bottomLine );
+ addProxyPointEventHandler( blPP, bottomLine, leftLine );
+ }
+ saveSvgPath();
+ }
+
+ function removeProxyPathIfAllowed( targetProxyPathGroup ) {
+ var proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
+ var proxyPathGroups = $( proxyPathContainer ).find( PROXY_PATH_GROUP_SELECTOR );
+ if ( proxyPathGroups.length < 2 ) {
+ if ( gConfig.allowDeleteAll ) {
+ deleteEntireElement();
+ }
+ return;
+ }
+ $( targetProxyPathGroup ).remove();
+ setSelectedProxyElement( null );
+ saveSvgPath();
+ }
+
+ /* ==================== */
+ /* Create Proxy Items */
+ /* ==================== */
+
+ function createProxyPathGroup( proxyPathType ) {
+ var group = document.createElementNS( 'http://www.w3.org/2000/svg', 'g' );
+ group.setAttribute( 'id', generateUniqueId() );
+ group.setAttribute( 'class', PROXY_PATH_CLASS );
+ group.setAttribute( PROXY_PATH_TYPE_ATTR, proxyPathType );
+
+ var linesGroup = document.createElementNS( 'http://www.w3.org/2000/svg', 'g' );
+ linesGroup.setAttribute( 'class', PROXY_LINES_CLASS );
+ group.appendChild( linesGroup );
+
+ var pointsGroup = document.createElementNS( 'http://www.w3.org/2000/svg', 'g' );
+ pointsGroup.setAttribute( 'class', PROXY_POINTS_CLASS );
+ group.appendChild( pointsGroup );
+
+ return group;
+ }
+
+ function createProxyPathProxyPoint( cx, cy ) {
+ var baseSvgElement = $( gConfig.baseSvgSelector );
+ var pixelsPerSvgUnit = Hi.svgUtils.getPixelsPerSvgUnit( baseSvgElement );
+ var svgRadius = PATH_EDIT_PROXY_POINT_RADIUS_PIXELS / pixelsPerSvgUnit.scaleX;
+
+ var point = document.createElementNS( 'http://www.w3.org/2000/svg', 'circle' );
+ point.setAttribute( 'cx', cx );
+ point.setAttribute( 'cy', cy );
+ point.setAttribute( 'r', svgRadius );
+ point.setAttribute( 'id', generateUniqueId() );
+ $( point ).addClass( 'draggable' );
+ $( point ).addClass( PROXY_ITEM_CLASS );
+ $( point ).addClass( PROXY_POINT_CLASS );
+ point.setAttribute( 'fill', PATH_EDIT_PROXY_POINT_COLOR );
+ point.setAttribute( 'vector-effect', 'non-scaling-stroke' );
+ return point;
+ }
+
+ function createProxyPathLine( beforeProxyPoint, afterProxyPoint, x1, y1, x2, y2 ) {
+ var line = document.createElementNS( 'http://www.w3.org/2000/svg', 'line' );
+ line.setAttribute( 'x1', x1 );
+ line.setAttribute( 'y1', y1 );
+ line.setAttribute( 'x2', x2 );
+ line.setAttribute( 'y2', y2 );
+ $( line ).addClass( PROXY_ITEM_CLASS );
+ $( line ).addClass( PROXY_LINE_CLASS );
+ line.setAttribute( BEFORE_PROXY_POINT_ID, $( beforeProxyPoint ).attr( 'id' ) );
+ line.setAttribute( AFTER_PROXY_POINT_ID, $( afterProxyPoint ).attr( 'id' ) );
+ line.setAttribute( 'stroke', PATH_EDIT_PROXY_LINE_COLOR );
+ line.setAttribute( 'stroke-width', PATH_EDIT_PROXY_LINE_WIDTH_PIXELS );
+ line.setAttribute( 'vector-effect', 'non-scaling-stroke' );
+ return line;
+ }
+
+ /* ==================== */
+ /* Proxy Point Drag */
+ /* ==================== */
+
+ function addProxyPointEventHandler( proxyPoint, beforeProxyLine, afterProxyLine ) {
+ /* Proxy point drag is now handled via the centralized pointer event
+ dispatch in svg-bg-event-listeners.js. This function is retained for
+ the call sites that set up proxy point structure, but no longer
+ attaches per-element mouse handlers. */
+ }
+
+ /* ==================== */
+ /* Whole Path Move */
+ /* ==================== */
+
+ function moveAllProxyPoints( deltaCx, deltaCy ) {
+ if ( ! gSvgPathEditData || ! gSvgPathEditData.proxyPathContainer ) { return; }
+
+ var proxyPoints = $( gSvgPathEditData.proxyPathContainer ).find( PROXY_POINT_SELECTOR );
+ proxyPoints.each( function() {
+ var cx = parseFloat( $( this ).attr( 'cx' ) ) + deltaCx;
+ var cy = parseFloat( $( this ).attr( 'cy' ) ) + deltaCy;
+ $( this ).attr( 'cx', cx ).attr( 'cy', cy );
+ });
+
+ var proxyLines = $( gSvgPathEditData.proxyPathContainer ).find( PROXY_LINE_SELECTOR );
+ proxyLines.each( function() {
+ $( this ).attr( 'x1', parseFloat( $( this ).attr( 'x1' ) ) + deltaCx );
+ $( this ).attr( 'y1', parseFloat( $( this ).attr( 'y1' ) ) + deltaCy );
+ $( this ).attr( 'x2', parseFloat( $( this ).attr( 'x2' ) ) + deltaCx );
+ $( this ).attr( 'y2', parseFloat( $( this ).attr( 'y2' ) ) + deltaCy );
+ });
+ }
+
+ function setActionStateAttr( actionState ) {
+ if ( gConfig && gConfig.baseSvgSelector ) {
+ $( gConfig.baseSvgSelector ).attr( 'action-state', actionState || '' );
+ }
+ }
+
+ /* ==================== */
+ /* Path Serialization */
+ /* ==================== */
+
+ function getSvgPathStringFromProxyPaths() {
+ var proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
+ var proxyPathGroups = $( proxyPathContainer ).find( PROXY_PATH_GROUP_SELECTOR );
+
+ var pathString = '';
+ $( proxyPathGroups ).each( function( index, proxyPathGroup ) {
+ var 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';
+ }
+ });
+
+ return pathString;
+ }
+
+ /* ==================== */
+ /* Save */
+ /* ==================== */
+
+ function saveSvgPath() {
+ if ( ! gSelectedPathSvgGroup || ! gConfig || ! gConfig.onSave ) { return; }
+
+ var svgPathString = getSvgPathStringFromProxyPaths();
+ gConfig.onSave( gSelectedPathSvgGroup[0], svgPathString );
+ }
+
+ /* ==================== */
+ /* Utilities */
+ /* ==================== */
+
+ function getReferenceElementForExtendingProxyPath() {
+ if ( gSvgPathEditData.selectedProxyElement ) {
+ return gSvgPathEditData.selectedProxyElement;
+ }
+ var lastProxyPath = $( gSvgPathEditData.proxyPathContainer ).find( PROXY_PATH_GROUP_SELECTOR ).last();
+ var lastProxyPoint = lastProxyPath.find( PROXY_POINT_SELECTOR ).last();
+ return lastProxyPoint;
+ }
+
+ function getPrecedingProxyLine( proxyPoint ) {
+ var proxyPointId = $( proxyPoint ).attr( 'id' );
+ return $( 'line[' + AFTER_PROXY_POINT_ID + '="' + proxyPointId + '"]' );
+ }
+
+ function getFollowingProxyLine( proxyPoint ) {
+ var proxyPointId = $( proxyPoint ).attr( 'id' );
+ return $( 'line[' + BEFORE_PROXY_POINT_ID + '="' + proxyPointId + '"]' );
+ }
+
+})();
diff --git a/src/hi/static/js/svg-path.js b/src/hi/static/js/svg-path.js
deleted file mode 100644
index 8f89f6df..00000000
--- a/src/hi/static/js/svg-path.js
+++ /dev/null
@@ -1,937 +0,0 @@
-(function() {
-
- window.Hi = window.Hi || {};
- window.Hi.edit = window.Hi.edit || {};
- window.Hi.svgUtils = window.Hi.svgUtils || {};
-
- const MODULE_NAME = 'svg-path';
- let gCurrentSelectionModule = null;
-
- const HiEditSvgPath = {
- init: function() {
- Hi.edit.eventBus.subscribe( Hi.edit.SELECTION_MADE_EVENT_NAME,
- this.clearSelection.bind( this ) );
- },
- handleClick: function( event ) {
- return _handleClick( event );
- },
- handleKeyDown: function( event ) {
- return _handleKeyDown( event );
- },
- clearSelection: function( data ) {
- gCurrentSelectionModule = data.moduleName;
- if ( data.moduleName != MODULE_NAME ) {
- clearSelectedPathSvgGroup();
- }
- }
- };
-
- window.Hi.edit.path = HiEditSvgPath;
- HiEditSvgPath.init();
-
- /*
- SVG PATH EDITING
-
- - When a path is selected, the original SVG element/group is hidden and proxy elements created.
- - Proxy elements are points and lines with points being way to move path endpoint location.
- - During editing, control proxy popionts can be moved, added and deleted.
- - Two types of paths: closed (with ending 'Z') and open.
- - The type is determined by the initial path and not changeable during editing.
- - An open path must have at least two proxy points (control points for manipulation).
- - A closed path must have at least 3 proxy points.
- - The behavior of adding to the path depends on its type.
- - Adding is relative to the last selected item.
- - You can select a line or a proxy point during editing.
- - An open path gets extended when adding (can also subdivide a line if it is selected).
- - A closed path has its lines subdivided when adding.
- - A entity's path can consist of multiple, disconnected segments.
- - Add a new proxy path adds a line or a rectangle for open and closed paths respectively.
- - A selected path aso shows the entity details in the side edit panel.
- */
-
- const PROXY_PATH_CONTAINER_ID = 'hi-proxy-path-container';
- const PROXY_PATH_CLASS = 'hi-proxy-path';
- const PROXY_PATH_GROUP_SELECTOR = 'g.' + PROXY_PATH_CLASS;
- const PROXY_POINTS_CLASS = 'hi-proxy-points';
- const PROXY_POINTS_GROUP_SELECTOR = 'g.' + PROXY_POINTS_CLASS;
- const PROXY_LINES_CLASS = 'hi-proxy-lines';
- const PROXY_LINES_GROUP_SELECTOR = 'g.' + PROXY_LINES_CLASS;
- const PROXY_ITEM_CLASS = 'proxy';
- const PROXY_POINT_CLASS = 'proxy-point';
- const PROXY_LINE_CLASS = 'proxy-line';
- const PROXY_POINT_SELECTOR = 'circle.' + PROXY_POINT_CLASS;
- const PROXY_LINE_SELECTOR = 'line.' + PROXY_LINE_CLASS;
- const PROXY_PATH_TYPE_ATTR = 'hi-proxy-path-type';
- const BEFORE_PROXY_POINT_ID = 'before-proxy-point-id';
- const AFTER_PROXY_POINT_ID = 'after-proxy-point-id';
-
- const PATH_ACTION_DELETE_KEY_CODES = [
- 88, // 'x'
- 8, // Backspace
- 46 // Delete
- ];
- const PATH_ACTION_INSERT_KEY_CODES = [
- 73, // 'i'
- 45 // Insert
- ];
- const PATH_ACTION_ADD_KEY_CODES = [
- 65, // 'a'
- 61 // '+'
- ];
- const PATH_ACTION_END_KEY_CODES = [
- 27 // Escape
- ];
-
- const CURSOR_MOVEMENT_THRESHOLD_PIXELS = 3; // Differentiate between move events and sloppy clicks
- const PATH_EDIT_PROXY_POINT_RADIUS_PIXELS = 8;
- const PATH_EDIT_PROXY_LINE_WIDTH_PIXELS = 5;
- const PATH_EDIT_NEW_PATH_RADIUS_PERCENT = 5; // Preferrable if this matches server new path sizing.
- const PATH_EDIT_PROXY_LINE_COLOR = 'red';
- const PATH_EDIT_PROXY_POINT_COLOR = 'red';
-
- const API_EDIT_SVG_PATH_URL = '/location/edit/item/path';
-
- const ProxyPathType = {
- OPEN: 'open',
- CLOSED: 'closed'
- };
-
- let gSelectedPathSvgGroup = null;
- let gSvgPathEditData = null;
- 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;
- }
-
- function _handleKeyDown( event ) {
- if ( ! Hi.isEditMode ) { return false; }
- if ( $(event.target).is('input[type="text"], textarea') ) {
- return false;
- }
- if ($(event.target).closest('.modal').length > 0) {
- 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;
- }
-
- 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_EDIT_MODE_URL}/${svgItemId}` );
- } else {
- AN.get( `${Hi.API_LOCATION_ITEM_STATUS_URL}/${svgItemId}` );
- }
- }
-
- function clearSelectedPathSvgGroup() {
- if ( gSelectedPathSvgGroup ) {
- if ( Hi.DEBUG ) { console.log('Clearing svg path selection'); }
- collapseSvgPath( );
- gSelectedPathSvgGroup = null;
- }
- }
-
- function handleProxyPathClick( 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;
- }
-
- 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++ ) {
-
- 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 );
-
- } else if (command === 'L' && currentProxyPathGroup ) {
- 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;
- }
- }
-
- // 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 ) {
-
- if ( Hi.DEBUG ) { 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 {
- if ( Hi.DEBUG ) { 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();
-
- 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 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;
- }
-
- function appendNewProxyPoint( newSvgPoint, proxyPathGroup ) {
-
- 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'));
-
- 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 );
-
- return newProxyPoint;
- }
-
- function insertNewProxyPoint( newSvgPoint, referenceProxyLine ) {
-
- 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 ); }
-
- const beforeX = parseFloat($(beforeProxyPoint).attr('cx'));
- const beforeY = parseFloat($(beforeProxyPoint).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 );
-
- $(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 );
-
- 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();
- }
-
- function deleteProxyLine( svgProxyLine ) {
- // 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.
-
- 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 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();
- }
-
- 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 {
- if ( Hi.DEBUG ) { 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();
- }
-
- 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 );
-
- // 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 );
-
- 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;
- }
-
- 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;
- }
-
- function addProxyPointEventHandler( proxyPoint, beforeProxyLine, afterProxyLine ) {
- // Drag logic for the proxy point
- $(proxyPoint).on('mousedown', function( event ) {
- event.preventDefault();
- event.stopImmediatePropagation();
-
- let startMousePosition = {
- x: event.clientX,
- y: event.clientY
- };
-
- 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;
-
- // 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);
- }
- }
-
- // 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);
- }
-
- // 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' ); }
-
- let newSvgPath = getSvgPathStringFromProxyPaths();
- $(gSelectedPathSvgGroup).find('path').attr( 'd', newSvgPath );
-
- const proxyPathContainer = $( '#' + PROXY_PATH_CONTAINER_ID );
- $(proxyPathContainer).remove();
-
- gSelectedPathSvgGroup.show();
-
- 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 );
- }
-
- 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';
- }
-
- });
-
- if ( Hi.DEBUG ) { 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;
- }
-
- function getPrecedingProxyLine( proxyPoint ) {
- 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 + '"]');
- }
-
-})();
diff --git a/src/hi/static/js/svg-utils.js b/src/hi/static/js/svg-utils.js
index adc9505b..1a9375be 100644
--- a/src/hi/static/js/svg-utils.js
+++ b/src/hi/static/js/svg-utils.js
@@ -27,6 +27,12 @@
},
getSvgTransformValues: function( transformAttrStr ) {
return _getSvgTransformValues( transformAttrStr );
+ },
+ snapToGrid: function( svgElement, value, shiftHeld ) {
+ return _snapToGrid( svgElement, value, shiftHeld );
+ },
+ snapAngle: function( angle, shiftHeld ) {
+ return _snapAngle( angle, shiftHeld );
}
};
@@ -190,6 +196,41 @@
return transform;
}
+ function _snapToGrid( svgElement, value, shiftHeld ) {
+ var gridPixels = ( window.Hi && window.Hi.SvgEdit )
+ ? ( window.Hi.SvgEdit.snapGridPixels || 0 ) : 0;
+ if ( gridPixels <= 0 ) { return value; }
+
+ var pixelsPerSvgUnit = _getPixelsPerSvgUnit( svgElement );
+ var svgUnitsPerPixel = 1.0 / pixelsPerSvgUnit.scaleX;
+ var screenPixels = shiftHeld ? 1 : gridPixels;
+ var gridSize = screenPixels * svgUnitsPerPixel;
+
+ return Math.round( value / gridSize ) * gridSize;
+ }
+
+ var FACTORS_OF_45 = [ 1, 3, 5, 9, 15, 45 ];
+
+ function _snapAngle( angle, shiftHeld ) {
+ var gridPixels = ( window.Hi && window.Hi.SvgEdit )
+ ? ( window.Hi.SvgEdit.snapGridPixels || 0 ) : 0;
+ if ( gridPixels <= 0 ) { return angle; }
+
+ var snapDegrees;
+ if ( shiftHeld ) {
+ snapDegrees = 1;
+ } else {
+ /* Find the largest factor of 45 that is <= gridPixels. */
+ snapDegrees = 1;
+ for ( var i = 0; i < FACTORS_OF_45.length; i++ ) {
+ if ( FACTORS_OF_45[i] <= gridPixels ) {
+ snapDegrees = FACTORS_OF_45[i];
+ }
+ }
+ }
+ return Math.round( angle / snapDegrees ) * snapDegrees;
+ }
+
function _getSvgTransformValuesOriginal( transformAttrStr ) {
let scale = { x: 1, y: 1 }, rotate = { angle: 0, cx: 0, cy: 0 }, translate = { x: 0, y: 0 };
diff --git a/src/hi/templates/icons/check-circle.html b/src/hi/templates/icons/check-circle.html
index f991e3e7..0c473695 100644
--- a/src/hi/templates/icons/check-circle.html
+++ b/src/hi/templates/icons/check-circle.html
@@ -1,3 +1,3 @@
<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
-</svg>
\ No newline at end of file
+</svg>
diff --git a/src/hi/templates/icons/clock.html b/src/hi/templates/icons/clock.html
index 968b205a..1243bfce 100644
--- a/src/hi/templates/icons/clock.html
+++ b/src/hi/templates/icons/clock.html
@@ -1,3 +1,4 @@
<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm3.5 6L13 10.5V7c0-.55-.45-1-1-1s-1 .45-1 1v4.5c0 .28.11.52.29.71.18.18.43.29.71.29.28 0 .52-.11.71-.29l2.5-2.5c.39-.39.39-1.02 0-1.41-.39-.39-1.02-.39-1.41 0z"/>
-</svg>
\ No newline at end of file
+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/>
+ <path d="M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>
+</svg>
diff --git a/src/hi/templates/icons/download.html b/src/hi/templates/icons/download.html
new file mode 100644
index 00000000..a9da806d
--- /dev/null
+++ b/src/hi/templates/icons/download.html
@@ -0,0 +1,3 @@
+<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
+ <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>
+</svg>
diff --git a/src/hi/templates/icons/exclamation-circle.html b/src/hi/templates/icons/exclamation-circle.html
index e043f9cc..190f53f2 100644
--- a/src/hi/templates/icons/exclamation-circle.html
+++ b/src/hi/templates/icons/exclamation-circle.html
@@ -1,3 +1,3 @@
<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
-</svg>
\ No newline at end of file
+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm2 15h-4v-4h4v4zm0-6h-4V6h4v5z"/>
+</svg>
diff --git a/src/hi/templates/icons/info-circle.html b/src/hi/templates/icons/info-circle.html
index 833b33e2..ad333f96 100644
--- a/src/hi/templates/icons/info-circle.html
+++ b/src/hi/templates/icons/info-circle.html
@@ -1,3 +1,3 @@
<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
-</svg>
\ No newline at end of file
+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm2 15h-4v-6h4v6zm0-8h-4V5h4v4z"/>
+</svg>
diff --git a/src/hi/templates/icons/minus-circle.html b/src/hi/templates/icons/minus-circle.html
index dab080a1..13fbc351 100644
--- a/src/hi/templates/icons/minus-circle.html
+++ b/src/hi/templates/icons/minus-circle.html
@@ -1,3 +1,3 @@
<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11H7v-2h10v2z"/>
-</svg>
\ No newline at end of file
+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 12H7v-4h10v4z"/>
+</svg>
diff --git a/src/hi/templates/icons/question-circle.html b/src/hi/templates/icons/question-circle.html
index 4bf44807..e27af89a 100644
--- a/src/hi/templates/icons/question-circle.html
+++ b/src/hi/templates/icons/question-circle.html
@@ -1,3 +1,3 @@
<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/>
-</svg>
\ No newline at end of file
+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm2 17h-4v-4h4v4zm3.07-8.75l-.9.92C15.45 11.9 14 13.5 14 15h-4v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H7c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/>
+</svg>
diff --git a/src/hi/templates/icons/times-circle.html b/src/hi/templates/icons/times-circle.html
index 11b32175..61d88dd0 100644
--- a/src/hi/templates/icons/times-circle.html
+++ b/src/hi/templates/icons/times-circle.html
@@ -1,3 +1,3 @@
<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm3.59 5L12 10.59 8.41 7 7 8.41 10.59 12 7 15.59 8.41 17 12 13.41 15.59 17 17 15.59 13.41 12 17 8.41 15.59 7z"/>
-</svg>
\ No newline at end of file
+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5.54 13.12L15.12 17.54 12 14.41 8.88 17.54 6.46 15.12 9.59 12 6.46 8.88 8.88 6.46 12 9.59 15.12 6.46 17.54 8.88 14.41 12 17.54 15.12z"/>
+</svg>
diff --git a/src/hi/templates/icons/undo.html b/src/hi/templates/icons/undo.html
new file mode 100644
index 00000000..404c80bc
--- /dev/null
+++ b/src/hi/templates/icons/undo.html
@@ -0,0 +1,3 @@
+<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
+ <path d="M12.5 8c-2.65 0-5.05 1.04-6.83 2.73L3 8v9h9l-2.83-2.83C10.42 12.9 11.42 12.5 12.5 12.5c2.33 0 4.3 1.46 5.11 3.5l2.39-.96C18.84 12.16 15.9 8 12.5 8z"/>
+</svg>
diff --git a/src/hi/templates/modals/action_cancel.html b/src/hi/templates/modals/action_cancel.html
new file mode 100644
index 00000000..b14b19bc
--- /dev/null
+++ b/src/hi/templates/modals/action_cancel.html
@@ -0,0 +1,9 @@
+{% extends "modals/action_1.html" %}
+{% load icons %}
+
+{% block action_center %}
+<a id="hi-modal-cancel" role="button" {% if autofocus %}autofocus="autofocus"{% endif %}
+ class="btn btn-outline-tertiary" href="#" data-dismiss="modal">
+ {% icon "cancel" size="sm" css_class="hi-icon-left" %}CANCEL
+</a>
+{% endblock %}
diff --git a/src/hi/templates/panes/bottom_buttons.html b/src/hi/templates/panes/bottom_buttons.html
index a1929eae..3f24b901 100644
--- a/src/hi/templates/panes/bottom_buttons.html
+++ b/src/hi/templates/panes/bottom_buttons.html
@@ -4,6 +4,13 @@
{% include "collection/panes/collection_buttons.html" %}
<div class="d-flex justify-content-end">
{% if request.view_parameters.is_editing %}
+ <div class="mx-1 d-flex align-items-center">
+ <label class="mb-0 mx-1" style="font-size: 0.85rem;"><b>Snap:</b></label>
+ <input type="number" id="hi-entity-snap-grid" class="form-control form-control-sm"
+ style="width: 4rem;" value="5" min="0" max="50" step="1"
+ title="Snap grid in screen pixels (0 to disable, hold Shift for fine mode)">
+ <label class="ms-1 mb-0" style="font-size: 0.85rem;">px</label>
+ </div>
<div class="mx-1">
<a href="{% url 'profiles_edit_reference_help' %}"
class="btn btn-tertiary btn-control" role="button"
diff --git a/src/hi/views.py b/src/hi/views.py
index 268e792c..5aae4401 100644
--- a/src/hi/views.py
+++ b/src/hi/views.py
@@ -177,6 +177,9 @@ class HomeView( View ):
redirect_url = reverse( 'collection_view_default' )
else:
redirect_url = reverse( 'location_view_default' )
+ query_string = request.META.get( 'QUERY_STRING', '' )
+ if query_string:
+ redirect_url = redirect_url + '?' + query_string
return HttpResponseRedirect( redirect_url )