Skip to content

Home Information - Your home, your data, organized.

Python

EntityStatusPanel framework, dispatcher, and three pilot panels (#328)

Tony C3c33cf29cf35
diff --git a/docs/dev/frontend/entity-display-overview.md b/docs/dev/frontend/entity-display-overview.md
new file mode 100644
index 00000000..ba9bf3b7
--- /dev/null
+++ b/docs/dev/frontend/entity-display-overview.md
@@ -0,0 +1,73 @@
+# Entity Display — Architecture Overview
+
+How entity state flows from sensor to pixel, and where the responsibilities live. Read this first when you're new to the frontend; reach for the focused docs (linked below) when you're authoring or modifying a specific surface.
+
+## The flow
+
+```
+Sensor reading (HA / ZM / etc.)
+ │
+ ▼
+EntityStateStatusData ─ raw per-state data container
+ │
+ ▼
+EntityStateDisplayData ─ display projections (StatusStyle, formatted text, etc.)
+ │
+ ▼
+StatusDisplayManager ─ assembles entityStateStatusMap, keyed by state id
+ │
+ ▼ ────── /api/status response ──────► JS dispatcher (entity_state_status.js)
+ │
+ ▼
+ DOM elements with data-state-id
+ (icons, paths, panels, sensor cards)
+```
+
+Server side: each `EntityState` gets one row in the status map. The row carries whatever update payloads the surfaces consuming this state might need — a status string, formatted display text, a controller widget value, an SVG style bundle. Source of truth: [`EntityStateDisplayData.to_polling_update_dict`](../../../src/hi/apps/monitor/display_data.py).
+
+Client side: the dispatcher walks every DOM element carrying `data-state-id="<id>"`, looks up the row for that state, and writes whatever subset the element opted into via declaration attributes (`data-status`, `data-display-text`, etc.). No descendant traversal, no class-as-join — each element is self-describing.
+
+## The four display surfaces
+
+The same polling pipeline drives four visually distinct surfaces. Each surface has its own authoring conventions but speaks the same wire contract.
+
+| Surface | Where it appears | Authoring doc |
+|---|---|---|
+| **LocationView SVG icons** | The map view's `<g>` icon elements per positioned entity | [`entity-visual-configuration.md`](entity-visual-configuration.md) |
+| **LocationView SVG paths** | The map view's `<path>` elements per area-based entity | [`entity-visual-configuration.md`](entity-visual-configuration.md) |
+| **Entity status modal** | Body of the per-entity status dialog | [`entity-status-panels.md`](entity-status-panels.md) |
+| **Collection cards** | Per-entity cards in the list and grid layouts of a collection view | [`entity-status-panels.md`](entity-status-panels.md) |
+
+The modal and collection-card surfaces share an `EntityStatusPanel` dispatch: a panel for a given `EntityType` provides up to three templates (`modal.html` / `list.html` / `grid.html`), with a framework fallback supplying a flat state list when no per-type panel exists.
+
+## The polling contract is the connective tissue
+
+All four surfaces ultimately render DOM elements whose live behavior is driven by the same per-element contract:
+
+```html
+<element data-state-id="<entity_state.id>"
+ data-status ← optional: receive the status attribute
+ data-display-text ← optional: receive the formatted text
+ data-display-magnitude ← optional: receive the magnitude only
+ data-display-unit ← optional: receive the unit only
+ data-controller-value ← optional: receive form value updates
+ data-svg-style ← optional: receive the full SVG style bundle
+ ...>
+```
+
+The full grammar, the server payload shape, and the rules about which declarations belong on which element shapes are documented in [`entity-status-display.md`](entity-status-display.md).
+
+## Where to look next
+
+By task:
+
+- **Adding visual support for a new `EntityType` on the map** (icon or path) — [`entity-visual-configuration.md`](entity-visual-configuration.md).
+- **Authoring a custom panel for a new `EntityType`** (modal / list / grid bodies) — [`entity-status-panels.md`](entity-status-panels.md).
+- **Modifying the polling-update mechanism**, the wire format, the color palette, or the per-element declaration grammar — [`entity-status-display.md`](entity-status-display.md).
+
+By component:
+
+- Backend: [`StatusDisplayManager`](../../../src/hi/apps/monitor/status_display_manager.py), [`EntityStateDisplayData` / `EntityDisplayData`](../../../src/hi/apps/monitor/display_data.py), [`EntityStateStatusData`](../../../src/hi/apps/monitor/status_data.py).
+- Frontend dispatcher: [`entity_state_status.js`](../../../src/hi/static/js/entity_state_status.js).
+- Panel dispatcher: [`state_panel_dispatch.py`](../../../src/hi/apps/entity/state_panel_dispatch.py) + [`state_panel_tags.py`](../../../src/hi/apps/entity/templatetags/state_panel_tags.py).
+- CSS palette and SVG status rules: [`main.css`](../../../src/hi/static/css/main.css) (search `:root` for variables, `g[status` and `.hi-status-display[status` for rules).
diff --git a/docs/dev/frontend/entity-status-display.md b/docs/dev/frontend/entity-status-display.md
index 448d57a1..fea1b0f1 100644
--- a/docs/dev/frontend/entity-status-display.md
+++ b/docs/dev/frontend/entity-status-display.md
@@ -1,222 +1,124 @@
-# Entity Status Display
+# Entity Status Display — Polling-Update Contract
-## Quick Reference
+Reference for the polling-update contract that connects backend state to live DOM. Covers the server payload shape, the per-element declaration grammar, the status-value vocabulary, the color palette, and the icon-vs-path asymmetry.
-### Key Files
-- **CSS**: Status colors defined in CSS custom properties (`:root` section)
-- **JavaScript**: `polling.js` handles real-time updates via `/api/status`
-- **Templates**: Entity elements need `data-entity-id` attributes for updates
-- **Backend**: `StatusDisplayManager` calculates display states from sensor data
+If you're new to entity display, start with [`entity-display-overview.md`](entity-display-overview.md). For consuming the contract from authoring contexts, see [`entity-status-panels.md`](entity-status-panels.md) (panel authoring) and [`entity-visual-configuration.md`](entity-visual-configuration.md) (SVG asset authoring).
-## Overview
+## The flow in one paragraph
-The entity status display system provides visual feedback for entity states through dynamic CSS classes, SVG styling, and real-time updates. This document covers the frontend implementation details for displaying entity status visually.
+On every `/api/status` poll, [`StatusDisplayManager`](../../../src/hi/apps/monitor/status_display_manager.py) builds an `entityStateStatusMap` keyed by `EntityState.id` (as a string). The JS dispatcher in [`entity_state_status.js`](../../../src/hi/static/js/entity_state_status.js) walks every DOM element carrying `data-state-id="<id>"`, looks up the row for that state, and writes whatever subset the element opted into via declaration attributes. No descendant traversal, no class-as-join — each element opts in directly.
-## Visual Display Implementation
+## Server payload shape
-Entity visual representation is implemented through three main approaches:
+Per-state row, built by [`EntityStateDisplayData.to_polling_update_dict`](../../../src/hi/apps/monitor/display_data.py):
-### 1. CSS Class Mapping
-
-The system takes normalized sensor values and applies them as CSS class names to SVG elements. This allows CSS rules to dynamically adjust visual display for well-known sensor values.
-
-```css
-/* Entity state CSS classes */
-.entity-svg.state-active {
- fill: var(--status-active);
- fill-opacity: 0.8;
+```python
+"42": { # key: str(entity_state.id)
+ "status": "active", # singular status value (for [data-status])
+ "controller": { "value": "on" }, # controller widget value (for [data-controller-value])
+ "display": {
+ "magnitude": 72.0, # numeric magnitude (for [data-display-magnitude])
+ "unit": "°F", # unit symbol (for [data-display-unit])
+ "text": "72.0°F", # combined human-readable label (for [data-display-text])
+ },
+ "svg_style": { # full SVG attribute bundle (for [data-svg-style])
+ "status": "active",
+ "stroke": "red",
+ "stroke-width": 4.0,
+ "fill": "red",
+ "fill-opacity": 0.5,
+ "stroke-dasharray": "2,4", # optional
+ },
}
+```
-.entity-svg.state-recent {
- fill: var(--status-recent);
- fill-opacity: 0.6;
-}
+Fields are present only when meaningful — sensor-only states omit `controller`; unit-less states omit `display.magnitude` / `display.unit`; states with no SVG styling omit `svg_style`. `entry.status` and `entry.svg_style.status` carry the same value when both are present; consumers pick the bundle that matches their opt-in.
-.entity-svg.state-past {
- fill: var(--status-past);
- fill-opacity: 0.4;
-}
+## The DOM contract
-.entity-svg.state-idle {
- fill: var(--status-idle);
- fill-opacity: 0.3;
-}
+Every element that wants polling updates carries one **anchor** attribute and one or more **declaration** attributes:
-.entity-svg.state-unknown {
- fill: var(--status-unknown);
- fill-opacity: 0.2;
-}
+```html
+<element data-state-id="<entity_state.id>"
+ data-status ← presence-only opt-in
+ data-display-text ← presence-only opt-in
+ ...>
```
-### 2. Predefined Icon Variants
+The anchor identifies which state this element listens to. Each declaration is presence-only — the attribute being present opts the element in; the dispatcher provides the value from the matching row. Server-rendered initial values stay where they are; the dispatcher just keeps them current.
-For well-known sensor values, the system can swap between predefined SVG icons to represent different states:
+### Declaration grammar
-```html
-<!-- Base entity icon -->
-<use href="#icon-motion-sensor-idle" class="entity-icon" />
+| Declaration | What the dispatcher writes | Source field |
+|---|---|---|
+| `data-status` | Sets the `status` HTML attribute to the **status value** | `entry.status` |
+| `data-controller-value` | Sets form `value` / `checked` / `selected` (per element type) | `entry.controller.value` |
+| `data-display-magnitude` | Replaces text content with the **magnitude** | `entry.display.magnitude` |
+| `data-display-unit` | Replaces text content with the **unit symbol** | `entry.display.unit` |
+| `data-display-text` | Replaces text content with the combined **user-facing string** | `entry.display.text` |
+| `data-svg-style` | Sets *all* keys in `entry.svg_style` as element attributes | `entry.svg_style` |
-<!-- Active state icon -->
-<use href="#icon-motion-sensor-active" class="entity-icon" />
-```
+Sliders are special-cased: the dispatcher skips a `<input type="range">` that the user is actively dragging so a polling refresh doesn't yank the thumb out from under them.
-### 3. Color Scheme Mapping
+### Status value vocabulary
-The system maps sensor values to color schemes applied via SVG fill, stroke, and opacity attributes. This is predominantly used for area entities (closed SVG paths) to show activity levels.
+The `status` value is a bucketed, CSS-friendly token derived from raw sensor data by per-state-type logic in [`EntityStateDisplayData._get_svg_status_style`](../../../src/hi/apps/monitor/display_data.py). CSS rules key on `[status="..."]` to apply visual styling. Common tokens used across multiple state types (so the same CSS rules cover several domains):
-```javascript
-// Color scheme application
-function applyColorScheme(element, colorData) {
- element.style.fill = colorData.fillColor;
- element.style.stroke = colorData.strokeColor;
- element.style.opacity = colorData.opacity;
- element.style.strokeWidth = colorData.strokeWidth;
-}
-```
+- `active`, `idle` — base states for binary alarms (movement, smoke, moisture, CO, gas), open/close, and HVAC action.
+- `recent`, `past` — decay buckets for sensors that visually "cool off" after activity (movement, open/close, smoke, etc.).
+- `on`, `off`, `dim` — binary power / light states.
+- `open`, `closed`, `partial` — open/close discrete states.
+- `connected`, `disconnected` — connectivity state.
+- `high`, `low` — discrete range state.
+- `smoke_detected`, `smoke_clear`, `moisture_detected`, `moisture_clear`, `co_detected`, `co_clear`, `gas_detected`, `gas_clear` — alarm-specific values, kept distinct from generic `active`/`idle` where the surface needs domain-specific styling.
-## Status Color System
+Adding a new state type that needs its own status token also requires adding matching CSS rules. The complete authoritative palette is in [`StatusStyle`](../../../src/hi/hi_styles.py) on the backend and the `g[status="..."]` / `.hi-status-display[status="..."]` rule blocks in [`main.css`](../../../src/hi/static/css/main.css) on the frontend.
-### Color Variables
+## Color palette
-Define status colors using CSS custom properties:
+CSS custom properties in [`main.css`](../../../src/hi/static/css/main.css)'s `:root`:
```css
-:root {
- /* Status colors following traffic light metaphor */
- --status-active: #dc3545; /* Red - Active/Alert */
- --status-recent: #fd7e14; /* Orange - Recently active */
- --status-past: #ffc107; /* Yellow - Past activity */
- --status-idle: #28a745; /* Green - Idle/Safe */
- --status-unknown: #6c757d; /* Gray - Unknown/Offline */
-}
+--status-active-color /* alarmed / detected — red */
+--status-recent-color /* recently alarmed — orange */
+--status-past-color /* past alarm decaying — yellow */
+--status-ok-color /* nominal / connected — green */
+--status-bad-color /* fault — dark red */
+--status-idle-color /* default / neutral — gray */
+--status-on-color /* powered on — yellow */
+--status-off-color /* powered off — gray */
```
-### Visual State Progression
+Each has an `--on-status-*-color` companion for foreground text against the corresponding background.
-The value decaying system creates a visual "cooling off" effect through color transitions:
+The decay sequence used by recently-active sensors moves through `active → recent → past → idle` as time passes since the last activation; the thresholds live in [`EntityStateDisplayData`](../../../src/hi/apps/monitor/display_data.py) (`RECENT_*_THRESHOLD_SECS`, `PAST_*_THRESHOLD_SECS`).
-**Color Progression**: Active (red) → Recent (orange) → Past (yellow) → Idle (green/gray)
+## Icon vs path update shape
-```css
-/* Smooth transitions between states */
-.entity-svg {
- transition: fill 0.3s ease, opacity 0.3s ease;
-}
+LocationView SVG icons and SVG paths react to status updates through different opt-ins, and the asymmetry is intentional.
-/* State-specific styling with opacity variations */
-.entity-active {
- fill: var(--status-active);
- opacity: 1.0;
-}
-.entity-recent {
- fill: var(--status-recent);
- opacity: 0.8;
-}
-.entity-past {
- fill: var(--status-past);
- opacity: 0.6;
-}
-.entity-idle {
- fill: var(--status-idle);
- opacity: 0.4;
-}
-```
+- **Icons** (`<g>` elements) declare `data-status`. The polling dispatcher writes only the `status` attribute; CSS rules keyed on `g[status="..."]` (and nested selectors like `g[status="off"] path.hi-state-bg`) supply the visual styling.
+- **Paths** (`<path>` elements) declare `data-svg-style`. The dispatcher writes the full bundle (`status`, `stroke`, `stroke-width`, `fill`, `fill-opacity`, `stroke-dasharray`) as inline SVG attributes; CSS only adds drop-shadow on top.
+
+Icons can't safely receive the full bundle because they are multi-element. A typical icon `<g>` wraps several primitives — body, outline, background plate — each of which may want differentiated styling for a given status. If the dispatcher pushed `fill="red"` onto the parent `<g>`, SVG attribute inheritance would paint every child red, overriding child-specific CSS. Per-child selectors are the only mechanism that gives each child independent control, which is why icons confine themselves to pushing the `status` attribute and letting CSS branch from there.
+
+Paths can use the full bundle because they are single-element — one `<path>` per region, no inheritance hazard — and their per-entity-type palette (movement vs smoke vs open/close, each with its own colors) is naturally expressed by Python's `StatusStyle` rather than as a Cartesian product of CSS rules. The attribute-driven path also leaves room for future continuous-value visuals (e.g., opacity proportional to a numeric magnitude) which closed-set CSS rules can't express.
+
+When adding a new visual, copy from an existing icon or path of the same shape — the right opt-in comes along.
+
+## Panel JS hooks
+
+Surfaces that need per-tick behavior beyond what the declarative contract expresses (e.g., a thermostat dial whose SVG marker angles are computed from numeric magnitudes) register a handler:
+
+- **`Hi.statePanels.registerUpdate(handler)`** — fires after each polling apply pass, receiving the full status map. For refresh-time work the declarative contract can't express.
+- **`Hi.statePanels.registerInit(handler)`** — fires at jQuery ready and after every async content insertion (modal opens, fragment loads). For positioning elements from server-rendered initial data. Handlers must be idempotent — they re-scan the document on each call.
+
+See [`entity_state_status.js`](../../../src/hi/static/js/entity_state_status.js) for the API and [`state_panels/thermostat/thermostat.js`](../../../src/hi/static/state_panels/thermostat/thermostat.js) for a canonical example using both hooks.
+
+## Related documentation
-## Client-Server Status Updates
-
-### Polling System Implementation
-
-The JavaScript `polling.js` module handles real-time status updates through server polling:
-
-### Server Response Format
-
-The server returns status updates in a standardized JSON format:
-
-### Element Targeting and Updates
-
-The polling system uses CSS class names and data attributes to target elements:
-
-## Workflow 1: Adding Status Display to New Entity Template
-
-**Scenario**: You have a new entity type (smart thermostat) that needs status display functionality in location views.
-
-**Step-by-Step Implementation:**
-
-1. **Plan the Visual States** (Domain consideration)
- ```python
- # Thermostat states we want to display:
- # - heating (red) - actively heating
- # - cooling (blue) - actively cooling
- # - idle (green) - maintaining temperature
- # - offline (gray) - no communication
- ```
-
-2. **Define Status CSS Classes** ([CSS Class Mapping](#css-class-mapping))
- ```css
- /* Add to your CSS file */
- .entity-svg.thermostat-heating {
- fill: var(--status-active);
- stroke: #cc0000;
- }
-
- .entity-svg.thermostat-cooling {
- fill: #0066cc;
- stroke: #004499;
- }
-
- .entity-svg.thermostat-idle {
- fill: var(--status-idle);
- stroke: #006600;
- }
-
- .entity-svg.thermostat-offline {
- fill: var(--status-unknown);
- stroke: #666666;
- }
- ```
-
-3. **Update Backend Status Logic** ([Server Response Format](#server-response-format))
- ```python
- # In your entity model or status manager
- class ThermostatStatusCalculator:
- def get_status_css_classes(self, thermostat_entity):
- current_state = thermostat_entity.get_current_state('hvac_mode')
-
- if not current_state or current_state.is_stale():
- return ['thermostat-offline']
-
- mode = current_state.value
- if mode == 'heating':
- return ['thermostat-heating']
- elif mode == 'cooling':
- return ['thermostat-cooling']
- elif mode == 'idle':
- return ['thermostat-idle']
- else:
- return ['thermostat-offline']
- ```
-
-4. **Update Template Integration** ([Template Integration](#template-integration))
- ```django
- <!-- In your location view template -->
- <g class="entity-group" data-entity-id="{{ thermostat.id }}">
- <use href="#icon-thermostat"
- class="entity-svg {{ thermostat.get_status_css_classes|join:' ' }}"
- transform="translate({{ thermostat.position.x }}, {{ thermostat.position.y }})"/>
- </g>
- ```
-
-5. **Test Status Updates** ([Polling System Implementation](#polling-system-implementation))
- ```javascript
- // Verify polling picks up thermostat status changes
- // Check browser Network tab for /api/status requests
- // Manually trigger state change and observe visual update
- ```
-
-**Expected Result**: Thermostat icons change color in real-time based on heating/cooling state.
-
-## Related Documentation
-- Status calculation logic: [Domain Guidelines](../domain/domain-guidelines.md#status-display-system)
-- Style guidelines: [Style Guidelines](style-guidelines.md)
-- Template conventions: [Template Conventions](template-conventions.md)
-- Frontend patterns: [Frontend Guidelines](frontend-guidelines.md)
+- [Architecture overview](entity-display-overview.md)
+- [Panel authoring](entity-status-panels.md)
+- [SVG asset authoring](entity-visual-configuration.md)
+- [Style guidelines](style-guidelines.md)
+- [Template conventions](template-conventions.md)
diff --git a/docs/dev/frontend/entity-status-panels.md b/docs/dev/frontend/entity-status-panels.md
new file mode 100644
index 00000000..e2ee4c76
--- /dev/null
+++ b/docs/dev/frontend/entity-status-panels.md
@@ -0,0 +1,107 @@
+# Entity Status Panels
+
+EntityStatusPanels render the body of the entity status modal and of the per-entity cards inside collections. The framework dispatches per-`EntityType`, so each panel can present its entity in whatever form best fits — a flat state list, a graphical dial, a video frame, etc. — while the surrounding modal / card chrome stays uniform.
+
+This document covers authoring a new panel.
+
+**Related docs:**
+- [`entity-display-overview.md`](entity-display-overview.md) — high-level architecture and how panels fit alongside the other display surfaces.
+- [`entity-status-display.md`](entity-status-display.md) — the polling-update contract that panel templates and panel JS plug into.
+
+## Overview
+
+A panel is a self-contained bundle of templates, CSS, and JavaScript scoped to one `EntityType` and rendered in one of three **display contexts**:
+
+| Context | Where it renders | Wrapper template |
+|---|---|---|
+| `modal` | The entity status modal body | `entity/templates/entity/modals/entity_status.html` |
+| `list` | A collection's list-card layout | `collection/templates/collection/panes/entity_card_list.html` |
+| `grid` | A collection's grid-card layout | `collection/templates/collection/panes/entity_card_grid.html` |
+
+The wrapper renders its own identifying chrome (entity name, integration logo, type label). The panel body fills the area below and must not duplicate that chrome.
+
+When an entity type has no panel of its own, the framework falls back to a flat state list. The fallback is itself a registered panel — see `entity/state_panels/fallback/`.
+
+## Anatomy
+
+```
+src/hi/apps/entity/templates/entity/state_panels/<type>/
+ modal.html # required
+ list.html # optional, falls back per context chain
+ grid.html # optional, falls back per context chain
+
+src/hi/static/state_panels/<type>/
+ <type>.css # optional
+ <type>.js # optional, registers JS handlers
+```
+
+`<type>` is the `EntityType.name.lower()` value (e.g. `thermostat`, `smoke_detector`).
+
+**Template resolution chain** (see [`state_panel_dispatch.py`](../../../src/hi/apps/entity/state_panel_dispatch.py)):
+
+1. `state_panels/<type>/<context>.html` — context-specific.
+2. `state_panels/<type>/modal.html` — panel default, used for any unprovided context.
+3. `state_panels/fallback/<context>.html` — framework fallback.
+
+So `modal.html` is the only required file per panel: a panel that wants to render the same body in all three contexts just provides that one template.
+
+## Template authoring
+
+The dispatch template tag `{% render_entity_status_panel %}` is invoked by the wrapper. By the time a panel template runs, the parent context plus the entity's display projection are flattened together, so the following names are top-level:
+
+| Name | What it is |
+|---|---|
+| `entity` | The `Entity` model instance. |
+| `entity_status_data` | The `EntityDisplayData` wrapper. |
+| `state_status_data_list` | Ordered list of `EntityStateDisplayData` for the entity's states (sorted per `ENTITY_STATUS_VIEW_ORDERING`). |
+| `state_status_data_by_role` | Dict keyed by lowercase `EntityStateRole.name`. Use this to pull a specific state by role. |
+| `entity_for_video` | The `Entity` whose video stream this panel should embed, or `None`. |
+| `display_only_svg_icon_item` | The framework `SvgIconItem` for the entity's type icon, or `None`. |
+| `display_category` | `EntityDisplayCategory` enum value for layout hints (`HAS_VIDEO` / `HAS_STATE` / `PLAIN`). |
+
+Source of truth: `EntityDisplayData.to_template_context()` in [`display_data.py`](../../../src/hi/apps/monitor/display_data.py).
+
+### Live updates via the polling contract
+
+Elements inside a panel get live updates by carrying `data-state-id="<entity_state.id>"` plus one or more declaration attributes. Example: a span whose text mirrors the current temperature:
+
+```html
+<span data-state-id="{{ state_status_data_by_role.thermostat_current_temperature.entity_state.id }}"
+ data-display-text>72.0°F</span>
+```
+
+For the full declaration grammar, server payload shape, and the icon-vs-path asymmetry, see [`entity-status-display.md`](entity-status-display.md). Authoring a panel template is mostly a matter of (1) pulling the right state via `state_status_data_by_role` or `state_status_data_list`, and (2) tagging the elements that should refresh.
+
+## JS extensions
+
+Most panels need no JavaScript — declarative HTML attributes and CSS rules carry all the live-update work. When more is needed (e.g., re-positioning an SVG marker from a numeric magnitude), register a handler with `Hi.statePanels`:
+
+- **`Hi.statePanels.registerUpdate(handler)`** — fires after each polling apply pass, receiving the full status map keyed by state id. Use this for refresh-time work the declarative contract can't express.
+- **`Hi.statePanels.registerInit(handler)`** — fires on initial page load *and* after every async content insertion (entity status modal opens, collection refreshes). Use this to position elements from server-rendered data. Handlers must be idempotent — they re-scan the document on each call.
+
+API source: [`entity_state_status.js`](../../../src/hi/static/js/entity_state_status.js). Reference panel: [`state_panels/thermostat/thermostat.js`](../../../src/hi/static/state_panels/thermostat/thermostat.js) uses both hooks for its SVG dial.
+
+## Walkthrough: adding a panel for a new `EntityType`
+
+1. Create `src/hi/apps/entity/templates/entity/state_panels/<type>/modal.html`. Add `list.html` / `grid.html` only if those contexts need a different layout.
+2. Fetch specific states by role with `state_status_data_by_role.<role_name>` (lowercase `EntityStateRole.name`), or iterate `state_status_data_list` for the ordered set. The `{% panel_state entity "role_name" %}` tag returns just the `EntityState` model if that's what you need.
+3. Tag refreshable elements per the polling-update contract. Server-rendered initial values stay; the dispatcher rewrites them each tick.
+4. Drop panel-private CSS and JS in `src/hi/static/state_panels/<type>/` if needed.
+5. Register any panel JS handlers via `Hi.statePanels.registerInit` / `registerUpdate`.
+6. Verify in the simulator: open the entity status modal, change values on the simulator side, watch the panel refresh; open a collection containing the entity and check the list and grid contexts.
+
+## Exemplars
+
+Read the existing panels when starting a new one — copy from the closest match.
+
+- **[`fallback/`](../../../src/hi/apps/entity/templates/entity/state_panels/fallback/)** — universal flat state list. Authors needing the standard rendering can include `fallback/state_list.html` directly.
+- **[`smoke_detector/`](../../../src/hi/apps/entity/templates/entity/state_panels/smoke_detector/)** — CSS-only panel. Status-attribute-driven variants switch icon and label visibility without any JS.
+- **[`thermostat/`](../../../src/hi/apps/entity/templates/entity/state_panels/thermostat/)** — full kit. Role-keyed state lookups, custom CSS, init + update JS hooks for an SVG dial.
+- **[`camera/`](../../../src/hi/apps/entity/templates/entity/state_panels/camera/)** — embeds the shared flat state list partial alongside a video stream, demonstrating panel composition with framework partials.
+
+## Pitfalls
+
+- **`data-svg-style` is for single-element styling.** Don't put it on a multi-element SVG `<g>` icon — children inherit the pushed `fill`/`stroke` attributes and lose their differentiated styling. Use `data-status` and CSS branching instead. See [`entity-status-display.md`](entity-status-display.md#icon-vs-path-update-shape) for the full rationale.
+- **Init handlers must be idempotent.** `registerInit` fires on both initial DOM-ready and every async content insertion. Handlers re-scan the document each time; applying state to already-initialized elements must be safe.
+- **Don't duplicate chrome.** The modal wrapper supplies the type icon, entity name, integration logo, and type label in its subheader. The collection-card wrappers supply the entity-name title and (when applicable) the video stream. Panel bodies render below this chrome and should not repeat any of it.
+- **Shared partials live where they were first authored.** The flat state list and per-state row templates live under `state_panels/fallback/` (where they were born). Other panels that want the same list reference them from that path; there's no separate "shared" namespace.
diff --git a/docs/dev/frontend/entity-visual-configuration.md b/docs/dev/frontend/entity-visual-configuration.md
index c26e8091..a0ba9f7e 100644
--- a/docs/dev/frontend/entity-visual-configuration.md
+++ b/docs/dev/frontend/entity-visual-configuration.md
@@ -1,485 +1,96 @@
# Entity Visual Configuration
+Configuring the visual representation of an `EntityType` on the LocationView map: SVG icon assets, area-based path assets, and the `StatusStyle` that drives their per-status appearance.
+
+**Related docs:**
+- [`entity-display-overview.md`](entity-display-overview.md) — high-level architecture and how LocationView visuals fit alongside the other display surfaces.
+- [`entity-status-display.md`](entity-status-display.md) — the polling-update contract. Map icons and paths automatically receive live updates via this contract; the rendering templates ([`svg_icon_item.html`](../../../src/hi/apps/location/templates/location/panes/svg_icon_item.html) and [`svg_path_item_{open,closed}.html`](../../../src/hi/apps/location/templates/location/panes/)) emit the necessary `data-state-id` and declaration attributes for you.
+
## Overview
-This document covers the frontend configuration required to set up visual representations for entity types. It includes icon configuration, path styling, viewbox management, and visual asset creation.
+The LocationView map represents each positioned entity in one of two ways:
+
+- **Icon**: an SVG `<g>` group containing the type's drawing commands, positioned, scaled, and rotated per the entity's `EntityPosition`. Used for point-like entities (sensors, switches, cameras).
+- **Path**: an SVG `<path>` element drawn from the entity's `EntityPath` data. Used for area-like entities (rooms, zones, boundaries).
+
+Choice is driven by `EntityType` registration — each type belongs to either the icon registry or one of the path registries. The framework hands the chosen template a populated `SvgIconItem` or `SvgPathItem` and renders it inside the LocationView SVG; live status updates flow through the polling dispatcher automatically.
+
+### Key configuration files
+
+- **Icons**: SVG drawing fragments at `src/hi/apps/entity/templates/entity/svg/type.{TYPE}.svg`
+- **Registration and styling**: [`src/hi/hi_styles.py`](../../../src/hi/hi_styles.py) — `EntityStyle.EntityTypesWithIcons`, `EntityStyle.EntityTypeClosedPaths`, `EntityStyle.EntityTypeOpenPaths`, `EntityStyle.PathEntityTypeToSvgStatusStyle`, and the `StatusStyle` palette.
+- **Rendering templates** (do not modify per-type — they read from `SvgIconItem` / `SvgPathItem`): [`svg_icon_item.html`](../../../src/hi/apps/location/templates/location/panes/svg_icon_item.html), [`svg_path_item_open.html`](../../../src/hi/apps/location/templates/location/panes/svg_path_item_open.html), [`svg_path_item_closed.html`](../../../src/hi/apps/location/templates/location/panes/svg_path_item_closed.html).
+- **Factory**: [`svg_item_factory.py`](../../../src/hi/apps/location/svg_item_factory.py) — assembles `SvgIconItem` / `SvgPathItem` instances from entities, positions, and `StatusStyle`.
+
+## Adding visual support for a new `EntityType`
+
+### 1. Choose icon or path
+
+- **Icon**: point-like entities — sensors, switches, cameras, displays.
+- **Path**: area-like entities — rooms, zones, boundary lines.
+
+### 2a. Icon-based configuration
+
+**Create the SVG drawing fragment** at `src/hi/apps/entity/templates/entity/svg/type.<type_name>.svg` (where `<type_name>` is `EntityType.name.lower()`). Requirements:
+
+- **No `<svg>` or `<g>` wrapper** — the LocationView's `svg_icon_item.html` template provides the wrapping `<g>` along with positioning transforms and the polling-update data attributes. The fragment should contain only drawing commands.
+- **Clickable background**: include a transparent rectangle covering the entire viewbox so the whole icon area receives pointer events:
+ ```svg
+ <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+ ```
+- **Default viewbox is `0 0 64 64`.** Register a custom viewbox in `EntityStyle.EntityTypeToIconViewbox` if the design needs different proportions.
+
+**Register the type** in `EntityStyle.EntityTypesWithIcons` (a set of `EntityType` values).
+
+The icon receives its visual styling from CSS rules keyed on `g[status="..."]` and from the bucketed `status_value` produced per-state-type by [`EntityStateDisplayData._get_svg_status_style`](../../../src/hi/apps/monitor/display_data.py). For why icons use CSS-driven (not attribute-driven) styling, see [`entity-status-display.md`](entity-status-display.md#icon-vs-path-update-shape).
+
+### 2b. Path-based configuration
+
+**Pick the registry** — closed (filled) or open (line) paths:
+- Closed: `EntityStyle.EntityTypeClosedPaths`
+- Open: `EntityStyle.EntityTypeOpenPaths`
+
+**Bind a `StatusStyle`** for the entity type in `EntityStyle.PathEntityTypeToSvgStatusStyle`. The `StatusStyle` instance defines stroke color, stroke width, fill color, fill opacity, dasharray — all attributes the polling dispatcher will push onto the path element on each refresh.
+
+For the existing palette of `StatusStyle` instances and the status-value vocabulary they emit (`active`, `idle`, `recent`, `past`, `smoke_detected`, etc.), see [`StatusStyle` in `hi_styles.py`](../../../src/hi/hi_styles.py) and the status-vocabulary discussion in [`entity-status-display.md`](entity-status-display.md#status-value-vocabulary).
+
+**Optional**: customize default path sizing in `EntityStyle.EntityTypePathInitialRadius` if your area type wants a non-default initial radius when first created.
+
+## Visual asset guidelines
+
+### SVG icon design
+
+- Design to a 64×64 viewbox unless registering a custom one.
+- Use `currentColor` for primary elements that should inherit state color through CSS.
+- Use fixed colors sparingly for distinctive details.
+- Maintain visibility at small scales (icons render down to ~16px in dense map views).
+- Follow the visual language of existing icons (similar stroke weights, fill patterns, metaphors).
+
+### Path styling
+
+- Provide meaningful defaults for the idle state.
+- Use color temperature progression (warm = active, cool = idle).
+- Consider opacity for layered visual effects (overlapping coverage zones).
+
+## Testing
+
+1. Create an instance of the new entity type via the admin or simulator.
+2. Position it on a location.
+3. Trigger state changes via the integration or simulator.
+4. Open the LocationView and verify:
+ - Icon renders at the expected position, scale, and rotation.
+ - Status changes update the visual (color tint, drop-shadow glow, etc.) within one polling cycle.
+ - Click target covers the whole icon (the `hi-entity-bg` rectangle).
+5. Open a collection containing the entity and verify the cards render reasonably; for entity types with custom panel needs see [`entity-status-panels.md`](entity-status-panels.md).
+
+## Simulator integration (optional)
+
+If the new entity type should be exercisable from the simulator, add it to `SimEntityType` in `hi.simulator.enums` and provide the matching simulator-side rendering and state machinery.
+
+## Related documentation
-### Key Configuration Files
-- **Icons**: `hi/apps/entity/templates/entity/svg/type.{TYPE}.svg`
-- **Registration**: `hi.hi_styles.EntityStyle.EntityTypesWithIcons`
-- **Path Types**: `hi.hi_styles.EntityStyle.EntityTypeClosedPaths/EntityTypeOpenPaths`
-- **Styling**: `hi.hi_styles.EntityStyle.PathEntityTypeToSvgStatusStyle`
-
-## Entity Display Methods
-
-Entities can be visually represented through two primary methods:
-
-### Icon-Based Representation
-- **EntityPosition**: Icon-based representation with position, scale, rotation
-- **Use Case**: Point entities like sensors, devices, controls
-- **Visual**: SVG icons with positioning and scaling
-
-### Path-Based Representation
-- **EntityPath**: SVG path representation for areas or complex shapes
-- **Use Case**: Areas, zones, complex geometric shapes
-- **Visual**: SVG paths with fill, stroke, and styling
-
-## Adding Visual Support for New Entity Types
-
-When adding visual support for a new entity type, follow these configuration steps:
-
-### 1. Choose Visual Display Method
-
-Determine whether the entity should be displayed as an icon or a path based on its nature:
-- **Icons**: Point-like entities (sensors, switches, cameras)
-- **Paths**: Area-like entities (rooms, zones, boundaries)
-
-### 2. Icon-Based Entity Configuration
-
-#### Create SVG Icon Asset
-
-Create an SVG icon for the new entity type in:
-```
-hi/apps/entity/templates/entity/svg/type.${TYPE}.svg
-```
-The `${TYPE}` must match the enum name in lowercase.
-
-**SVG Icon Requirements:**
-```svg
-<!-- Example: type.motion_sensor.svg -->
-<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
-<circle cx="32" cy="32" r="20" fill="currentColor"/>
-<path d="M20,32 L32,20 L44,32 L32,44 Z" fill="white" opacity="0.8"/>
-```
-
-**Key Requirements:**
-1. **Clickable Background**: Always include a rectangle covering the entire viewbox:
- ```svg
- <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
- ```
- This ensures the entire icon area is clickable for user interactions.
-
-2. **No Wrapping SVG Element**: File should contain only drawing commands, no `<svg>` wrapper
-
-3. **Standard Viewbox**: Default viewbox is `0 0 64 64` unless custom viewbox is registered
-
-#### Register Icon Configuration
-
-Add the new entity type to the icon registry:
-```python
-# hi.hi_styles.EntityStyle.EntityTypesWithIcons
-EntityTypesWithIcons = {
- EntityType.MOTION_SENSOR,
- EntityType.DOOR_SENSOR,
- EntityType.YOUR_NEW_TYPE, # Add here
- # ... existing types
-}
-```
-
-#### Custom Viewbox Configuration (Optional)
-
-If your icon requires a different viewbox than the default `0 0 64 64`, register it:
-```python
-# hi.hi_styles.EntityStyle.EntityTypeToIconViewbox
-EntityTypeToIconViewbox = {
- EntityType.YOUR_NEW_TYPE: "0 0 100 50", # Custom viewbox
- # ... existing custom viewboxes
-}
-```
-
-### 3. Path-Based Entity Configuration
-
-#### Choose Path Type
-
-Determine whether the entity represents a closed or open path:
-
-**Closed Paths** (filled areas):
-```python
-# hi.hi_styles.EntityStyle.EntityTypeClosedPaths
-EntityTypeClosedPaths = {
- EntityType.ROOM,
- EntityType.ZONE,
- EntityType.YOUR_NEW_AREA_TYPE, # Add here
-}
-```
-
-**Open Paths** (lines/curves):
-```python
-# hi.hi_styles.EntityStyle.EntityTypeOpenPaths
-EntityTypeOpenPaths = {
- EntityType.CORRIDOR,
- EntityType.BOUNDARY_LINE,
- EntityType.YOUR_NEW_LINE_TYPE, # Add here
-}
-```
-
-#### Define Visual Style
-
-Create or reference a visual style for the path entity:
-```python
-# hi.hi_styles.EntityStyle.PathEntityTypeToSvgStatusStyle
-PathEntityTypeToSvgStatusStyle = {
- EntityType.YOUR_NEW_TYPE: YourCustomSvgStatusStyle,
- # Reference existing style or create new one
-}
-```
-
-#### Create Custom SVG Status Style (If Needed)
-
-If no existing style fits your entity type, create a new style class:
-```python
-# In hi.hi_styles.EntityStyle
-class YourCustomSvgStatusStyle:
- """SVG styling for your custom entity type"""
-
- # Default styling
- default_fill = "#E0E0E0"
- default_stroke = "#808080"
- default_stroke_width = "2"
-
- # State-based styling
- active_fill = "#FF4444"
- active_stroke = "#CC0000"
-
- recent_fill = "#FF8844"
- recent_stroke = "#CC4400"
-
- past_fill = "#FFCC44"
- past_stroke = "#CC8800"
-
- idle_fill = "#44FF44"
- idle_stroke = "#00CC00"
-```
-
-#### Default Path Sizing (Optional)
-
-Configure default sizing for path entities:
-```python
-# hi.hi_styles.EntityStyle.EntityTypePathInitialRadius
-EntityTypePathInitialRadius = {
- EntityType.YOUR_NEW_TYPE: 25.0, # Default radius in pixels
- # ... existing size overrides
-}
-```
-
-## Visual Asset Guidelines
-
-### SVG Icon Design Standards
-
-**Size and Scaling:**
-- Design for 64x64 viewbox by default
-- Use simple, recognizable shapes
-- Ensure visibility at small scales (16px minimum)
-
-**Color Usage:**
-- Use `currentColor` for primary elements that should inherit entity state colors
-- Use fixed colors sparingly for distinctive details
-- Maintain sufficient contrast with background
-
-**Style Consistency:**
-- Follow existing icon visual language
-- Use similar stroke weights and fill patterns
-- Maintain consistent visual metaphors
-
-### Path Styling Standards
-
-**Stroke and Fill:**
-- Provide meaningful defaults for idle state
-- Ensure status colors are clearly distinguishable
-- Consider opacity for layered visual effects
-
-**Visual Hierarchy:**
-- Active states should be most prominent
-- Use color temperature progression (hot to cool)
-- Maintain readability across different backgrounds
-
-## Template Integration
-
-### Icon Entity Template Usage
-
-```django
-<!-- Icon entity in location view -->
-<g class="entity-group" data-entity-id="{{ entity.id }}">
- <use href="#icon-{{ entity.entity_type.name.lower }}"
- class="entity-icon {{ entity.get_status_css_classes }}"
- transform="translate({{ entity.position.x }}, {{ entity.position.y }})
- scale({{ entity.position.scale }})
- rotate({{ entity.position.rotation }})" />
-</g>
-```
-
-### Path Entity Template Usage
-
-```django
-<!-- Path entity in location view -->
-<g class="entity-group" data-entity-id="{{ entity.id }}">
- <path class="entity-path {{ entity.get_status_css_classes }}"
- d="{{ entity.path.svg_path }}"
- style="{{ entity.get_path_styling }}" />
-</g>
-```
-
-### Icon Symbol Definitions
-
-Icons must be included in the SVG symbol definitions:
-```django
-<!-- In base template or location template -->
-<defs>
- {% for entity_type in entity_types_with_icons %}
- <symbol id="icon-{{ entity_type.name.lower }}" viewBox="{{ entity_type.get_viewbox }}">
- {% include entity_type.get_icon_template %}
- </symbol>
- {% endfor %}
-</defs>
-```
-
-## Testing Visual Configuration
-
-### Visual Testing Checklist
-
-When adding new entity visual support:
-
-1. **Icon Visibility**: Verify icon displays correctly at various scales
-2. **State Changes**: Test all status states (active, recent, past, idle, unknown)
-3. **Color Contrast**: Ensure sufficient contrast in all color schemes
-4. **Click Targets**: Verify clickable area covers entire visual element
-5. **Template Rendering**: Test in location views, collection views, and status modals
-6. **Responsive Scaling**: Test on different screen sizes and zoom levels
-
-### Manual Testing Process
-
-1. Create test entity of new type
-2. Position entity in a location
-3. Trigger state changes through integration or simulation
-4. Verify visual feedback matches expected behavior
-5. Test entity in different view contexts
-
-## Simulator Integration (Optional)
-
-If the new entity type should be supported by the simulator:
-```python
-# hi.simulator.enums.SimEntityType
-SimEntityType = Enum('SimEntityType', [
- 'MOTION_SENSOR',
- 'DOOR_SENSOR',
- 'YOUR_NEW_TYPE', # Add corresponding simulator type
- # ... existing types
-])
-```
-
-
-## Real-World Workflow Examples
-
-### Workflow 1: Adding a New Entity Type with Custom Icon
-
-**Scenario**: Add support for a "Smart Door Lock" entity type with a custom icon and status colors.
-
-**Complete Implementation Process:**
-
-1. **Domain Setup** (Cross-reference: [Entity Patterns](../domain/entity-patterns.md))
- ```python
- # Add to hi.apps.entity.enums.EntityType
- class EntityType(Enum):
- # ... existing types
- SMART_DOOR_LOCK = ("smart_door_lock", "Smart Door Lock")
-
- # Add to appropriate group
- class EntityGroupType(Enum):
- SECURITY_DEVICES = "security_devices"
- # Add SMART_DOOR_LOCK to this group
- ```
-
-2. **Create Custom SVG Icon** ([Create SVG Icon Asset](#create-svg-icon-asset))
-
-Note: Do **not** use the `<g>` tag inside these SVGs!
-
- ```xml
- <!-- File: hi/apps/entity/templates/entity/svg/type.smart_door_lock.svg -->
- <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
- <!-- Door outline -->
- <rect x="20" y="10" width="24" height="44" fill="none" stroke="currentColor" stroke-width="2"/>
- <!-- Lock mechanism -->
- <circle cx="32" cy="32" r="6" fill="currentColor"/>
- <!-- Key hole -->
- <circle cx="32" cy="32" r="2" fill="white"/>
- <!-- Status indicator (will change color based on state) -->
- <circle cx="45" cy="15" r="4" fill="currentColor" opacity="0.8"/>
- ```
-
-3. **Register Icon Type** ([Register Icon Configuration](#register-icon-configuration))
- ```python
- # In hi.hi_styles.EntityStyle.EntityTypesWithIcons
- EntityTypesWithIcons = {
- EntityType.MOTION_SENSOR,
- EntityType.DOOR_SENSOR,
- EntityType.SMART_DOOR_LOCK, # Add this line
- # ... existing types
- }
- ```
-
-4. **Define Status-Specific Styling** ([Status Colors](../entity-status-display.md#status-color-system))
- ```css
- /* Add to your CSS file */
- .entity-svg.door-lock-locked {
- fill: var(--status-idle); /* Green - secure */
- stroke: #006600;
- }
-
- .entity-svg.door-lock-unlocked {
- fill: var(--status-recent); /* Orange - caution */
- stroke: #cc6600;
- }
-
- .entity-svg.door-lock-jammed {
- fill: var(--status-active); /* Red - problem */
- stroke: #cc0000;
- }
-
- .entity-svg.door-lock-offline {
- fill: var(--status-unknown); /* Gray - unknown */
- stroke: #666666;
- }
- ```
-
-5. **Test Visual Configuration** ([Testing Visual Configuration](#testing-visual-configuration))
- ```python
- # Create test entity
- test_door_lock = Entity.objects.create(
- name="Front Door Lock",
- entity_type=EntityType.SMART_DOOR_LOCK,
- location=test_location
- )
-
- # Create EntityPosition for icon display
- EntityPosition.objects.create(
- entity=test_door_lock,
- x=100, y=150,
- scale=1.0, rotation=0
- )
- ```
-
-6. **Verify in Location View**
- - Navigate to location view containing the door lock
- - Verify icon displays correctly
- - Test status changes trigger color updates
- - Check click interactions work (clickable background)
-
-**Expected Result**: Smart door lock appears as custom icon with status-based color changes.
-
----
-
-### Workflow 2: Converting Icon Entity to Path Entity
-
-**Scenario**: Motion sensor needs to represent a coverage area rather than just a point location.
-
-**Migration Process:**
-
-1. **Plan Path Representation** ([Entity Display Methods](#entity-display-methods))
- ```python
- # Motion sensor coverage area as circular path
- # Center: sensor position
- # Radius: detection range
- coverage_radius = 50 # units in SVG coordinates
- center_x, center_y = 200, 300
- ```
-
-2. **Remove from Icon Registry** ([Icon Configuration](#register-icon-configuration))
- ```python
- # Remove from hi.hi_styles.EntityStyle.EntityTypesWithIcons
- EntityTypesWithIcons = {
- # EntityType.MOTION_SENSOR, # Comment out or remove
- EntityType.DOOR_SENSOR,
- # ... other types
- }
- ```
-
-3. **Add to Path Registry** ([Path-Based Configuration](#path-based-entity-configuration))
- ```python
- # Add to hi.hi_styles.EntityStyle.EntityTypeClosedPaths
- EntityTypeClosedPaths = {
- EntityType.ROOM,
- EntityType.MOTION_SENSOR, # Add this line
- # ... existing types
- }
- ```
-
-4. **Create SVG Path Data** ([SVG Path Requirements](#path-based-entity-configuration))
- ```python
- import math
-
- def create_circular_path(center_x, center_y, radius):
- """Create SVG path for circular coverage area"""
- # Create circle using path commands (more flexible than <circle>)
- path_data = (
- f"M {center_x - radius} {center_y} "
- f"A {radius} {radius} 0 0 1 {center_x + radius} {center_y} "
- f"A {radius} {radius} 0 0 1 {center_x - radius} {center_y} "
- f"Z"
- )
- return path_data
-
- # Update existing motion sensor entities
- for motion_sensor in Entity.objects.filter(entity_type=EntityType.MOTION_SENSOR):
- # Get current position
- position = motion_sensor.entityposition_set.first()
- if position:
- # Create EntityPath with coverage area
- EntityPath.objects.create(
- entity=motion_sensor,
- svg_path=create_circular_path(position.x, position.y, 50)
- )
- # Remove EntityPosition
- position.delete()
- ```
-
-5. **Define Path Styling** ([Define Visual Style](#define-visual-style))
- ```python
- # Create new style class in hi.hi_styles.EntityStyle
- class MotionSensorPathStyle:
- default_fill = "#E0E0E0"
- default_stroke = "#808080"
- default_opacity = 0.3
-
- active_fill = "#FF4444"
- active_stroke = "#CC0000"
- active_opacity = 0.6
-
- recent_fill = "#FF8844"
- recent_stroke = "#CC4400"
- recent_opacity = 0.5
-
- idle_fill = "#44FF44"
- idle_stroke = "#00CC00"
- idle_opacity = 0.3
-
- # Register the style
- PathEntityTypeToSvgStatusStyle = {
- EntityType.MOTION_SENSOR: MotionSensorPathStyle,
- # ... existing mappings
- }
- ```
-
-6. **Update Templates** (Cross-reference: [Template Integration](#template-integration))
- ```django
- <!-- Motion sensors now render as paths instead of icons -->
- {% for entity in entities %}
- {% if entity.entity_type.name == 'MOTION_SENSOR' %}
- <path class="entity-path {{ entity.get_status_css_classes }}"
- data-entity-id="{{ entity.id }}"
- d="{{ entity.path.svg_path }}"
- style="{{ entity.get_path_styling }}"/>
- {% elif entity.has_position %}
- <!-- Other icon entities -->
- <use href="#icon-{{ entity.entity_type.name.lower }}"/>
- {% endif %}
- {% endfor %}
- ```
-
-**Expected Result**: Motion sensors display as coverage areas that show detection zones rather than point icons.
-
-## Related Documentation
-- Entity domain patterns: [Entity Patterns](../domain/entity-patterns.md)
-- Status display implementation: [Entity Status Display](entity-status-display.md)
-- Style guidelines: [Style Guidelines](style-guidelines.md)
-- Icon system: [Icon System](icon-system.md)
-- Frontend guidelines: [Frontend Guidelines](frontend-guidelines.md)
+- [Architecture overview](entity-display-overview.md)
+- [Polling-update contract](entity-status-display.md)
+- [Panel authoring](entity-status-panels.md)
+- [Icon system](icon-system.md)
+- [Style guidelines](style-guidelines.md)
diff --git a/src/hi/apps/alert/templates/alert/modals/alert_details.html b/src/hi/apps/alert/templates/alert/modals/alert_details.html
index aaa64b34..a639be58 100644
--- a/src/hi/apps/alert/templates/alert/modals/alert_details.html
+++ b/src/hi/apps/alert/templates/alert/modals/alert_details.html
@@ -59,7 +59,7 @@
</h6>
</div>
<div class="card-body p-2">
- <img class="img-fluid" src="{{ video_stream.source_url }}" alt="{{ alert_visual_content.alarm.title }}">
+ <img class="img-fluid" data-video-stream src="{{ video_stream.source_url }}" alt="{{ alert_visual_content.alarm.title }}">
{% if not alert_visual_content.is_from_latest %}
<small class="text-muted d-block mt-1">From: {{ alert_visual_content.alarm.timestamp|localtime|date:"M j, Y H:i" }}</small>
{% endif %}
@@ -113,7 +113,7 @@
<small class="text-muted">Source {{ video_source.index }} - {{ video_source.alarm.timestamp|localtime|date:"M j H:i" }}</small>
</div>
<div class="card-body p-2">
- <img class="img-fluid" src="{{ video_stream.source_url }}" alt="Source {{ video_source.index }}">
+ <img class="img-fluid" data-video-stream src="{{ video_stream.source_url }}" alt="Source {{ video_source.index }}">
</div>
</div>
{% endif %}
diff --git a/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html b/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html
index c4c80791..0131300c 100644
--- a/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html
+++ b/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html
@@ -5,7 +5,7 @@
{% sensor_response_video_stream sensor_response as video_stream %}
{% if video_stream and video_stream.source_url %}
<div class="mb-2">
- <img class="img-fluid" src="{{ video_stream.source_url }}" alt="{{ alarm.title }}">
+ <img class="img-fluid" data-video-stream src="{{ video_stream.source_url }}" alt="{{ alarm.title }}">
</div>
{% elif sensor_response.source_image_url %}
<!-- Fallback to image when video stream is not available -->
diff --git a/src/hi/apps/collection/collection_manager.py b/src/hi/apps/collection/collection_manager.py
index ef3a179a..90020a9e 100644
--- a/src/hi/apps/collection/collection_manager.py
+++ b/src/hi/apps/collection/collection_manager.py
@@ -10,6 +10,7 @@ from hi.apps.entity.enums import EntityGroupType
from hi.apps.entity.models import Entity
from hi.apps.location.models import Location, LocationView
from hi.apps.location.svg_item_factory import SvgItemFactory
+from hi.apps.monitor.display_data import EntityDisplayData
from hi.apps.monitor.status_display_manager import StatusDisplayManager
from .models import (
@@ -66,10 +67,14 @@ class CollectionManager(Singleton):
entity_list = [ x.entity for x in collection_entity_list ]
entity_status_data_list = StatusDisplayManager().get_entity_status_data_list(
entities = entity_list,
- )
+ )
+ entity_display_data_list = [
+ EntityDisplayData( entity_status_data = d )
+ for d in entity_status_data_list
+ ]
return CollectionData(
collection = collection,
- entity_status_data_list = entity_status_data_list,
+ entity_status_data_list = entity_display_data_list,
)
def create_collection( self, name : str ) -> Collection:
diff --git a/src/hi/apps/collection/edit/views.py b/src/hi/apps/collection/edit/views.py
index 64139841..e91e1384 100644
--- a/src/hi/apps/collection/edit/views.py
+++ b/src/hi/apps/collection/edit/views.py
@@ -228,7 +228,6 @@ class CollectionPositionEditView( View, CollectionViewMixin ):
svg_icon_item = SvgItemFactory().create_svg_icon_item(
item = collection_position.collection,
position = collection_position,
- css_class = '',
)
set_attributes_map = {
svg_icon_item.html_id: {
diff --git a/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html b/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html
index 06ea9783..ab72483b 100644
--- a/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html
+++ b/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html
@@ -1,3 +1,4 @@
+{% load state_panel_tags %}
<div class="card h-100">
<div class="card-body p-3">
{% include "collection/panes/entity_card_title.html" with entity_status_data=entity_status_data %}
@@ -6,7 +7,7 @@
{% include "console/panes/entity_video_stream_w_link.html" with entity=entity_status_data.entity %}
</div>
{% else %}
- {% include "collection/panes/entity_state_list.html" with entity_state_status_data_list=entity_status_data.state_status_data_list %}
+ {% render_entity_status_panel entity_status_data "grid" %}
{% endif %}
</div>
</div>
diff --git a/src/hi/apps/collection/templates/collection/panes/entity_card_list.html b/src/hi/apps/collection/templates/collection/panes/entity_card_list.html
index e789a1a3..6d7ca73e 100644
--- a/src/hi/apps/collection/templates/collection/panes/entity_card_list.html
+++ b/src/hi/apps/collection/templates/collection/panes/entity_card_list.html
@@ -1,3 +1,4 @@
+{% load state_panel_tags %}
<div class="card h-100">
<div class="card-body">
<div class="d-flex">
@@ -10,10 +11,9 @@
</div>
{% else %}
<div class="entity-content-section flex-grow-1 ml-3">
- {% include "collection/panes/entity_state_list.html" with entity_state_status_data_list=entity_status_data.state_status_data_list %}
+ {% render_entity_status_panel entity_status_data "list" %}
</div>
{% endif %}
</div>
</div>
</div>
-
diff --git a/src/hi/apps/collection/templates/collection/panes/entity_state_row.html b/src/hi/apps/collection/templates/collection/panes/entity_state_row.html
deleted file mode 100644
index b7f9dbc7..00000000
--- a/src/hi/apps/collection/templates/collection/panes/entity_state_row.html
+++ /dev/null
@@ -1,26 +0,0 @@
-{% load common_tags %}
-{% load icons %}
-{% with sensor_response=entity_state_status_data.latest_sensor_response %}
-
-{% if entity_state_status_data.controller_data_list %}
-{% for controller_data in entity_state_status_data.controller_data_list %}
-<div class="text-muted text-center"><small>{{ controller_data.controller.name }}</small></div>
-{% include "control/panes/controller_data.html" with controller_data=controller_data in_modal_context=True %}
-{% endfor %}
-
-{% elif entity_state_status_data.sensor_response_list %}
-<div class="text-muted text-center"><small>{{ sensor_response.sensor.name }}</small></div>
-{# Per-state CSS class wrapper so polling updates land via the #}
-{# entity_state_status.js dispatcher (selector: .{css_class}). #}
-<div class="{{ sensor_response.css_class }}">
- {% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}
-</div>
-
-{% elif entity_state_status_data.has_sensor %}
-<div class="alert alert-info">{{ entity_state_status_data.entity_state.name }}: awaiting sensor reading.</div>
-
-{% else %}
-<div class="alert alert-info">{{ entity_state_status_data.entity_state.name }}: no sensors or controllers defined.</div>
-{% endif %}
-
-{% endwith %}
diff --git a/src/hi/apps/collection/transient_models.py b/src/hi/apps/collection/transient_models.py
index 4000cae0..8e993f45 100644
--- a/src/hi/apps/collection/transient_models.py
+++ b/src/hi/apps/collection/transient_models.py
@@ -4,7 +4,7 @@ from typing import List
from hi.apps.collection.edit.forms import CollectionEditForm, CollectionPositionForm
from hi.apps.entity.enums import EntityGroupType
from hi.apps.entity.models import Entity
-from hi.apps.monitor.transient_models import EntityStatusData
+from hi.apps.monitor.display_data import EntityDisplayData
from .models import Collection
@@ -13,7 +13,7 @@ from .models import Collection
class CollectionData:
collection : Collection
- entity_status_data_list : List[ EntityStatusData ]
+ entity_status_data_list : List[ EntityDisplayData ]
def to_template_context(self):
return {
diff --git a/src/hi/apps/common/svg_models.py b/src/hi/apps/common/svg_models.py
index e2f7dd72..d3f599ba 100644
--- a/src/hi/apps/common/svg_models.py
+++ b/src/hi/apps/common/svg_models.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from decimal import Decimal, ROUND_HALF_UP
-from typing import List
+from typing import List, Optional
from django.core.exceptions import ValidationError
from django.db import models
@@ -110,7 +110,7 @@ class SvgIconItem:
"""
html_id : str
- css_class : str
+ state_id : Optional[ int ]
status_value : str
template_name : str
bounding_box : SvgViewBox
@@ -154,7 +154,7 @@ class SvgPathItem:
"""
html_id : str
- css_class : str
+ state_id : Optional[ int ]
svg_path : str
stroke_color : str
stroke_width : float
diff --git a/src/hi/apps/console/templates/console/panes/camera_controls.html b/src/hi/apps/console/templates/console/panes/camera_controls.html
index 7bfceef7..162acd35 100644
--- a/src/hi/apps/console/templates/console/panes/camera_controls.html
+++ b/src/hi/apps/console/templates/console/panes/camera_controls.html
@@ -6,8 +6,8 @@
<a href="{% url 'console_entity_video_stream_dispatch' entity_id=camera_data.entity.id %}"
data-entity-id="{{ camera_data.entity.id }}"
data-async="#main-content"
- class="btn btn-primary btn-control btn-camera {% if camera_data.status_entity_state %}{{ camera_data.status_entity_state.css_class }}{% endif %}"
- {% if camera_data.status_entity_state %}status=""{% endif %}
+ class="btn btn-primary btn-control btn-camera"
+ {% if camera_data.status_entity_state %}data-state-id="{{ camera_data.status_entity_state.id }}" data-status status=""{% endif %}
role="button">
{{ camera_data.short_name }}
</a>
diff --git a/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html
index 2885c709..3fdc64aa 100644
--- a/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html
+++ b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html
@@ -115,7 +115,7 @@
<div class="video-container mb-3" role="img" aria-label="Event video playback">
{% sensor_response_video_stream sensor_history_data.current_sensor_response as video_stream %}
{% if video_stream and video_stream.source_url %}
- <img class="img-fluid" src="{{ video_stream.source_url }}" alt="Video recording from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}" data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}" onerror="this.style.display='none'; this.outerHTML='<div class=\'alert alert-warning text-center d-flex align-items-center justify-content-center\' style=\'min-height: 240px;\'><div><div class=\'mb-2\'>[VIDEO]</div><h6>Video No Longer Available</h6></div></div>'">
+ <img class="img-fluid" data-video-stream src="{{ video_stream.source_url }}" alt="Video recording from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}" data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}" onerror="this.style.display='none'; this.outerHTML='<div class=\'alert alert-warning text-center d-flex align-items-center justify-content-center\' style=\'min-height: 240px;\'><div><div class=\'mb-2\'>[VIDEO]</div><h6>Video No Longer Available</h6></div></div>'">
{% elif sensor_history_data.current_sensor_response.source_image_url %}
<!-- Fallback to image when video stream is not available -->
<img class="img-fluid" src="{{ sensor_history_data.current_sensor_response.source_image_url }}" alt="Image from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}" data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}">
diff --git a/src/hi/apps/console/templates/console/panes/entity_video_stream.html b/src/hi/apps/console/templates/console/panes/entity_video_stream.html
index f5f28675..b17c4553 100644
--- a/src/hi/apps/console/templates/console/panes/entity_video_stream.html
+++ b/src/hi/apps/console/templates/console/panes/entity_video_stream.html
@@ -2,6 +2,11 @@
{% entity_video_stream entity as video_stream %}
{% if video_stream and video_stream.source_url %}
<div class="video-container">
- <img class="img-fluid" src="{{ video_stream.source_url }}" alt="{{ entity.name }} Live Video">
+ {# ``data-video-stream`` opts this <img> into the connection #}
+{# manager's force-close-on-unload lifecycle. ``.video-container`` #}
+{# on the parent is purely styling (also used by historical video #}
+{# playback containers); the data attribute is the behavior marker. #}
+ <img class="img-fluid" data-video-stream
+ src="{{ video_stream.source_url }}" alt="{{ entity.name }} Live Video">
</div>
{% endif %}
diff --git a/src/hi/apps/control/templates/control/panes/continuous_slider.html b/src/hi/apps/control/templates/control/panes/continuous_slider.html
index ee977749..ac46394c 100644
--- a/src/hi/apps/control/templates/control/panes/continuous_slider.html
+++ b/src/hi/apps/control/templates/control/panes/continuous_slider.html
@@ -33,7 +33,9 @@ Parameters:
max="{{ slider_max }}"
{% if slider_step %}step="{{ slider_step }}"{% endif %}
value="{{ controller_data.latest_sensor_response.value|default_if_none:slider_default }}"
- class="{{ controller_data.css_class }} {{ DIVID.CONTROLLER_SLIDER_CLASS }} {{ slider_class }}"
+ class="{{ DIVID.CONTROLLER_SLIDER_CLASS }} {{ slider_class }}"
+ data-state-id="{{ controller_data.entity_state.id }}"
+ data-controller-value
{{ DIVID.CONTROLLER_DISPLAY_TARGET_ATTR }}=".hi-continuous-slider-value"
{{ DIVID.CONTROLLER_DISPLAY_FORMAT_ATTR }}="{n}{{ display_unit }}"
onchange-async="true"
diff --git a/src/hi/apps/control/templates/control/panes/continuous_slider_with_units.html b/src/hi/apps/control/templates/control/panes/continuous_slider_with_units.html
index d65e3561..88f902e5 100644
--- a/src/hi/apps/control/templates/control/panes/continuous_slider_with_units.html
+++ b/src/hi/apps/control/templates/control/panes/continuous_slider_with_units.html
@@ -35,7 +35,9 @@ Optional (forwarded to slider chrome):
max="{{ display_max.magnitude }}"
{% if slider_step %}step="{{ slider_step }}"{% endif %}
value="{{ display_value.magnitude }}"
- class="{{ controller_data.css_class }} {{ DIVID.CONTROLLER_SLIDER_CLASS }} {{ slider_class }}"
+ class="{{ DIVID.CONTROLLER_SLIDER_CLASS }} {{ slider_class }}"
+ data-state-id="{{ controller_data.entity_state.id }}"
+ data-controller-value
{{ DIVID.CONTROLLER_DISPLAY_TARGET_ATTR }}=".hi-continuous-slider-value"
{{ DIVID.CONTROLLER_DISPLAY_FORMAT_ATTR }}="{n}{{ display_value.unit_symbol }}"
onchange-async="true"
diff --git a/src/hi/apps/control/templates/control/panes/controller_data.html b/src/hi/apps/control/templates/control/panes/controller_data.html
index f42996db..95c026f8 100644
--- a/src/hi/apps/control/templates/control/panes/controller_data.html
+++ b/src/hi/apps/control/templates/control/panes/controller_data.html
@@ -1,22 +1,22 @@
{% load common_tags %}
{% load control_tags %}
+{% load icons %}
{% generate_uuid as unique_id %}
-<div id="hi-controller-{{ controller_data.controller.id }}-{{ unique_id }}"
- class="{{ controller_data.css_class }}" >
+<div id="hi-controller-{{ controller_data.controller.id }}-{{ unique_id }}">
<form action="{% url 'control_controller' controller_id=controller_data.controller.id %}"
method="post"
- class="form" data-async="#hi-controller-{{ controller_data.controller.id }}-{{ unique_id }}" data-mode="replace"{% if in_modal_context %} data-stay-in-modal="true"{% endif %}>
+ class="form" data-async="#hi-controller-{{ controller_data.controller.id }}-{{ unique_id }}" data-mode="replace" data-stay-in-modal="true">
{% csrf_token %}
- <input type="hidden" name="response_context" value="{% if in_modal_context %}modal{% else %}page{% endif %}">
-
{% include_controller_widget controller_data.controller %}
{% if controller_data.error_list %}
- <div class="text-danger">
- <ul>
+ <div class="alert alert-danger d-flex align-items-start mt-2 py-2 small"
+ role="alert">
+ {% icon "warning" size="sm" css_class="mr-2 mt-1" %}
+ <div>
{% for msg in controller_data.error_list %}
- <li>{{ msg }}</li>
+ <div>{{ msg }}</div>
{% endfor %}
- </ul>
+ </div>
</div>
{% endif %}
</form>
diff --git a/src/hi/apps/control/templates/control/panes/controller_data_row.html b/src/hi/apps/control/templates/control/panes/controller_data_row.html
index b10b8a6f..a0cedd99 100644
--- a/src/hi/apps/control/templates/control/panes/controller_data_row.html
+++ b/src/hi/apps/control/templates/control/panes/controller_data_row.html
@@ -16,6 +16,6 @@
</div>
</div>
<div class="col-6 align-self-center">
- {% include "control/panes/controller_data.html" with controller_data=controller_data in_modal_context=True %}
+ {% include "control/panes/controller_data.html" with controller_data=controller_data %}
</div>
</div>
diff --git a/src/hi/apps/control/templates/control/panes/controller_discrete.html b/src/hi/apps/control/templates/control/panes/controller_discrete.html
index 3fe5fdbf..cc2f7ac3 100644
--- a/src/hi/apps/control/templates/control/panes/controller_discrete.html
+++ b/src/hi/apps/control/templates/control/panes/controller_discrete.html
@@ -1,7 +1,9 @@
<div class="discrete-control">
<select id="{{ attribute_form.value.id_for_label }}"
name="value"
- class="{{ controller_data.css_class }} discrete-select form-select"
+ class="discrete-select form-select"
+ data-state-id="{{ controller_data.entity_state.id }}"
+ data-controller-value
onchange-async="true"
data-controller-id="{{ controller_data.controller.id }}">
{% for value, label in controller_data.controller.choices %}
diff --git a/src/hi/apps/control/templates/control/panes/controller_on_off.html b/src/hi/apps/control/templates/control/panes/controller_on_off.html
index 4a06600a..e4f85156 100644
--- a/src/hi/apps/control/templates/control/panes/controller_on_off.html
+++ b/src/hi/apps/control/templates/control/panes/controller_on_off.html
@@ -3,7 +3,9 @@
<label class="switch-modern">
<input type="checkbox"
name="value"
- class="{{ controller_data.css_class }} switch-input"
+ class="switch-input"
+ data-state-id="{{ controller_data.entity_state.id }}"
+ data-status data-controller-value
{% if controller_data.latest_sensor_response.is_on %}checked="true"{% endif %}
status="{{ controller_data.latest_sensor_response.value }}"
data-on-text="{{ on_text }}"
diff --git a/src/hi/apps/control/templates/control/panes/controller_open_close.html b/src/hi/apps/control/templates/control/panes/controller_open_close.html
index 46f0c982..67e87b97 100644
--- a/src/hi/apps/control/templates/control/panes/controller_open_close.html
+++ b/src/hi/apps/control/templates/control/panes/controller_open_close.html
@@ -4,7 +4,9 @@
<input type="checkbox"
name="value"
value="open"
- class="{{ controller_data.css_class }} switch-input"
+ class="switch-input"
+ data-state-id="{{ controller_data.entity_state.id }}"
+ data-status data-controller-value
{% if controller_data.latest_sensor_response.is_open %}checked="true"{% endif %}
status="{{ controller_data.latest_sensor_response.value }}"
data-on-text="{{ on_text }}"
diff --git a/src/hi/apps/control/view_mixins.py b/src/hi/apps/control/view_mixins.py
index ba955ba5..58c39418 100644
--- a/src/hi/apps/control/view_mixins.py
+++ b/src/hi/apps/control/view_mixins.py
@@ -46,8 +46,7 @@ class ControlViewMixin:
request : HttpRequest,
controller : Controller,
error_list : List[ str ],
- override_sensor_value : str = None,
- in_modal_context : bool = False ) -> HttpResponse:
+ override_sensor_value : str = None ) -> HttpResponse:
latest_sensor_response = StatusDisplayManager().get_latest_sensor_response(
entity_state = controller.entity_state,
@@ -59,9 +58,8 @@ class ControlViewMixin:
)
if controller_data.latest_sensor_response and ( override_sensor_value is not None ):
controller_data.latest_sensor_response.value = override_sensor_value
-
+
context = {
'controller_data': controller_data,
- 'in_modal_context': in_modal_context,
}
return render( request, 'control/panes/controller_data.html', context )
diff --git a/src/hi/apps/control/views.py b/src/hi/apps/control/views.py
index b4b278a9..0af83a5e 100644
--- a/src/hi/apps/control/views.py
+++ b/src/hi/apps/control/views.py
@@ -69,15 +69,11 @@ class ControllerView( View, ControlViewMixin, ControllerMixin ):
override_value = override_sensor_value,
)
- response_context = request.POST.get('response_context', 'page')
- in_modal_context = bool( response_context == 'modal' )
-
return self.controller_data_response(
request = request,
controller = controller,
error_list = controller_outcome.error_list,
override_sensor_value = override_sensor_value,
- in_modal_context = in_modal_context,
)
def _get_value_for_missing_input( self, controller : Controller ) -> str:
diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.py
index 9a90729c..ecb6e8b4 100644
--- a/src/hi/apps/entity/edit/views.py
+++ b/src/hi/apps/entity/edit/views.py
@@ -223,7 +223,6 @@ class EntityPositionEditView( View, EntityViewMixin ):
svg_icon_item = SvgItemFactory().create_svg_icon_item(
item = entity_position.entity,
position = entity_position,
- css_class = '',
)
set_attributes_map = {
svg_icon_item.html_id: {
diff --git a/src/hi/apps/entity/state_panel_dispatch.py b/src/hi/apps/entity/state_panel_dispatch.py
new file mode 100644
index 00000000..bf2d62df
--- /dev/null
+++ b/src/hi/apps/entity/state_panel_dispatch.py
@@ -0,0 +1,69 @@
+"""Template-path resolution for EntityStatusPanel rendering.
+
+A panel is a self-contained bundle of templates, CSS, and (optionally)
+JS that defines how an entity of a particular EntityType is rendered
+in one of three display contexts: the EntityStatusView modal body, the
+collection list card, and the collection grid card.
+
+``modal.html`` is the panel's required default template. ``list.html``
+and ``grid.html`` are optional per-context overrides. The framework
+provides fallback templates for any entity type that has no panel."""
+
+from typing import List
+
+from django.template import Template
+from django.template.exceptions import TemplateDoesNotExist
+from django.template.loader import get_template
+
+from hi.apps.entity.enums import EntityType
+
+
+SUPPORTED_DISPLAY_CONTEXTS = ( 'modal', 'list', 'grid' )
+
+# Per-context framework fallback used when the entity's type has no
+# panel directory. All three are framework-provided and guaranteed
+# to exist.
+FRAMEWORK_FALLBACK_TEMPLATES = {
+ 'modal': 'entity/state_panels/fallback/modal.html',
+ 'list': 'entity/state_panels/fallback/list.html',
+ 'grid': 'entity/state_panels/fallback/grid.html',
+}
+
+
+def resolve_panel_template(
+ entity_type : EntityType,
+ display_context_name : str,
+) -> Template:
+ """Return the first existing template for the (entity_type,
+ display_context) pair along the three-step resolution chain:
+
+ 1. Panel's context-specific template (``<type>/<context>.html``).
+ 2. Panel's required default template (``<type>/modal.html``).
+ 3. Framework fallback for the context (always exists)."""
+
+ if display_context_name not in SUPPORTED_DISPLAY_CONTEXTS:
+ raise ValueError(
+ f'Unsupported display context: {display_context_name!r}. '
+ f'Expected one of {SUPPORTED_DISPLAY_CONTEXTS}.'
+ )
+
+ type_lower = entity_type.name.lower()
+ for candidate in _candidate_paths( type_lower, display_context_name ):
+ try:
+ return get_template( candidate )
+ except TemplateDoesNotExist:
+ continue
+
+ raise TemplateDoesNotExist(
+ f'No panel template found for entity_type={entity_type.name} '
+ f'context={display_context_name}; framework fallback at '
+ f'{FRAMEWORK_FALLBACK_TEMPLATES[display_context_name]} is missing.'
+ )
+
+
+def _candidate_paths( type_lower : str, display_context_name : str ) -> List[ str ]:
+ return [
+ f'entity/state_panels/{type_lower}/{display_context_name}.html',
+ f'entity/state_panels/{type_lower}/modal.html',
+ FRAMEWORK_FALLBACK_TEMPLATES[ display_context_name ],
+ ]
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status.html b/src/hi/apps/entity/templates/entity/modals/entity_status.html
index 314d6eae..1f33be63 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_status.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_status.html
@@ -1,15 +1,48 @@
{% extends "modals/action_3.html" %}
{% load icons %}
{% load common_tags %}
+{% load static %}
+{% load state_panel_tags %}
+{% load integration_tags %}
{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}
{% block title_text %}
-Status
+{{ entity.name }}
+{% endblock %}
+
+{# Framework-level subheader: entity type icon + label on the left, #}
+{# integration logo centered (when present), "Status" label on the #}
+{# right. Panels render their body below without repeating any of #}
+{# this identifying chrome. #}
+{% block subheader %}
+<div class="hi-entity-status-subheader d-flex align-items-center px-3 py-1 border-bottom">
+ <div class="hi-entity-status-subheader__left d-flex align-items-center">
+ {% if display_only_svg_icon_item %}
+ <span class="hi-entity-status-subheader__type-icon mr-2">
+ {% include "entity/panes/entity_display_only_svg_icon.html" with svg_icon_item=display_only_svg_icon_item %}
+ </span>
+ {% endif %}
+ <small class="text-muted text-uppercase">{{ entity.entity_type.label }}</small>
+ </div>
+ <div class="hi-entity-status-subheader__center flex-grow-1 text-center">
+ {% if entity.integration_id %}
+ {% integration_logo_path entity as logo_path %}
+ {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline">{% endif %}
+ {% elif entity.previous_integration_id %}
+ {% previous_integration_logo_path entity as prev_logo_path %}
+ {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached">{% endif %}
+ {% endif %}
+ </div>
+ <div class="hi-entity-status-subheader__right">
+ <small class="text-muted text-uppercase">Status</small>
+ </div>
+</div>
{% endblock %}
{% block body %}
-{% include_with_fallback entity.entity_type.entity_status_template_name "entity/modals/entity_status_default.html" %}
+{% integration_health_banner entity.integration_id "Values shown may be stale; controls may not respond." %}
+{% render_entity_status_panel entity_status_data "modal" %}
{% endblock %}
{% block action_left %}
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status_ceiling_fan.html b/src/hi/apps/entity/templates/entity/modals/entity_status_ceiling_fan.html
deleted file mode 100644
index 6c72371b..00000000
--- a/src/hi/apps/entity/templates/entity/modals/entity_status_ceiling_fan.html
+++ /dev/null
@@ -1,4 +0,0 @@
-{# Reserved for ceiling-fan-specific EntityStatusView layout. #}
-{# Delegates to the default flat-list template until a custom #}
-{# layout is needed. #}
-{% include "entity/modals/entity_status_default.html" %}
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status_default.html b/src/hi/apps/entity/templates/entity/modals/entity_status_default.html
deleted file mode 100644
index 868396f7..00000000
--- a/src/hi/apps/entity/templates/entity/modals/entity_status_default.html
+++ /dev/null
@@ -1,40 +0,0 @@
-{% load static %}
-{% load video_tags %}
-{% load integration_tags %}
-
-<div class="d-flex justify-content-between mb-2">
- {% if display_only_svg_icon_item %}
- <div class="display-only-svg-icon pr-2">
- {% include "entity/panes/entity_display_only_svg_icon.html" with svg_icon_item=display_only_svg_icon_item %}
- </div>
- {% endif %}
- <div class="text-center">
- <div class="h4 mb-0">{{ entity.name }}</div>
- {% if entity.integration_id %}
- <div class="text-muted">
- <small>
- {% integration_logo_path entity as logo_path %}
- {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline mr-1">{% endif %}
- From: {% integration_display_name entity %}
- </small>
- </div>
- {% elif entity.previous_integration_id %}
- <div class="text-muted font-italic">
- <small>
- {% previous_integration_logo_path entity as prev_logo_path %}
- {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}
- Detached from: {% previous_integration_display_name entity %}
- </small>
- </div>
- {% endif %}
- </div>
- <div>
- <div class="h5 text-muted">{{ entity.entity_type.label }}</div>
- </div>
-</div>
-
-<div>
- {% include "console/panes/entity_video_stream_w_link.html" with entity=entity_for_video %}
-</div>
-
-{% include "entity/panes/entity_state_status_list.html" with entity_state_status_data_list=state_status_data_list in_modal_context=True %}
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status_thermostat.html b/src/hi/apps/entity/templates/entity/modals/entity_status_thermostat.html
deleted file mode 100644
index f187c03c..00000000
--- a/src/hi/apps/entity/templates/entity/modals/entity_status_thermostat.html
+++ /dev/null
@@ -1,4 +0,0 @@
-{# Reserved for thermostat-specific EntityStatusView layout. #}
-{# Delegates to the default flat-list template until a custom #}
-{# layout (e.g., graphical dial / mode picker) is needed. #}
-{% include "entity/modals/entity_status_default.html" %}
diff --git a/src/hi/apps/entity/templates/entity/panes/entity_state_status_list.html b/src/hi/apps/entity/templates/entity/panes/entity_state_status_list.html
deleted file mode 100644
index 64d7fb78..00000000
--- a/src/hi/apps/entity/templates/entity/panes/entity_state_status_list.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<div>
- {% for entity_state_status_data in entity_state_status_data_list %}
- <div class="my-2">
- {% include "entity/panes/entity_state_status_row.html" with entity_state_status_data=entity_state_status_data %}
- </div>
- {% endfor %}
-</div>
diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/grid.html b/src/hi/apps/entity/templates/entity/state_panels/camera/grid.html
new file mode 100644
index 00000000..38ef4928
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/grid.html
@@ -0,0 +1,17 @@
+{# Camera EntityStatusPanel — collection grid card context. Video fills #}
+{# the cell with a name overlay along the bottom. #}
+<div class="hi-state-panel-camera hi-state-panel-camera--grid">
+
+ <div class="stream">
+ {% if entity.has_video_stream %}
+ {% include "console/panes/entity_video_stream_w_link.html" with entity=entity %}
+ {% else %}
+ <div class="stream-unavailable">Offline</div>
+ {% endif %}
+ </div>
+
+ <div class="grid-overlay">
+ <div class="entity-name">{{ entity.name }}</div>
+ </div>
+
+</div>
diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/list.html b/src/hi/apps/entity/templates/entity/state_panels/camera/list.html
new file mode 100644
index 00000000..8a9a769f
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/list.html
@@ -0,0 +1,16 @@
+{# Camera EntityStatusPanel — collection list card context. #}
+<div class="hi-state-panel-camera hi-state-panel-camera--list">
+
+ <div class="stream">
+ {% if entity.has_video_stream %}
+ {% include "console/panes/entity_video_stream_w_link.html" with entity=entity %}
+ {% else %}
+ <div class="stream-unavailable">Offline</div>
+ {% endif %}
+ </div>
+
+ <div class="list-meta">
+ <div class="entity-name">{{ entity.name }}</div>
+ </div>
+
+</div>
diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html b/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html
new file mode 100644
index 00000000..2140053c
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html
@@ -0,0 +1,23 @@
+{# Camera EntityStatusPanel — modal context. #}
+{# Reuses the existing video-stream wrapper for the live frame and the #}
+{# existing per-state row list for any controllers/sensors the camera #}
+{# entity exposes (e.g., ZoneMinder Function dropdown, connectivity #}
+{# sensors). No new JS — the video stream rendering and click-through to #}
+{# the full-page video pane all go through the established machinery. #}
+<div class="hi-state-panel-camera hi-state-panel-camera--modal">
+
+ <div class="stream">
+ {% if entity.has_video_stream %}
+ {% include "console/panes/entity_video_stream_w_link.html" with entity=entity %}
+ {% else %}
+ <div class="stream-unavailable">Video stream not available</div>
+ {% endif %}
+ </div>
+
+ {% if state_status_data_list %}
+ <div class="states">
+ {% include "entity/state_panels/fallback/state_list.html" with entity_state_status_data_list=state_status_data_list %}
+ </div>
+ {% endif %}
+
+</div>
diff --git a/src/hi/apps/entity/templates/entity/state_panels/fallback/grid.html b/src/hi/apps/entity/templates/entity/state_panels/fallback/grid.html
new file mode 100644
index 00000000..1233641f
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/fallback/grid.html
@@ -0,0 +1,7 @@
+{# Framework fallback for the collection grid card context: renders #}
+{# the entity's state list. Currently identical to the list-context #}
+{# fallback; panels wanting a denser grid layout provide their own #}
+{# grid.html. #}
+{% if state_status_data_list %}
+{% include "entity/state_panels/fallback/state_list.html" with entity_state_status_data_list=state_status_data_list %}
+{% endif %}
diff --git a/src/hi/apps/entity/templates/entity/state_panels/fallback/list.html b/src/hi/apps/entity/templates/entity/state_panels/fallback/list.html
new file mode 100644
index 00000000..1592e50c
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/fallback/list.html
@@ -0,0 +1,8 @@
+{# Framework fallback for the collection list card context: renders #}
+{# the entity's state list. The surrounding card wrapper #}
+{# (``entity_card_list.html``) supplies the entity-name title and #}
+{# the video stream (when present) above this panel body, so this #}
+{# panel only renders the per-state rows. #}
+{% if state_status_data_list %}
+{% include "entity/state_panels/fallback/state_list.html" with entity_state_status_data_list=state_status_data_list %}
+{% endif %}
diff --git a/src/hi/apps/entity/templates/entity/state_panels/fallback/modal.html b/src/hi/apps/entity/templates/entity/state_panels/fallback/modal.html
new file mode 100644
index 00000000..d7925b21
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/fallback/modal.html
@@ -0,0 +1,15 @@
+{# Framework fallback for the modal context: renders any entity #}
+{# whose type has no panel registered. The surrounding #}
+{# ``entity_status.html`` modal supplies the identifying chrome #}
+{# (icon, entity name, integration logo, type label) in its #}
+{# subheader block, so this panel body only renders the video #}
+{# stream (when present) and the flat state list. #}
+{% if entity_for_video %}
+<div>
+ {% include "console/panes/entity_video_stream_w_link.html" with entity=entity_for_video %}
+</div>
+{% endif %}
+
+{% if state_status_data_list %}
+{% include "entity/state_panels/fallback/state_list.html" with entity_state_status_data_list=state_status_data_list %}
+{% endif %}
diff --git a/src/hi/apps/collection/templates/collection/panes/entity_state_list.html b/src/hi/apps/entity/templates/entity/state_panels/fallback/state_list.html
similarity index 51%
rename from src/hi/apps/collection/templates/collection/panes/entity_state_list.html
rename to src/hi/apps/entity/templates/entity/state_panels/fallback/state_list.html
index 951e90b9..5aa6bc51 100644
--- a/src/hi/apps/collection/templates/collection/panes/entity_state_list.html
+++ b/src/hi/apps/entity/templates/entity/state_panels/fallback/state_list.html
@@ -1,7 +1,7 @@
<div>
{% for entity_state_status_data in entity_state_status_data_list %}
<div class="my-2">
- {% include "collection/panes/entity_state_row.html" with entity_state_status_data=entity_state_status_data %}
+ {% include "entity/state_panels/fallback/state_row.html" with entity_state_status_data=entity_state_status_data %}
</div>
{% endfor %}
</div>
diff --git a/src/hi/apps/entity/templates/entity/panes/entity_state_status_row.html b/src/hi/apps/entity/templates/entity/state_panels/fallback/state_row.html
similarity index 100%
rename from src/hi/apps/entity/templates/entity/panes/entity_state_status_row.html
rename to src/hi/apps/entity/templates/entity/state_panels/fallback/state_row.html
diff --git a/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/grid.html b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/grid.html
new file mode 100644
index 00000000..dc6d3062
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/grid.html
@@ -0,0 +1,32 @@
+{% with smoke_data=state_status_data_by_role.smoke battery_data=state_status_data_by_role.battery_level %}
+
+<div class="hi-state-panel-smoke_detector hi-state-panel-smoke_detector--grid"
+ {% if smoke_data %}data-state-id="{{ smoke_data.entity_state.id }}" data-status status="{{ smoke_data.latest_sensor_value }}"{% endif %}>
+
+ {% if smoke_data %}
+ <div class="badge">
+ <svg class="icon icon--clear" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M12 2L4 5v6c0 5 3.5 9.5 8 11 4.5-1.5 8-6 8-11V5l-8-3zm-1.3 14.3l-3.7-3.7 1.4-1.4 2.3 2.3 5.3-5.3 1.4 1.4-6.7 6.7z"/>
+ </svg>
+ <svg class="icon icon--alarm" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>
+ </svg>
+ <svg class="icon icon--recent" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <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.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>
+ </svg>
+ <svg class="icon icon--past" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <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.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>
+ </svg>
+ </div>
+
+ <div class="status-line">
+ <span class="status-label status-label--clear">Clear</span>
+ <span class="status-label status-label--alarm">Smoke Detected</span>
+ </div>
+ {% endif %}
+
+ <div class="entity-name">{{ entity.name }}</div>
+
+</div>
+
+{% endwith %}
diff --git a/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/list.html b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/list.html
new file mode 100644
index 00000000..7f285bc5
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/list.html
@@ -0,0 +1,40 @@
+{% with smoke_data=state_status_data_by_role.smoke battery_data=state_status_data_by_role.battery_level %}
+
+<div class="hi-state-panel-smoke_detector hi-state-panel-smoke_detector--list"
+ {% if smoke_data %}data-state-id="{{ smoke_data.entity_state.id }}" data-status status="{{ smoke_data.latest_sensor_value }}"{% endif %}>
+
+ {% if smoke_data %}
+ <div class="badge">
+ <svg class="icon icon--clear" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M12 2L4 5v6c0 5 3.5 9.5 8 11 4.5-1.5 8-6 8-11V5l-8-3zm-1.3 14.3l-3.7-3.7 1.4-1.4 2.3 2.3 5.3-5.3 1.4 1.4-6.7 6.7z"/>
+ </svg>
+ <svg class="icon icon--alarm" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>
+ </svg>
+ <svg class="icon icon--recent" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <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.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>
+ </svg>
+ <svg class="icon icon--past" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <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.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>
+ </svg>
+ </div>
+ {% endif %}
+
+ <div class="list-meta">
+ <div class="entity-name">{{ entity.name }}</div>
+ <div class="status-line">
+ <span class="status-label status-label--clear">Clear</span>
+ <span class="status-label status-label--alarm">Smoke Detected</span>
+ </div>
+ </div>
+
+ {% if battery_data %}
+ <div class="aux-bits">
+ <span data-state-id="{{ battery_data.entity_state.id }}"
+ data-display-text>{{ battery_data.latest_display_label }}</span>
+ </div>
+ {% endif %}
+
+</div>
+
+{% endwith %}
diff --git a/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/modal.html b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/modal.html
new file mode 100644
index 00000000..c7a88a19
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/modal.html
@@ -0,0 +1,45 @@
+{% with smoke_data=state_status_data_by_role.smoke battery_data=state_status_data_by_role.battery_level %}
+
+{# The ``status`` attribute carries the smoke state's value for CSS #}
+{# variant switching. Initial render uses the raw sensor value #}
+{# (``smoke_clear`` / ``smoke_detected``); polling overwrites with #}
+{# the decay-aware value (``idle`` / ``active`` / ``recent`` / #}
+{# ``past``). CSS handles both vocabularies. #}
+<div class="hi-state-panel-smoke_detector hi-state-panel-smoke_detector--modal"
+ {% if smoke_data %}data-state-id="{{ smoke_data.entity_state.id }}" data-status status="{{ smoke_data.latest_sensor_value }}"{% endif %}>
+
+ {% if smoke_data %}
+ <div class="hero">
+ <div class="badge">
+ <svg class="icon icon--clear" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M12 2L4 5v6c0 5 3.5 9.5 8 11 4.5-1.5 8-6 8-11V5l-8-3zm-1.3 14.3l-3.7-3.7 1.4-1.4 2.3 2.3 5.3-5.3 1.4 1.4-6.7 6.7z"/>
+ </svg>
+ <svg class="icon icon--alarm" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>
+ </svg>
+ <svg class="icon icon--recent" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <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.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>
+ </svg>
+ <svg class="icon icon--past" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <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.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>
+ </svg>
+ </div>
+ <div class="status-label status-label--clear">Clear</div>
+ <div class="status-label status-label--alarm">Smoke Detected</div>
+ </div>
+ {% endif %}
+
+ {% if battery_data %}
+ <div class="auxiliary">
+ <div class="aux-item">
+ <div class="aux-label">Battery</div>
+ <div class="aux-value"
+ data-state-id="{{ battery_data.entity_state.id }}"
+ data-display-text>{{ battery_data.latest_display_label }}</div>
+ </div>
+ </div>
+ {% endif %}
+
+</div>
+
+{% endwith %}
diff --git a/src/hi/apps/entity/templates/entity/state_panels/thermostat/grid.html b/src/hi/apps/entity/templates/entity/state_panels/thermostat/grid.html
new file mode 100644
index 00000000..93809c30
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/thermostat/grid.html
@@ -0,0 +1,26 @@
+{% with current_data=state_status_data_by_role.thermostat_current_temperature setpoint_data=state_status_data_by_role.thermostat_target_temperature action_data=state_status_data_by_role.hvac_action %}
+
+<div class="hi-state-panel-thermostat hi-state-panel-thermostat--grid"
+ {% if action_data %}data-state-id="{{ action_data.entity_state.id }}" data-status status="{{ action_data.latest_sensor_value }}"{% endif %}>
+
+ {% if current_data %}
+ <div class="grid-temp"
+ data-state-id="{{ current_data.entity_state.id }}"
+ data-display-text>
+ {{ current_data.latest_display_label }}
+ </div>
+ {% endif %}
+ <div class="entity-name">{{ entity.name }}</div>
+ {% if setpoint_data %}
+ <div class="setpoint-line">
+ <span class="dial-mode-label" for-status="heating">Heating</span>
+ <span class="dial-mode-label" for-status="cooling">Cooling</span>
+ <span class="dial-mode-label" for-status="idle">Idle</span>
+ <span class="dial-mode-label" for-status="off">Off</span>
+ · <strong data-state-id="{{ setpoint_data.entity_state.id }}" data-display-text>{{ setpoint_data.latest_display_label }}</strong>
+ </div>
+ {% endif %}
+
+</div>
+
+{% endwith %}
diff --git a/src/hi/apps/entity/templates/entity/state_panels/thermostat/list.html b/src/hi/apps/entity/templates/entity/state_panels/thermostat/list.html
new file mode 100644
index 00000000..dc1a2c56
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/thermostat/list.html
@@ -0,0 +1,44 @@
+{% with current_data=state_status_data_by_role.thermostat_current_temperature setpoint_data=state_status_data_by_role.thermostat_target_temperature action_data=state_status_data_by_role.hvac_action %}
+
+<div class="hi-state-panel-thermostat hi-state-panel-thermostat--list"
+ {% if action_data %}data-state-id="{{ action_data.entity_state.id }}" data-status status="{{ action_data.latest_sensor_value }}"{% endif %}>
+
+ <div class="dial">
+ <svg class="dial-svg" viewBox="0 0 220 220" aria-hidden="true">
+ <circle class="dial-track" cx="110" cy="110" r="95" fill="none" stroke-width="2"/>
+ {% if setpoint_data %}
+ <g class="dial-setpoint-marker"
+ data-marker-state-id="{{ setpoint_data.entity_state.id }}"
+ data-temp-value="{{ setpoint_data.latest_display_value.magnitude }}">
+ <line x1="110" y1="10" x2="110" y2="24" stroke-width="6" stroke-linecap="round"/>
+ </g>
+ {% endif %}
+ {% if current_data %}
+ <g class="dial-current-marker"
+ data-marker-state-id="{{ current_data.entity_state.id }}"
+ data-temp-value="{{ current_data.latest_display_value.magnitude }}">
+ <circle cx="110" cy="17" r="9"/>
+ </g>
+ {% endif %}
+ </svg>
+ <div class="dial-center">
+ {% if current_data %}
+ <span class="dial-temp"
+ data-state-id="{{ current_data.entity_state.id }}"
+ data-display-text>{{ current_data.latest_display_label }}</span>
+ {% endif %}
+ </div>
+ </div>
+
+ <div class="list-meta">
+ <div class="entity-name">{{ entity.name }}</div>
+ {% if setpoint_data %}
+ <div class="setpoint-summary">
+ Target <strong data-state-id="{{ setpoint_data.entity_state.id }}" data-display-text>{{ setpoint_data.latest_display_label }}</strong>
+ </div>
+ {% endif %}
+ </div>
+
+</div>
+
+{% endwith %}
diff --git a/src/hi/apps/entity/templates/entity/state_panels/thermostat/modal.html b/src/hi/apps/entity/templates/entity/state_panels/thermostat/modal.html
new file mode 100644
index 00000000..0cca0190
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/state_panels/thermostat/modal.html
@@ -0,0 +1,53 @@
+{% load common_tags %}
+{% with current_data=state_status_data_by_role.thermostat_current_temperature setpoint_data=state_status_data_by_role.thermostat_target_temperature action_data=state_status_data_by_role.hvac_action %}
+
+{# The panel root carries ``data-state-id`` + ``data-status`` for #}
+{# the HVAC_ACTION state so the polling dispatcher keeps the #}
+{# ``status`` attribute current (idle / heating / cooling / off). #}
+{# CSS keyed on ``[status=...]`` handles the color tint and the #}
+{# dial-mode label visibility. The setpoint and current-temperature #}
+{# markers on the dial are JS-positioned because their angle #}
+{# depends on the numeric magnitude, which CSS alone can't compute. #}
+<div class="hi-state-panel-thermostat hi-state-panel-thermostat--modal"
+ {% if action_data %}data-state-id="{{ action_data.entity_state.id }}" data-status status="{{ action_data.latest_sensor_value }}"{% endif %}>
+
+ <div class="dial">
+ <svg class="dial-svg" viewBox="0 0 220 220" aria-hidden="true">
+ <circle class="dial-track" cx="110" cy="110" r="95" fill="none" stroke-width="2"/>
+ {% if setpoint_data %}
+ <g class="dial-setpoint-marker"
+ data-marker-state-id="{{ setpoint_data.entity_state.id }}"
+ data-temp-value="{{ setpoint_data.latest_display_value.magnitude }}">
+ <line x1="110" y1="8" x2="110" y2="24" stroke-width="3" stroke-linecap="round"/>
+ </g>
+ {% endif %}
+ {% if current_data %}
+ <g class="dial-current-marker"
+ data-marker-state-id="{{ current_data.entity_state.id }}"
+ data-temp-value="{{ current_data.latest_display_value.magnitude }}">
+ <circle cx="110" cy="15" r="5"/>
+ </g>
+ {% endif %}
+ </svg>
+ <div class="dial-center">
+ {% if current_data %}
+ <span class="dial-temp"
+ data-state-id="{{ current_data.entity_state.id }}"
+ data-display-text>{{ current_data.latest_display_label }}</span>
+ {% endif %}
+ <span class="dial-mode-label" for-status="idle">Idle</span>
+ <span class="dial-mode-label" for-status="heating">Heating</span>
+ <span class="dial-mode-label" for-status="cooling">Cooling</span>
+ <span class="dial-mode-label" for-status="off">Off</span>
+ </div>
+ </div>
+
+ {% if state_status_data_list %}
+ <div class="states">
+ {% include "entity/state_panels/fallback/state_list.html" with entity_state_status_data_list=state_status_data_list %}
+ </div>
+ {% endif %}
+
+</div>
+
+{% endwith %}
diff --git a/src/hi/apps/entity/templatetags/state_panel_tags.py b/src/hi/apps/entity/templatetags/state_panel_tags.py
new file mode 100644
index 00000000..ae51061f
--- /dev/null
+++ b/src/hi/apps/entity/templatetags/state_panel_tags.py
@@ -0,0 +1,74 @@
+"""Template tags for the EntityStatusPanel framework.
+
+``render_entity_status_panel`` is the dispatch point used at each
+panel call site (EntityStatus modal body, collection list card,
+collection grid card). It resolves a template along the panel
+fallback chain and renders it with the parent context plus
+panel-specific additions.
+
+``panel_state`` is a presentation helper for panel templates that
+need to pull a specific EntityState by ``EntityStateRole`` (e.g.,
+the thermostat panel reaching for the current-temperature state)."""
+
+from typing import Optional
+
+from django import template
+
+from hi.apps.entity.enums import EntityStateRole
+from hi.apps.entity.models import Entity, EntityState
+from hi.apps.entity.state_panel_dispatch import (
+ SUPPORTED_DISPLAY_CONTEXTS,
+ resolve_panel_template,
+)
+
+
+register = template.Library()
+
+
[email protected]_tag( takes_context = True )
+def render_entity_status_panel( context, entity_status_data, display_context_name : str ):
+ """Render the panel for ``entity_status_data.entity`` in
+ ``display_context_name``.
+
+ The panel template's context is the parent's flattened context
+ merged with the entity_status_data's ``to_template_context()``
+ fields, so panel templates have ``entity``,
+ ``state_status_data_list``, ``state_status_data_by_role``, and the
+ other display fields at the top level regardless of which call
+ site (modal / list card / grid card) invokes the tag."""
+
+ if display_context_name not in SUPPORTED_DISPLAY_CONTEXTS:
+ raise ValueError(
+ f'Unsupported display context: {display_context_name!r}. '
+ f'Expected one of {SUPPORTED_DISPLAY_CONTEXTS}.'
+ )
+
+ template_obj = resolve_panel_template(
+ entity_type = entity_status_data.entity.entity_type,
+ display_context_name = display_context_name,
+ )
+ flat = context.flatten()
+ flat.update( entity_status_data.to_template_context() )
+ flat[ 'display_context_name' ] = display_context_name
+ return template_obj.render( flat )
+
+
+def panel_state( entity : Entity, role : str ) -> Optional[ EntityState ]:
+ """Return the EntityState on ``entity`` whose role matches
+ ``role`` (case-insensitive name match against ``EntityStateRole``),
+ or ``None`` when no such state exists. Walks both the entity's
+ own states and delegated states."""
+
+ try:
+ role_enum = EntityStateRole.from_name( role )
+ except ValueError:
+ return None
+
+ for state in entity.states.all():
+ if state.entity_state_role == role_enum:
+ return state
+ for delegation in entity.entity_state_delegations.select_related( 'entity_state' ).all():
+ if delegation.entity_state.entity_state_role == role_enum:
+ return delegation.entity_state
+ return None
diff --git a/src/hi/apps/entity/tests/test_state_panel_dispatch.py b/src/hi/apps/entity/tests/test_state_panel_dispatch.py
new file mode 100644
index 00000000..29caa959
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_state_panel_dispatch.py
@@ -0,0 +1,155 @@
+import logging
+from unittest.mock import patch
+
+from django.template.exceptions import TemplateDoesNotExist
+
+from hi.apps.entity.enums import EntityType
+from hi.apps.entity.state_panel_dispatch import (
+ FRAMEWORK_FALLBACK_TEMPLATES,
+ SUPPORTED_DISPLAY_CONTEXTS,
+ resolve_panel_template,
+)
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestResolvePanelTemplate(BaseTestCase):
+ """``resolve_panel_template`` walks a three-step chain: the panel's
+ context-specific template, the panel's required default (modal.html),
+ then the framework's per-context fallback. The framework fallbacks
+ are guaranteed to exist; the panel templates may or may not."""
+
+ def test_falls_back_to_framework_default_when_no_panel_exists(self):
+ # SMOKE_DETECTOR has no panel templates in Phase 1; resolution
+ # lands on the framework fallback for the modal context.
+ template_obj = resolve_panel_template(
+ entity_type = EntityType.OTHER,
+ display_context_name = 'modal',
+ )
+ self.assertEqual(
+ template_obj.origin.template_name,
+ FRAMEWORK_FALLBACK_TEMPLATES[ 'modal' ],
+ )
+
+ def test_falls_back_to_framework_default_for_list_context(self):
+ template_obj = resolve_panel_template(
+ entity_type = EntityType.OTHER,
+ display_context_name = 'list',
+ )
+ self.assertEqual(
+ template_obj.origin.template_name,
+ FRAMEWORK_FALLBACK_TEMPLATES[ 'list' ],
+ )
+
+ def test_falls_back_to_framework_default_for_grid_context(self):
+ template_obj = resolve_panel_template(
+ entity_type = EntityType.OTHER,
+ display_context_name = 'grid',
+ )
+ self.assertEqual(
+ template_obj.origin.template_name,
+ FRAMEWORK_FALLBACK_TEMPLATES[ 'grid' ],
+ )
+
+ def test_returns_panel_context_template_when_present(self):
+ # Simulate a panel directory existing for camera with all
+ # three context-specific templates.
+ with patch(
+ 'hi.apps.entity.state_panel_dispatch.get_template'
+ ) as mock_get_template:
+ mock_get_template.side_effect = self._template_existence_simulator({
+ 'entity/state_panels/camera/grid.html': True,
+ })
+ template_obj = resolve_panel_template(
+ entity_type = EntityType.CAMERA,
+ display_context_name = 'grid',
+ )
+ self.assertEqual(
+ mock_get_template.call_args_list[ 0 ].args[ 0 ],
+ 'entity/state_panels/camera/grid.html',
+ )
+ self.assertIsNotNone( template_obj )
+
+ def test_list_context_falls_back_to_panel_modal_when_list_absent(self):
+ # Panel provides modal.html but not list.html; resolution
+ # should reach modal.html, not the framework fallback.
+ with patch(
+ 'hi.apps.entity.state_panel_dispatch.get_template'
+ ) as mock_get_template:
+ mock_get_template.side_effect = self._template_existence_simulator({
+ 'entity/state_panels/camera/modal.html': True,
+ })
+ resolve_panel_template(
+ entity_type = EntityType.CAMERA,
+ display_context_name = 'list',
+ )
+ requested_paths = [ call.args[ 0 ] for call in mock_get_template.call_args_list ]
+ self.assertIn( 'entity/state_panels/camera/list.html', requested_paths )
+ self.assertIn( 'entity/state_panels/camera/modal.html', requested_paths )
+ # Resolution stops at modal.html; framework fallback is never asked.
+ self.assertNotIn(
+ FRAMEWORK_FALLBACK_TEMPLATES[ 'list' ],
+ requested_paths,
+ )
+
+ def test_modal_context_lookup_order(self):
+ # Modal context tries the panel's modal.html, then the framework
+ # fallback. There is no intermediate step.
+ with patch(
+ 'hi.apps.entity.state_panel_dispatch.get_template'
+ ) as mock_get_template:
+ mock_get_template.side_effect = self._template_existence_simulator( {} )
+ resolve_panel_template(
+ entity_type = EntityType.THERMOSTAT,
+ display_context_name = 'modal',
+ )
+ requested_paths = [ call.args[ 0 ] for call in mock_get_template.call_args_list ]
+ # First lookup is panel/modal; last is framework fallback. The
+ # middle step (panel/modal again) is harmless duplication.
+ self.assertEqual(
+ requested_paths[ 0 ],
+ 'entity/state_panels/thermostat/modal.html',
+ )
+ self.assertEqual(
+ requested_paths[ -1 ],
+ FRAMEWORK_FALLBACK_TEMPLATES[ 'modal' ],
+ )
+
+ def test_unsupported_context_raises(self):
+ with self.assertRaises( ValueError ):
+ resolve_panel_template(
+ entity_type = EntityType.OTHER,
+ display_context_name = 'sidebar',
+ )
+
+ def test_all_supported_contexts_resolve_to_real_framework_fallbacks(self):
+ # Sanity check: every supported context has a framework
+ # fallback template that actually exists.
+ for context_name in SUPPORTED_DISPLAY_CONTEXTS:
+ template_obj = resolve_panel_template(
+ entity_type = EntityType.OTHER,
+ display_context_name = context_name,
+ )
+ self.assertEqual(
+ template_obj.origin.template_name,
+ FRAMEWORK_FALLBACK_TEMPLATES[ context_name ],
+ )
+
+ # ------------------------------------------------------------------
+
+ def _template_existence_simulator( self, existing_template_names_dict ):
+ """Return a mock side_effect that simulates ``get_template``
+ finding the listed templates, plus the framework fallbacks
+ (which are guaranteed to exist in production)."""
+ from django.template.loader import get_template as real_get_template
+
+ existing = set( existing_template_names_dict )
+ existing.update( FRAMEWORK_FALLBACK_TEMPLATES.values() )
+
+ def side_effect( template_name ):
+ if template_name in existing:
+ return real_get_template( FRAMEWORK_FALLBACK_TEMPLATES[ 'modal' ] )
+ raise TemplateDoesNotExist( template_name )
+
+ return side_effect
diff --git a/src/hi/apps/entity/tests/test_state_panel_tags.py b/src/hi/apps/entity/tests/test_state_panel_tags.py
new file mode 100644
index 00000000..663fb36c
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_state_panel_tags.py
@@ -0,0 +1,93 @@
+import logging
+
+from hi.apps.entity.enums import EntityStateRole, EntityType
+from hi.apps.entity.models import Entity, EntityState, EntityStateDelegation
+from hi.apps.entity.templatetags.state_panel_tags import panel_state
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestPanelState(BaseTestCase):
+ """``panel_state`` looks up an EntityState on the entity by
+ EntityStateRole (case-insensitive name match), walking the
+ entity's own states then delegated states. Returns None when
+ no state with the requested role is bound to the entity."""
+
+ def setUp(self):
+ super().setUp()
+ self.entity = Entity.objects.create(
+ name = 'Test Thermostat',
+ entity_type_str = str( EntityType.THERMOSTAT ),
+ )
+ self.current_temp_state = EntityState.objects.create(
+ entity = self.entity,
+ name = 'Current Temperature',
+ entity_state_type_str = 'TEMPERATURE',
+ role_str = str( EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE ),
+ )
+ self.setpoint_state = EntityState.objects.create(
+ entity = self.entity,
+ name = 'Target Temperature',
+ entity_state_type_str = 'TEMPERATURE',
+ role_str = str( EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE ),
+ )
+
+ def test_returns_state_matching_role(self):
+ state = panel_state( self.entity, 'thermostat_current_temperature' )
+ self.assertEqual( state, self.current_temp_state )
+
+ def test_role_match_is_case_insensitive(self):
+ state = panel_state( self.entity, 'THERMOSTAT_TARGET_TEMPERATURE' )
+ self.assertEqual( state, self.setpoint_state )
+
+ def test_returns_none_when_no_state_matches_role(self):
+ # The entity has no HVAC_MODE state; lookup returns None.
+ result = panel_state( self.entity, 'hvac_mode' )
+ self.assertIsNone( result )
+
+ def test_returns_none_for_unknown_role_name(self):
+ result = panel_state( self.entity, 'definitely_not_a_real_role' )
+ self.assertIsNone( result )
+
+ def test_walks_delegated_states(self):
+ # A state delegated from another entity should be reachable
+ # by role lookup on the delegating entity.
+ principal_entity = Entity.objects.create(
+ name = 'External Humidity Sensor',
+ entity_type_str = str( EntityType.OTHER ),
+ )
+ humidity_state = EntityState.objects.create(
+ entity = principal_entity,
+ name = 'Humidity',
+ entity_state_type_str = 'HUMIDITY',
+ role_str = str( EntityStateRole.HUMIDITY ),
+ )
+ EntityStateDelegation.objects.create(
+ delegate_entity = self.entity,
+ entity_state = humidity_state,
+ )
+
+ state = panel_state( self.entity, 'humidity' )
+ self.assertEqual( state, humidity_state )
+
+ def test_own_state_wins_over_delegated_when_roles_collide(self):
+ # If both an own state and a delegated state carry the same
+ # role, the entity's own state is returned (own-states pass
+ # is first in the lookup order).
+ principal_entity = Entity.objects.create(
+ name = 'External', entity_type_str = str( EntityType.OTHER ),
+ )
+ delegated_dup = EntityState.objects.create(
+ entity = principal_entity,
+ name = 'Other Current Temp',
+ entity_state_type_str = 'TEMPERATURE',
+ role_str = str( EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE ),
+ )
+ EntityStateDelegation.objects.create(
+ delegate_entity = self.entity,
+ entity_state = delegated_dup,
+ )
+
+ state = panel_state( self.entity, 'thermostat_current_temperature' )
+ self.assertEqual( state, self.current_temp_state )
diff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.py
index 3610d581..4e3d4c65 100644
--- a/src/hi/apps/entity/views.py
+++ b/src/hi/apps/entity/views.py
@@ -9,6 +9,7 @@ from hi.apps.common import datetimeproxy
from hi.apps.attribute.view_mixins import AttributeEditViewMixin
from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
+from hi.apps.monitor.display_data import EntityDisplayData
from hi.apps.monitor.status_display_manager import StatusDisplayManager
from hi.views import page_not_found_response
@@ -40,8 +41,9 @@ class EntityStatusView( HiModalView, EntityViewMixin ):
entity_status_data = StatusDisplayManager().get_entity_status_data( entity = entity )
if not entity_status_data.entity_state_status_data_list:
return EntityEditView().get( request, *args, **kwargs )
-
- context = entity_status_data.to_template_context()
+
+ entity_display_data = EntityDisplayData( entity_status_data = entity_status_data )
+ context = entity_display_data.to_template_context()
return self.modal_response( request, context )
diff --git a/src/hi/apps/location/location_view_data.py b/src/hi/apps/location/location_view_data.py
index fcb43175..0c454ef4 100644
--- a/src/hi/apps/location/location_view_data.py
+++ b/src/hi/apps/location/location_view_data.py
@@ -6,8 +6,8 @@ from hi.apps.common.svg_models import SvgIconItem, SvgPathItem
from hi.apps.entity.entity_state_role_order import ENTITY_PRIMARY_STATE_ORDERING
from hi.apps.entity.models import Entity, EntityPosition, EntityPath
from hi.apps.location.svg_item_factory import SvgItemFactory
-from hi.apps.monitor.status_display_data import StatusDisplayData
-from hi.apps.monitor.transient_models import EntityStateStatusData
+from hi.apps.monitor.display_data import EntityStateDisplayData
+from hi.apps.monitor.status_data import EntityStateStatusData
from .models import LocationView
@@ -29,45 +29,44 @@ class LocationViewData:
def __post_init__(self):
self._svg_item_factory = SvgItemFactory()
- # Primary-state map is computed first; the CSS class map is
+ # Primary-state map is computed first; the state-id map is
# derived from it so the entity's ``<g>`` element carries
- # exactly one ``hi-entity-state-*`` class (the primary).
- # That keeps the polling update path's per-state CSS class
- # selectors from clobbering the icon's ``status`` attribute.
+ # exactly one ``data-state-id`` (the primary state). That
+ # gives the polling dispatcher a single anchor for SVG
+ # styling updates on this entity's icon.
self._latest_entity_state_status_data_map = self._get_latest_entity_state_status_data_map()
- self._css_class_map = self._get_css_class_map()
+ self._state_id_map = self._get_state_id_map()
return
-
+
def svg_icon_items(self) -> Generator[ SvgIconItem, None, None ]:
for entity_position in self.entity_positions:
- css_class = self._css_class_map.get( entity_position.entity, '' )
+ state_id = self._state_id_map.get( entity_position.entity )
latest_entity_state_status_data = self._latest_entity_state_status_data_map.get(
entity_position.entity,
)
if latest_entity_state_status_data:
- status_display_data = StatusDisplayData(
+ status_display_data = EntityStateDisplayData(
entity_state_status_data = latest_entity_state_status_data,
)
svg_status_style = status_display_data.svg_status_style
else:
svg_status_style = None
-
+
svg_icon_item = self._svg_item_factory.create_svg_icon_item(
item = entity_position.entity,
position = entity_position,
- css_class = css_class,
+ state_id = state_id,
svg_status_style = svg_status_style,
)
yield svg_icon_item
continue
-
+
for collection_position in self.collection_positions:
svg_icon_item = self._svg_item_factory.create_svg_icon_item(
item = collection_position.collection,
position = collection_position,
- css_class = '',
)
yield svg_icon_item
continue
@@ -77,46 +76,47 @@ class LocationViewData:
for entity_path in self.entity_paths:
- css_class = self._css_class_map.get( entity_path.entity, '' )
+ state_id = self._state_id_map.get( entity_path.entity )
latest_entity_state_status_data = self._latest_entity_state_status_data_map.get(
entity_path.entity,
)
if latest_entity_state_status_data:
- status_display_data = StatusDisplayData(
+ status_display_data = EntityStateDisplayData(
entity_state_status_data = latest_entity_state_status_data,
)
svg_status_style = status_display_data.svg_status_style
else:
svg_status_style = None
-
+
svg_path_item = self._svg_item_factory.create_svg_path_item(
item = entity_path.entity,
path = entity_path,
- css_class = css_class,
+ state_id = state_id,
svg_status_style = svg_status_style,
)
yield svg_path_item
continue
-
+
for collection_path in self.collection_paths:
svg_path_item = self._svg_item_factory.create_svg_path_item(
item = collection_path.collection,
path = collection_path,
- css_class = '',
)
yield svg_path_item
continue
return
- def _get_css_class_map(self):
- # One ``hi-entity-state-*`` class per entity — the primary
- # state's class. Entities without a primary state (no states
- # with sensor responses) get no class.
- css_class_map = dict()
+ def _get_state_id_map(self):
+ # One state id per entity — the primary state's id. Drives
+ # the ``data-state-id`` attribute on the SVG icon / path
+ # elements so the polling dispatcher can target them.
+ # Entities without a primary state (no states with sensor
+ # responses) get no entry and render without data-state-id.
+ state_id_map = dict()
for entity, picked in self._latest_entity_state_status_data_map.items():
- css_class_map[entity] = picked.entity_state.css_class
+ state_id_map[entity] = picked.entity_state.id
continue
- return css_class_map
+ return state_id_map
def _get_latest_entity_state_status_data_map(self):
# Per-entity primary-state selection: among states with a
diff --git a/src/hi/apps/location/svg_item_factory.py b/src/hi/apps/location/svg_item_factory.py
index d3f066f1..a077f78e 100644
--- a/src/hi/apps/location/svg_item_factory.py
+++ b/src/hi/apps/location/svg_item_factory.py
@@ -28,7 +28,7 @@ class SvgItemFactory( Singleton ):
return SvgIconItem(
html_id = None,
- css_class = None,
+ state_id = None,
status_value = None,
position_x = None,
position_y = None,
@@ -41,7 +41,7 @@ class SvgItemFactory( Singleton ):
def create_svg_icon_item( self,
item : LocationItemModelMixin,
position : LocationItemPositionModel,
- css_class : str,
+ state_id : int = None,
svg_status_style : SvgStatusStyle = None ) -> SvgIconItem:
if not svg_status_style:
svg_status_style = ItemStyle.get_default_svg_icon_status_style()
@@ -55,7 +55,7 @@ class SvgItemFactory( Singleton ):
return SvgIconItem(
html_id = item.html_id,
- css_class = css_class,
+ state_id = state_id,
status_value = svg_status_style.status_value,
position_x = float( position.svg_x ),
position_y = float( position.svg_y ),
@@ -71,7 +71,7 @@ class SvgItemFactory( Singleton ):
def create_svg_path_item( self,
item : LocationItemModelMixin,
path : LocationItemPathModel,
- css_class : str,
+ state_id : int = None,
svg_status_style : SvgStatusStyle = None ) -> SvgPathItem:
if not svg_status_style:
if isinstance( item, Entity ):
@@ -83,7 +83,7 @@ class SvgItemFactory( Singleton ):
return SvgPathItem(
html_id = item.html_id,
- css_class = css_class,
+ state_id = state_id,
svg_path = path.svg_path,
stroke_color = svg_status_style.stroke_color,
stroke_width = svg_status_style.stroke_width,
diff --git a/src/hi/apps/location/templates/location/panes/svg_icon_item.html b/src/hi/apps/location/templates/location/panes/svg_icon_item.html
index 667e77a0..df090bab 100644
--- a/src/hi/apps/location/templates/location/panes/svg_icon_item.html
+++ b/src/hi/apps/location/templates/location/panes/svg_icon_item.html
@@ -1,5 +1,6 @@
<g id="{{ svg_icon_item.html_id }}"
- class="hi-icon selectable draggable {{ svg_icon_item.css_class }} hi-svg-icon"
+ class="hi-icon selectable draggable hi-svg-icon"
+ {% if svg_icon_item.state_id %}data-state-id="{{ svg_icon_item.state_id }}" data-status{% endif %}
status="{{ svg_icon_item.status_value }}"
data-type="svg-icon"
onmouseover="this.setAttribute('hover','true');"
diff --git a/src/hi/apps/location/templates/location/panes/svg_path_item_closed.html b/src/hi/apps/location/templates/location/panes/svg_path_item_closed.html
index 7aa1dd0e..0545a314 100644
--- a/src/hi/apps/location/templates/location/panes/svg_path_item_closed.html
+++ b/src/hi/apps/location/templates/location/panes/svg_path_item_closed.html
@@ -1,10 +1,11 @@
-<path class="{{ svg_path_item.css_class }} hi-path-closed"
+<path class="hi-path-closed"
+ {% if svg_path_item.state_id %}data-state-id="{{ svg_path_item.state_id }}" data-svg-style{% endif %}
fill="{{ svg_path_item.fill_color }}"
- fill-opacity="{{ svg_path_item.fill_opacity }}"
- stroke="{{ svg_path_item.stroke_color }}"
- stroke-width="{{ svg_path_item.stroke_width }}"
+ fill-opacity="{{ svg_path_item.fill_opacity }}"
+ stroke="{{ svg_path_item.stroke_color }}"
+ stroke-width="{{ svg_path_item.stroke_width }}"
{% if svg_path_item.stroke_dasharray_value %}stroke-dasharray="{{ svg_path_item.stroke_dasharray_value }}"{% endif %}
- vector-effect="non-scaling-stroke"
+ vector-effect="non-scaling-stroke"
onmouseover="this.setAttribute('hover','true');"
onmouseout="this.removeAttribute('hover');"
d="{{ svg_path_item.svg_path }}"></path>
diff --git a/src/hi/apps/location/templates/location/panes/svg_path_item_open.html b/src/hi/apps/location/templates/location/panes/svg_path_item_open.html
index 322ed276..70018160 100644
--- a/src/hi/apps/location/templates/location/panes/svg_path_item_open.html
+++ b/src/hi/apps/location/templates/location/panes/svg_path_item_open.html
@@ -2,13 +2,14 @@
onmouseover="this.setAttribute('hover','true');"
onmouseout="this.removeAttribute('hover');"
d="{{ svg_path_item.svg_path }}"></path>
-<path class="{{ svg_path_item.css_class }} hi-path-open"
+<path class="hi-path-open"
+ {% if svg_path_item.state_id %}data-state-id="{{ svg_path_item.state_id }}" data-svg-style{% endif %}
fill="{{ svg_path_item.fill_color }}"
- fill-opacity="{{ svg_path_item.fill_opacity }}"
- stroke="{{ svg_path_item.stroke_color }}"
- stroke-width="{{ svg_path_item.stroke_width }}"
+ fill-opacity="{{ svg_path_item.fill_opacity }}"
+ stroke="{{ svg_path_item.stroke_color }}"
+ stroke-width="{{ svg_path_item.stroke_width }}"
{% if svg_path_item.stroke_dasharray_value %}stroke-dasharray="{{ svg_path_item.stroke_dasharray_value }}"{% endif %}
- vector-effect="non-scaling-stroke"
+ vector-effect="non-scaling-stroke"
style="pointer-events: none;"
d="{{ svg_path_item.svg_path }}"></path>
</g>
diff --git a/src/hi/apps/location/tests/test_location_view_data.py b/src/hi/apps/location/tests/test_location_view_data.py
index d0289bd6..d543884e 100644
--- a/src/hi/apps/location/tests/test_location_view_data.py
+++ b/src/hi/apps/location/tests/test_location_view_data.py
@@ -4,7 +4,7 @@ from datetime import datetime, timezone
from hi.apps.entity.enums import EntityStateRole, EntityStateType, EntityType
from hi.apps.entity.models import Entity, EntityState
from hi.apps.location.location_view_data import LocationViewData
-from hi.apps.monitor.transient_models import EntityStateStatusData
+from hi.apps.monitor.status_data import EntityStateStatusData
from hi.apps.sense.transient_models import SensorResponse
from hi.integrations.transient_models import IntegrationKey
from hi.testing.base_test_case import BaseTestCase
diff --git a/src/hi/apps/location/tests/test_svg_item_factory.py b/src/hi/apps/location/tests/test_svg_item_factory.py
index 5aa4b86e..9b96d216 100644
--- a/src/hi/apps/location/tests/test_svg_item_factory.py
+++ b/src/hi/apps/location/tests/test_svg_item_factory.py
@@ -85,13 +85,13 @@ class TestSvgItemFactory(BaseTestCase):
icon_item = factory.create_svg_icon_item(
item=entity,
position=position,
- css_class='entity-icon'
+ state_id=42,
)
-
+
# Should create proper SvgIconItem
self.assertIsInstance(icon_item, SvgIconItem)
self.assertEqual(icon_item.html_id, 'entity-123')
- self.assertEqual(icon_item.css_class, 'entity-icon')
+ self.assertEqual(icon_item.state_id, 42)
self.assertEqual(icon_item.position_x, 100.0)
self.assertEqual(icon_item.position_y, 200.0)
self.assertEqual(icon_item.rotate, 45.0)
@@ -126,13 +126,13 @@ class TestSvgItemFactory(BaseTestCase):
path_item = factory.create_svg_path_item(
item=entity,
path=path,
- css_class='entity-path'
+ state_id=42,
)
-
+
# Should create proper SvgPathItem
self.assertIsInstance(path_item, SvgPathItem)
self.assertEqual(path_item.html_id, 'entity-456')
- self.assertEqual(path_item.css_class, 'entity-path')
+ self.assertEqual(path_item.state_id, 42)
self.assertEqual(path_item.svg_path, 'M 10,10 L 50,50 L 10,50 Z')
self.assertEqual(path_item.stroke_color, '#ff0000')
self.assertEqual(path_item.stroke_width, 2.0)
@@ -253,7 +253,7 @@ class TestSvgItemFactory(BaseTestCase):
# Test that display icon has no positioning or status
self.assertIsInstance(display_icon, SvgIconItem)
self.assertIsNone(display_icon.html_id)
- self.assertIsNone(display_icon.css_class)
+ self.assertIsNone(display_icon.state_id)
self.assertIsNone(display_icon.status_value)
self.assertIsNone(display_icon.position_x)
self.assertIsNone(display_icon.position_y)
diff --git a/src/hi/apps/location/view_mixins.py b/src/hi/apps/location/view_mixins.py
index 1d4cfe6a..d90e5e2c 100644
--- a/src/hi/apps/location/view_mixins.py
+++ b/src/hi/apps/location/view_mixins.py
@@ -8,7 +8,7 @@ import hi.apps.common.antinode as antinode
from hi.apps.entity.models import Entity
from hi.apps.location.location_manager import LocationManager
from hi.apps.location.models import Location, LocationView
-from hi.apps.monitor.status_display_data import StatusDisplayData
+from hi.apps.monitor.display_data import EntityStateDisplayData
from hi.apps.monitor.status_display_manager import StatusDisplayManager
from hi.hi_async_view import HiSideView
@@ -62,10 +62,10 @@ class LocationViewMixin:
)
set_attributes_map = dict()
for entity_state_status_data in entity_status_data.entity_state_status_data_list:
- status_display_data = StatusDisplayData(
+ status_display_data = EntityStateDisplayData(
entity_state_status_data = entity_state_status_data,
)
- selector = f'.{status_display_data.css_class}'
+ selector = f'[data-state-id="{status_display_data.entity_state.id}"]'
set_attributes_map.update({
selector: status_display_data.attribute_dict
})
diff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/display_data.py
similarity index 70%
rename from src/hi/apps/monitor/status_display_data.py
rename to src/hi/apps/monitor/display_data.py
index 2b0adec3..9a94a202 100644
--- a/src/hi/apps/monitor/status_display_data.py
+++ b/src/hi/apps/monitor/display_data.py
@@ -1,17 +1,34 @@
+"""Display-level projections of raw monitor data.
+
+The raw classes ``EntityStateStatusData`` and ``EntityStatusData`` (in
+``status_data``) are pure data containers — cheap to construct,
+free of display-format work. Templates and other rendering call sites
+go through the wrapping ``EntityStateDisplayData`` /
+``EntityDisplayData`` here, which add display-ready accessors (unit
+conversion, formatted labels, SVG status styles, role-keyed lookup,
+etc.). Manager produces raw; views project."""
+
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional
+
import hi.apps.common.datetimeproxy as datetimeproxy
+from hi.apps.common.svg_models import SvgIconItem
from hi.apps.console.console_converter_helper import (
ConsoleConverterHelper,
DisplayValue,
)
+from hi.apps.entity.entity_state_role_order import ENTITY_STATUS_VIEW_ORDERING
from hi.apps.entity.enums import EntityStateType, EntityStateValue
+from hi.apps.entity.models import Entity
from hi.hi_styles import StatusStyle
-from .transient_models import EntityStateStatusData
+from .enums import EntityDisplayCategory
+from .status_data import EntityStateStatusData, EntityStatusData
-
-class StatusDisplayData:
+
+class EntityStateDisplayData:
RECENT_MOVEMENT_THRESHOLD_SECS = 90
PAST_MOVEMENT_THRESHOLD_SECS = 180
@@ -40,6 +57,7 @@ class StatusDisplayData:
PAST_GAS_THRESHOLD_SECS = 1800
def __init__( self, entity_state_status_data : EntityStateStatusData ):
+ self._raw = entity_state_status_data
self._entity_state = entity_state_status_data.entity_state
self._sensor_response_list = entity_state_status_data.sensor_response_list
self._controller_data_list = entity_state_status_data.controller_data_list
@@ -57,6 +75,17 @@ class StatusDisplayData:
self._controller_data_value = self._get_controller_data_value()
return
+ def __getattr__( self, name ):
+ # Fall through to the wrapped raw data for any accessor not
+ # defined here (e.g. ``latest_sensor_response``, ``has_sensor``,
+ # ``has_controller``). Lets mainline templates that take a raw
+ # ``EntityStateStatusData`` also accept this display wrapper
+ # without per-template breakage. Properties defined on this
+ # class take precedence — ``__getattr__`` only fires for misses.
+ if name.startswith( '_' ):
+ raise AttributeError( name )
+ return getattr( self._raw, name )
+
@property
def entity_state(self):
return self._entity_state
@@ -134,18 +163,39 @@ class StatusDisplayData:
def to_polling_update_dict(self) -> dict:
"""Build the per-EntityState row of ``entityStateStatusMap``.
- Carries the three UI update pieces: DOM attributes,
- controller widget state, and the human-readable display
- text."""
+
+ Shape consumed by the JS dispatcher; each top-level key feeds
+ one element-level declaration:
+
+ - ``status`` → for ``[data-status]`` (singular status
+ attribute push, e.g., panel root driving
+ ``[status="..."]`` CSS)
+ - ``controller``→ for ``[data-controller-value]`` (form value
+ push to sliders / checkboxes / selects)
+ - ``display`` → for ``[data-display-text]`` /
+ ``[data-display-magnitude]`` /
+ ``[data-display-unit]``
+ - ``svg_style`` → for ``[data-svg-style]`` (bundled SVG
+ attribute push: status, stroke, fill, etc.,
+ for LocationView icon and path elements)
+
+ ``status`` and ``svg_style.status`` carry the same value;
+ consumers pick the bundle that matches their opt-in. Fields
+ are present only when meaningful — sensor-only states omit
+ ``controller``; unit-less states omit
+ ``display.magnitude``/``display.unit``; states with no SVG
+ styling omit ``svg_style``."""
+ svg_style_dict = self.attribute_dict # may be {} for unrecognized values
display_value = self.latest_display_value
display_dict = { 'text': self.latest_display_label }
if display_value.unit_symbol:
display_dict[ 'magnitude' ] = display_value.magnitude
- display_dict[ 'unit_symbol' ] = display_value.unit_symbol
- row = {
- 'attributes': self.attribute_dict,
- 'display_value': display_dict,
- }
+ display_dict[ 'unit' ] = display_value.unit_symbol
+ row = { 'display': display_dict }
+ if svg_style_dict:
+ row[ 'svg_style' ] = svg_style_dict
+ if 'status' in svg_style_dict:
+ row[ 'status' ] = svg_style_dict[ 'status' ]
if self.controller_data_value is not None:
row[ 'controller' ] = { 'value': self.controller_data_value }
return row
@@ -401,3 +451,86 @@ class StatusDisplayData:
return StatusStyle.Low
return None
+
+
+@dataclass
+class EntityDisplayData:
+ """Display projection of an ``EntityStatusData``. Wraps the raw
+ entity-level status data and exposes the accessors templates
+ need: a role-keyed map of per-state display projections, an
+ ordered list of the same, plus pass-through to the basic
+ ``entity`` / ``entity_for_video`` / ``display_only_svg_icon_item``
+ references. Constructed once per render at the view layer; each
+ contained state is wrapped exactly once at construction time."""
+
+ entity_status_data : EntityStatusData
+ state_display_data_map : Dict[ int, 'EntityStateDisplayData' ] = field(
+ init = False, repr = False,
+ )
+
+ def __post_init__(self):
+ # Each contained state's ``EntityStateDisplayData`` is built
+ # exactly once here. ``state_status_data_list`` and
+ # ``state_status_data_by_role`` below both project from this
+ # map, so the per-state construction cost (the
+ # ConsoleConverterHelper lookup and the _get_svg_status_style
+ # dispatch) is paid once per render even when both projections
+ # are accessed (the typical ``to_template_context()`` path).
+ self.state_display_data_map = {
+ d.entity_state.id: EntityStateDisplayData( d )
+ for d in self.entity_status_data.entity_state_status_data_list
+ }
+
+ @property
+ def entity(self) -> Entity:
+ return self.entity_status_data.entity
+
+ @property
+ def entity_for_video(self) -> Optional[Entity]:
+ return self.entity_status_data.entity_for_video
+
+ @property
+ def display_only_svg_icon_item(self) -> Optional[SvgIconItem]:
+ return self.entity_status_data.display_only_svg_icon_item
+
+ @property
+ def display_category(self) -> EntityDisplayCategory:
+ return self.entity_status_data.display_category
+
+ @property
+ def state_status_data_list(self) -> List['EntityStateDisplayData']:
+ """Display-ordered list of per-state display projections,
+ sorted by ``ENTITY_STATUS_VIEW_ORDERING`` for the entity's
+ type. Each item wraps the corresponding raw
+ ``EntityStateStatusData``."""
+ ordered_raw = sorted(
+ self.entity_status_data.entity_state_status_data_list,
+ key = lambda d: ENTITY_STATUS_VIEW_ORDERING.sort_key(
+ d.entity_state.entity_state_role,
+ self.entity_status_data.entity.entity_type,
+ ),
+ )
+ return [ self.state_display_data_map[ d.entity_state.id ] for d in ordered_raw ]
+
+ @property
+ def state_status_data_by_role(self) -> Dict[str, 'EntityStateDisplayData']:
+ """Role-keyed lookup for panel templates that pull a
+ specific state by semantic role. Keys are the lowercase
+ ``EntityStateRole`` name. Values are
+ ``EntityStateDisplayData`` so panel templates get the
+ display-ready accessors directly."""
+ return {
+ d.entity_state.entity_state_role.name.lower(): self.state_display_data_map[ d.entity_state.id ]
+ for d in self.entity_status_data.entity_state_status_data_list
+ }
+
+ def to_template_context(self) -> Dict:
+ return {
+ 'entity': self.entity,
+ 'entity_status_data': self,
+ 'state_status_data_list': self.state_status_data_list,
+ 'state_status_data_by_role': self.state_status_data_by_role,
+ 'entity_for_video': self.entity_for_video,
+ 'display_only_svg_icon_item': self.display_only_svg_icon_item,
+ 'display_category': self.display_category,
+ }
diff --git a/src/hi/apps/monitor/transient_models.py b/src/hi/apps/monitor/status_data.py
similarity index 62%
rename from src/hi/apps/monitor/transient_models.py
rename to src/hi/apps/monitor/status_data.py
index f827688d..c2f3bede 100644
--- a/src/hi/apps/monitor/transient_models.py
+++ b/src/hi/apps/monitor/status_data.py
@@ -3,7 +3,6 @@ from typing import List
from hi.apps.control.transient_models import ControllerData
from hi.apps.common.svg_models import SvgIconItem
-from hi.apps.entity.entity_state_role_order import ENTITY_STATUS_VIEW_ORDERING
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.transient_models import SensorResponse
@@ -42,32 +41,6 @@ class EntityStatusData:
if not self.entity_for_video and self.entity.has_video_stream:
self.entity_for_video = self.entity
return
-
- @property
- def state_status_data_list(self) -> List[ EntityStateStatusData ]:
- """Display-ordered EntityStateStatusData list, sorted by
- ``ENTITY_STATUS_VIEW_ORDERING`` for the entity's EntityType.
- Use this in templates and other consumers that need the
- canonical display order. The underlying
- ``entity_state_status_data_list`` field stays order-neutral
- for consumers (e.g., per-state CSS-class update paths) that
- don't care about listing order."""
- return sorted(
- self.entity_state_status_data_list,
- key = lambda d: ENTITY_STATUS_VIEW_ORDERING.sort_key(
- d.entity_state.entity_state_role, self.entity.entity_type,
- ),
- )
-
- def to_template_context(self):
- context = {
- 'entity': self.entity,
- 'state_status_data_list': self.state_status_data_list,
- 'entity_for_video': self.entity_for_video,
- 'display_only_svg_icon_item': self.display_only_svg_icon_item,
- 'display_category': self.display_category,
- }
- return context
@property
def display_category( self ) -> EntityDisplayCategory:
diff --git a/src/hi/apps/monitor/status_display_manager.py b/src/hi/apps/monitor/status_display_manager.py
index 626b6a5b..7189413b 100644
--- a/src/hi/apps/monitor/status_display_manager.py
+++ b/src/hi/apps/monitor/status_display_manager.py
@@ -14,8 +14,8 @@ from hi.apps.sense.sensor_response_manager import SensorResponseMixin
from hi.apps.sense.transient_models import SensorResponse
from hi.testing.dev_overrides import DevOverrideManager
-from .status_display_data import StatusDisplayData
-from .transient_models import EntityStatusData, EntityStateStatusData
+from .display_data import EntityStateDisplayData
+from .status_data import EntityStatusData, EntityStateStatusData
class StatusDisplayManager( Singleton, SensorResponseMixin ):
@@ -31,18 +31,17 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
def get_entity_state_status_map( self ) -> Dict[ str, dict ]:
"""Build the per-EntityState polling-update map consumed by
- the client. One pass through ``StatusDisplayData`` per
- EntityState produces all three UI update pieces
- (attributes, controller, display_value) in one structure."""
+ the client. Keyed by the EntityState id (as a string, since
+ JSON object keys are always strings). The value shape is
+ defined by ``EntityStateDisplayData.to_polling_update_dict``."""
entity_state_status_data_list = self.get_all_entity_state_status_data_list()
status_map : Dict[ str, dict ] = {}
for entity_state_status_data in entity_state_status_data_list:
- status_display_data = StatusDisplayData( entity_state_status_data )
- status_map[ status_display_data.css_class ] = (
- status_display_data.to_polling_update_dict()
- )
+ status_display_data = EntityStateDisplayData( entity_state_status_data )
+ state_id_key = str( status_display_data.entity_state.id )
+ status_map[ state_id_key ] = status_display_data.to_polling_update_dict()
if settings.DEBUG and settings.DEBUG_TRACE_STATE:
latest = status_display_data.sensor_response_list[ 0 ]
DevOverrideManager.trace_state(
@@ -50,7 +49,7 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
ha_entity_id = latest.integration_key.integration_name,
hi_entity_state_id = status_display_data.entity_state.id,
hi_value = latest.value,
- row = status_map[ status_display_data.css_class ],
+ row = status_map[ state_id_key ],
)
continue
diff --git a/src/hi/apps/monitor/tests/test_transient_models.py b/src/hi/apps/monitor/tests/test_status_data.py
similarity index 68%
rename from src/hi/apps/monitor/tests/test_transient_models.py
rename to src/hi/apps/monitor/tests/test_status_data.py
index 2402a983..5d765f5f 100644
--- a/src/hi/apps/monitor/tests/test_transient_models.py
+++ b/src/hi/apps/monitor/tests/test_status_data.py
@@ -1,7 +1,8 @@
import logging
from unittest.mock import Mock
-from hi.apps.monitor.transient_models import EntityStateStatusData, EntityStatusData
+from hi.apps.monitor.display_data import EntityDisplayData
+from hi.apps.monitor.status_data import EntityStateStatusData, EntityStatusData
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.transient_models import SensorResponse
from hi.apps.control.transient_models import ControllerData
@@ -128,29 +129,36 @@ class TestEntityStateStatusData(BaseTestCase):
class TestEntityStatusData(BaseTestCase):
def test_template_context_includes_all_required_display_data(self):
- """Test template context provides complete data for UI rendering."""
+ """``EntityDisplayData.to_template_context`` provides the keys
+ templates rely on for rendering, with the per-state list
+ wrapped in display-ready ``EntityStateDisplayData`` items."""
entity = Entity.objects.create(
name='Display Entity',
- entity_type_str='CAMERA'
+ entity_type_str='CAMERA',
+ )
+ state_1 = EntityState.objects.create(
+ entity=entity, name='State 1',
+ entity_state_type_str='ON_OFF',
+ )
+ state_2 = EntityState.objects.create(
+ entity=entity, name='State 2',
+ entity_state_type_str='MOVEMENT',
)
-
- # Create mock entity state status data
- state_status_data1 = Mock(spec=EntityStateStatusData)
- state_status_data1.entity_state = Mock()
- state_status_data1.entity_state.entity_state_type_str = 'ON_OFF'
-
- state_status_data2 = Mock(spec=EntityStateStatusData)
- state_status_data2.entity_state = Mock()
- state_status_data2.entity_state.entity_state_type_str = 'MOTION'
-
status_data = EntityStatusData(
entity=entity,
- entity_state_status_data_list=[state_status_data1, state_status_data2]
+ entity_state_status_data_list=[
+ EntityStateStatusData(
+ entity_state=state_1,
+ sensor_response_list=[], controller_data_list=[],
+ ),
+ EntityStateStatusData(
+ entity_state=state_2,
+ sensor_response_list=[], controller_data_list=[],
+ ),
+ ],
)
-
- context = status_data.to_template_context()
-
- # Should include all data needed for template rendering
+ display_data = EntityDisplayData(entity_status_data=status_data)
+ context = display_data.to_template_context()
self.assertIn('entity', context)
self.assertIn('state_status_data_list', context)
self.assertEqual(context['entity'], entity)
@@ -192,8 +200,8 @@ class TestEntityStatusData(BaseTestCase):
self.assertEqual(len(status_data.entity_state_status_data_list), 0)
self.assertIsNone(status_data.display_only_svg_icon_item)
- # Template context should still be valid
- context = status_data.to_template_context()
+ # Template context should still be valid (via display wrapper)
+ context = EntityDisplayData(entity_status_data=status_data).to_template_context()
self.assertEqual(context['entity'], entity)
self.assertEqual(len(context['state_status_data_list']), 0)
@@ -238,3 +246,70 @@ class TestEntityStatusData(BaseTestCase):
self.assertIn('ON_OFF', state_types)
self.assertIn('MOTION', state_types)
self.assertIn('RECORDING', state_types)
+
+
+class TestStateStatusDataByRole(BaseTestCase):
+ """``EntityDisplayData.state_status_data_by_role`` indexes the
+ state-status entries by the lowercase EntityStateRole name so
+ panel templates can pull a specific state by semantic role."""
+
+ def test_keys_are_lowercase_role_names(self):
+ from hi.apps.entity.enums import EntityStateRole, EntityType
+ from hi.apps.entity.models import EntityState
+
+ entity = Entity.objects.create(
+ name='Smoke Test',
+ entity_type_str=str(EntityType.SMOKE_DETECTOR),
+ )
+ smoke_state = EntityState.objects.create(
+ entity=entity, name='Smoke',
+ entity_state_type_str='SMOKE',
+ role_str=str(EntityStateRole.SMOKE),
+ )
+ battery_state = EntityState.objects.create(
+ entity=entity, name='Battery',
+ entity_state_type_str='BATTERY_LEVEL',
+ role_str=str(EntityStateRole.BATTERY_LEVEL),
+ )
+
+ status_data = EntityStatusData(
+ entity=entity,
+ entity_state_status_data_list=[
+ EntityStateStatusData(
+ entity_state=smoke_state,
+ sensor_response_list=[], controller_data_list=[],
+ ),
+ EntityStateStatusData(
+ entity_state=battery_state,
+ sensor_response_list=[], controller_data_list=[],
+ ),
+ ],
+ )
+ display_data = EntityDisplayData(entity_status_data=status_data)
+
+ by_role = display_data.state_status_data_by_role
+ self.assertIn('smoke', by_role)
+ self.assertIn('battery_level', by_role)
+ self.assertEqual(by_role['smoke'].entity_state, smoke_state)
+ self.assertEqual(by_role['battery_level'].entity_state, battery_state)
+
+ def test_empty_when_no_states(self):
+ entity = Entity.objects.create(
+ name='Empty', entity_type_str='OTHER',
+ )
+ status_data = EntityStatusData(
+ entity=entity, entity_state_status_data_list=[],
+ )
+ display_data = EntityDisplayData(entity_status_data=status_data)
+ self.assertEqual(display_data.state_status_data_by_role, {})
+
+ def test_template_context_includes_by_role_map(self):
+ entity = Entity.objects.create(
+ name='Ctx Test', entity_type_str='OTHER',
+ )
+ status_data = EntityStatusData(
+ entity=entity, entity_state_status_data_list=[],
+ )
+ display_data = EntityDisplayData(entity_status_data=status_data)
+ context = display_data.to_template_context()
+ self.assertIn('state_status_data_by_role', context)
diff --git a/src/hi/apps/monitor/tests/test_status_display_data.py b/src/hi/apps/monitor/tests/test_status_display_data.py
index a63864bd..5f4ba921 100644
--- a/src/hi/apps/monitor/tests/test_status_display_data.py
+++ b/src/hi/apps/monitor/tests/test_status_display_data.py
@@ -5,16 +5,16 @@ from unittest.mock import Mock, patch
from hi.apps.entity.models import Entity, EntityState
from hi.apps.entity.enums import EntityStateValue
from hi.apps.sense.transient_models import SensorResponse
-from hi.apps.monitor.status_display_data import StatusDisplayData
-from hi.apps.monitor.transient_models import EntityStateStatusData
+from hi.apps.monitor.display_data import EntityStateDisplayData
+from hi.apps.monitor.status_data import EntityStateStatusData
from hi.hi_styles import StatusStyle
from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
-class TestStatusDisplayData(BaseTestCase):
- """Test StatusDisplayData business logic and style calculations."""
+class TestEntityStateDisplayData(BaseTestCase):
+ """Test EntityStateDisplayData business logic and style calculations."""
def setUp(self):
super().setUp()
@@ -53,7 +53,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.ON))
status_data = self._create_entity_state_status_data('ON_OFF', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.On)
self.assertFalse(display_data.should_skip)
@@ -63,7 +63,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.OFF))
status_data = self._create_entity_state_status_data('ON_OFF', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.Off)
self.assertFalse(display_data.should_skip)
@@ -73,7 +73,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response('INVALID')
status_data = self._create_entity_state_status_data('ON_OFF', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertIsNone(display_data.svg_status_style)
self.assertTrue(display_data.should_skip)
@@ -85,7 +85,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.CONNECTED))
status_data = self._create_entity_state_status_data('CONNECTIVITY', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.Connected)
@@ -94,7 +94,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.DISCONNECTED))
status_data = self._create_entity_state_status_data('CONNECTIVITY', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.Disconnected)
@@ -105,7 +105,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.HIGH))
status_data = self._create_entity_state_status_data('HIGH_LOW', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.High)
@@ -114,7 +114,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.LOW))
status_data = self._create_entity_state_status_data('HIGH_LOW', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.Low)
@@ -128,7 +128,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.ACTIVE))
status_data = self._create_entity_state_status_data('MOVEMENT', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementActive)
@@ -150,7 +150,7 @@ class TestStatusDisplayData(BaseTestCase):
status_data = self._create_entity_state_status_data('MOVEMENT', [recent_response, past_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementRecent)
@@ -172,7 +172,7 @@ class TestStatusDisplayData(BaseTestCase):
status_data = self._create_entity_state_status_data('MOVEMENT', [recent_response, past_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementPast)
@@ -194,7 +194,7 @@ class TestStatusDisplayData(BaseTestCase):
status_data = self._create_entity_state_status_data('MOVEMENT', [recent_response, past_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementIdle)
@@ -213,7 +213,7 @@ class TestStatusDisplayData(BaseTestCase):
)
status_data = self._create_entity_state_status_data('SMOKE', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.SmokeDetected)
@@ -236,7 +236,7 @@ class TestStatusDisplayData(BaseTestCase):
'SMOKE', [recent_response, past_response],
)
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.SmokeRecent)
@@ -259,7 +259,7 @@ class TestStatusDisplayData(BaseTestCase):
'SMOKE', [recent_response, past_response],
)
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.SmokePast)
@@ -281,7 +281,7 @@ class TestStatusDisplayData(BaseTestCase):
'SMOKE', [recent_response, past_response],
)
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.SmokeClear)
@@ -295,7 +295,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.ACTIVE))
status_data = self._create_entity_state_status_data('PRESENCE', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
# PRESENCE reuses Movement styles in the implementation
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementActive)
@@ -308,7 +308,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.IDLE))
status_data = self._create_entity_state_status_data('PRESENCE', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
# Should return MovementIdle for inactive presence
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementIdle)
@@ -323,7 +323,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.OPEN))
status_data = self._create_entity_state_status_data('OPEN_CLOSE', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.Open)
@@ -345,7 +345,7 @@ class TestStatusDisplayData(BaseTestCase):
status_data = self._create_entity_state_status_data('OPEN_CLOSE', [recent_response, past_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.OpenRecent)
@@ -367,7 +367,7 @@ class TestStatusDisplayData(BaseTestCase):
status_data = self._create_entity_state_status_data('OPEN_CLOSE', [recent_response, past_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.OpenPast)
@@ -389,7 +389,7 @@ class TestStatusDisplayData(BaseTestCase):
status_data = self._create_entity_state_status_data('OPEN_CLOSE', [recent_response, past_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.Closed)
@@ -401,7 +401,7 @@ class TestStatusDisplayData(BaseTestCase):
'OPEN_CLOSE_POSITION', [ sensor_response ],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.svg_status_style, StatusStyle.Closed )
@@ -415,7 +415,7 @@ class TestStatusDisplayData(BaseTestCase):
'OPEN_CLOSE_POSITION', [ sensor_response ],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.svg_status_style, StatusStyle.OpenPartial )
@@ -427,7 +427,7 @@ class TestStatusDisplayData(BaseTestCase):
'OPEN_CLOSE_POSITION', [ sensor_response ],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.svg_status_style, StatusStyle.Open )
@@ -439,7 +439,7 @@ class TestStatusDisplayData(BaseTestCase):
'OPEN_CLOSE_POSITION', [ sensor_response ],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.svg_status_style, StatusStyle.Closed )
@@ -454,7 +454,7 @@ class TestStatusDisplayData(BaseTestCase):
'POWER_LEVEL', [ sensor_response ],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.svg_status_style.status_value, 'off' )
@@ -465,7 +465,7 @@ class TestStatusDisplayData(BaseTestCase):
'POWER_LEVEL', [ sensor_response ],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.svg_status_style.status_value, 'dim' )
@@ -475,7 +475,7 @@ class TestStatusDisplayData(BaseTestCase):
'POWER_LEVEL', [ sensor_response ],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.svg_status_style.status_value, 'dim' )
@@ -486,7 +486,7 @@ class TestStatusDisplayData(BaseTestCase):
'POWER_LEVEL', [ sensor_response ],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.svg_status_style.status_value, 'on' )
@@ -496,7 +496,7 @@ class TestStatusDisplayData(BaseTestCase):
'POWER_LEVEL', [ sensor_response ],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.svg_status_style.status_value, 'on' )
@@ -508,7 +508,7 @@ class TestStatusDisplayData(BaseTestCase):
'POWER_LEVEL', [ sensor_response ],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.svg_status_style.status_value, 'off' )
@@ -518,7 +518,7 @@ class TestStatusDisplayData(BaseTestCase):
"""Test default style is returned when no sensor data exists."""
status_data = self._create_entity_state_status_data('TEMPERATURE', [])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
# Should use default style with DEFAULT_STATUS_VALUE when no sensor data
self.assertIsNotNone(display_data.svg_status_style)
@@ -533,7 +533,7 @@ class TestStatusDisplayData(BaseTestCase):
expected_style = Mock()
mock_default.return_value = expected_style
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
mock_default.assert_called_once_with(status_value='25.5')
self.assertEqual(display_data.svg_status_style, expected_style)
@@ -543,7 +543,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.IDLE))
status_data = self._create_entity_state_status_data('MOVEMENT', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
# Should return idle since no penultimate active state
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementIdle)
@@ -555,7 +555,7 @@ class TestStatusDisplayData(BaseTestCase):
def test_css_class_delegates_to_entity_state(self):
"""Test css_class property delegates to entity_state."""
status_data = self._create_entity_state_status_data('ON_OFF', [])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
# Entity state css_class should be accessible
css_class = display_data.css_class
@@ -567,7 +567,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response(str(EntityStateValue.ON))
status_data = self._create_entity_state_status_data('ON_OFF', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
# Should return the style's to_dict() result
attr_dict = display_data.attribute_dict
@@ -579,7 +579,7 @@ class TestStatusDisplayData(BaseTestCase):
sensor_response = self._create_mock_sensor_response('INVALID')
status_data = self._create_entity_state_status_data('ON_OFF', [sensor_response])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.attribute_dict, {})
@@ -589,7 +589,7 @@ class TestStatusDisplayData(BaseTestCase):
response2 = self._create_mock_sensor_response('VALUE2')
status_data = self._create_entity_state_status_data('ON_OFF', [response1, response2])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.latest_sensor_value, 'VALUE1')
@@ -599,7 +599,7 @@ class TestStatusDisplayData(BaseTestCase):
response2 = self._create_mock_sensor_response('VALUE2')
status_data = self._create_entity_state_status_data('ON_OFF', [response1, response2])
- display_data = StatusDisplayData(status_data)
+ display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.penultimate_sensor_value, 'VALUE2')
@@ -631,7 +631,7 @@ class TestLatestDisplayLabel(BaseTestCase):
sensor_response_list = [ response ],
controller_data_list = [],
)
- return StatusDisplayData( status_data )
+ return EntityStateDisplayData( status_data )
def test_unit_less_enum_value_returns_labeled_form(self):
# ``smoke_detected`` (wire form) → ``Smoke Detected``
@@ -682,7 +682,7 @@ class TestLatestDisplayLabel(BaseTestCase):
sensor_response_list = [],
controller_data_list = [],
)
- display_data = StatusDisplayData( status_data )
+ display_data = EntityStateDisplayData( status_data )
self.assertEqual( display_data.latest_display_label, '' )
@@ -690,10 +690,11 @@ class TestToPollingUpdateDict(BaseTestCase):
"""``to_polling_update_dict`` builds the per-EntityState row of
the unified ``entityStateStatusMap``. Pins the contract for
each kind of EntityState the polling path sees: sensor-only
- (no ``controller`` key), unit-bearing (``magnitude`` and
- ``unit_symbol`` present in display_value), unit-less enum
- (``magnitude``/``unit_symbol`` absent), and the always-present
- ``attributes`` and ``display_value`` keys."""
+ (no ``controller``), unit-bearing (``magnitude`` and ``unit``
+ present in ``display``), unit-less enum (``magnitude``/``unit``
+ absent), the always-present ``display`` key, and the optional
+ ``status`` / ``svg_style`` bundle for elements that opt in via
+ ``[data-status]`` / ``[data-svg-style]``."""
def setUp(self):
super().setUp()
@@ -721,7 +722,7 @@ class TestToPollingUpdateDict(BaseTestCase):
sensor_response_list = [ response ],
controller_data_list = controller_data_list,
)
- return StatusDisplayData( status_data )
+ return EntityStateDisplayData( status_data )
def test_sensor_only_row_omits_controller_key(self):
display_data = self._make_display_data(
@@ -738,56 +739,65 @@ class TestToPollingUpdateDict(BaseTestCase):
self.assertIn( 'controller', row )
self.assertIn( 'value', row[ 'controller' ] )
- def test_unit_bearing_display_value_includes_magnitude_and_unit(self):
+ def test_unit_bearing_display_includes_magnitude_and_unit(self):
display_data = self._make_display_data(
'TEMPERATURE', '21', units = '°C',
)
row = display_data.to_polling_update_dict()
- display_value = row[ 'display_value' ]
- self.assertIn( 'text', display_value )
- self.assertIn( 'magnitude', display_value )
- self.assertIn( 'unit_symbol', display_value )
+ display = row[ 'display' ]
+ self.assertIn( 'text', display )
+ self.assertIn( 'magnitude', display )
+ self.assertIn( 'unit', display )
- def test_unit_less_display_value_omits_magnitude_and_unit(self):
+ def test_unit_less_display_omits_magnitude_and_unit(self):
display_data = self._make_display_data(
'MOVEMENT', str(EntityStateValue.ACTIVE),
)
row = display_data.to_polling_update_dict()
- display_value = row[ 'display_value' ]
- self.assertIn( 'text', display_value )
- self.assertNotIn( 'magnitude', display_value )
- self.assertNotIn( 'unit_symbol', display_value )
+ display = row[ 'display' ]
+ self.assertIn( 'text', display )
+ self.assertNotIn( 'magnitude', display )
+ self.assertNotIn( 'unit', display )
- def test_display_value_text_is_human_readable_label(self):
+ def test_display_text_is_human_readable_label(self):
# Same source of truth as ``value_label`` template filter —
# JS sets element.textContent to this string.
display_data = self._make_display_data(
'SMOKE', str(EntityStateValue.SMOKE_DETECTED),
)
row = display_data.to_polling_update_dict()
- self.assertEqual(
- row[ 'display_value' ][ 'text' ], 'Smoke Detected',
- )
+ self.assertEqual( row[ 'display' ][ 'text' ], 'Smoke Detected' )
- def test_display_value_text_humanizes_free_form_wire_value(self):
+ def test_display_text_humanizes_free_form_wire_value(self):
# DISCRETE-typed states (HA hvac_action, fan preset, etc.)
# carry free-form wire values not bound to an
- # EntityStateValue member. The polling map's
- # ``display_value.text`` humanizes them so the sensor card
- # displays a readable label on poll refresh — the headline
- # behavior of #310.
+ # EntityStateValue member. The polling map's display text
+ # humanizes them so the sensor card displays a readable
+ # label on poll refresh — the headline behavior of #310.
display_data = self._make_display_data( 'DISCRETE', 'heating' )
row = display_data.to_polling_update_dict()
- self.assertEqual(
- row[ 'display_value' ][ 'text' ], 'Heating',
- )
+ self.assertEqual( row[ 'display' ][ 'text' ], 'Heating' )
- def test_attributes_always_present(self):
- # Even for unrecognized values where there's no SVG style,
- # ``attributes`` is always emitted (possibly as an empty
- # dict) — the JS dispatcher iterates whatever keys it
- # finds and is safe with an empty mapping.
+ def test_status_present_when_svg_style_present(self):
+ # SVG-styled states publish both a top-level ``status`` (for
+ # ``[data-status]`` consumers like panel roots) and the full
+ # ``svg_style`` bundle (for ``[data-svg-style]`` consumers
+ # like LocationView icon ``<g>`` elements).
+ display_data = self._make_display_data(
+ 'MOVEMENT', str(EntityStateValue.ACTIVE),
+ )
+ row = display_data.to_polling_update_dict()
+ self.assertIn( 'status', row )
+ self.assertIn( 'svg_style', row )
+ self.assertEqual( row[ 'status' ], row[ 'svg_style' ][ 'status' ] )
+
+ def test_status_and_svg_style_omitted_when_no_svg_style(self):
+ # When the value produces no svg_status_style (e.g., ON_OFF
+ # with an unrecognized value), both the top-level status and
+ # the svg_style bundle are absent. ``display`` is still
+ # present so display-text consumers keep refreshing.
display_data = self._make_display_data( 'ON_OFF', 'INVALID' )
row = display_data.to_polling_update_dict()
- self.assertIn( 'attributes', row )
- self.assertIsInstance( row[ 'attributes' ], dict )
+ self.assertNotIn( 'status', row )
+ self.assertNotIn( 'svg_style', row )
+ self.assertIn( 'display', row )
diff --git a/src/hi/apps/monitor/tests/test_status_display_manager.py b/src/hi/apps/monitor/tests/test_status_display_manager.py
index c59bc232..5a5070b1 100644
--- a/src/hi/apps/monitor/tests/test_status_display_manager.py
+++ b/src/hi/apps/monitor/tests/test_status_display_manager.py
@@ -6,7 +6,7 @@ from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.models import Sensor
from hi.apps.sense.transient_models import SensorResponse
from hi.apps.monitor.status_display_manager import StatusDisplayManager
-from hi.apps.monitor.transient_models import EntityStateStatusData
+from hi.apps.monitor.status_data import EntityStateStatusData
from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
@@ -240,11 +240,11 @@ class TestStatusDisplayManager(BaseTestCase):
# The unified map emits a row for every EntityState with a
# response, even those whose value produces no
# ``svg_status_style`` (e.g., ON_OFF with an unrecognized
- # value). The pre-refactor ``cssClassUpdateMap`` skipped
- # these; the unified shape carries display_value and
- # (when applicable) controller updates which remain useful
- # independent of icon styling, so they're always
- # emitted with an empty ``attributes`` dict.
+ # value). The pre-refactor cssClassUpdateMap skipped these;
+ # the unified shape carries ``display`` (and, when
+ # applicable, ``controller``) updates which remain useful
+ # independent of icon styling. States with no SVG style
+ # simply omit ``status`` / ``svg_style`` from their row.
entity = Entity.objects.create(
name='Unrecognized State', entity_type_str='SENSOR',
)
@@ -266,5 +266,8 @@ class TestStatusDisplayManager(BaseTestCase):
return_value=[status_data]):
result = manager.get_entity_state_status_map()
- self.assertIn(entity_state.css_class, result)
- self.assertEqual(result[entity_state.css_class]['attributes'], {})
+ state_id_key = str(entity_state.id)
+ self.assertIn(state_id_key, result)
+ self.assertNotIn('svg_style', result[state_id_key])
+ self.assertNotIn('status', result[state_id_key])
+ self.assertIn('display', result[state_id_key])
diff --git a/src/hi/apps/sense/templates/sense/modals/sensor_history_details.html b/src/hi/apps/sense/templates/sense/modals/sensor_history_details.html
index 92d3b255..5ab2a56c 100644
--- a/src/hi/apps/sense/templates/sense/modals/sensor_history_details.html
+++ b/src/hi/apps/sense/templates/sense/modals/sensor_history_details.html
@@ -13,7 +13,7 @@ Sensor Response Details
{% sensor_response_video_stream sensor_response as video_stream %}
{% if video_stream and video_stream.source_url %}
<div>
- <img class="img-fluid" src="{{ video_stream.source_url }}" alt="Sensor History">
+ <img class="img-fluid" data-video-stream src="{{ video_stream.source_url }}" alt="Sensor History">
</div>
{% elif sensor_response.source_image_url %}
<!-- Fallback to image when video stream is not available -->
diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html
index 275e8e2d..49359428 100644
--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html
+++ b/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html
@@ -35,9 +35,7 @@
</div>
<div class="col-6 align-self-center">
<a href="{{ sensor_response.click_url }}" title="See details" data-async="true">
- <div class="{{ sensor_response.css_class }}">
- {% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}
- </div>
+ {% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}
</a>
</div>
</div>
diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html
index 44231672..ae3d62b9 100644
--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html
+++ b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html
@@ -1,2 +1,2 @@
{% load entity_tags units %}
-<div class="text-center px-2" status="{{ sensor_response.value }}" display-text>{% if sensor_response.entity_state.units %}{{ sensor_response.value|as_display_value:sensor_response.entity_state }}{% else %}{{ sensor_response.value|value_label }}{% endif %}</div>
+<div class="hi-status-display text-center px-2" data-state-id="{{ sensor_response.sensor.entity_state.id }}" data-status data-display-text status="{{ sensor_response.value }}">{% if sensor_response.entity_state.units %}{{ sensor_response.value|as_display_value:sensor_response.entity_state }}{% else %}{{ sensor_response.value|value_label }}{% endif %}</div>
diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html
index 6b5410f1..a591e0ab 100644
--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html
+++ b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html
@@ -6,6 +6,6 @@ the ``as_display_value`` filter goes through ``ConsoleConverterHelper``
to produce a ``DisplayValue`` whose ``__str__`` combines the
user-display magnitude and unit symbol.
{% endcomment %}
-<div class="text-center px-2" status="{{ sensor_response.value }}" display-text>
+<div class="hi-status-display text-center px-2" data-state-id="{{ sensor_response.sensor.entity_state.id }}" data-status data-display-text status="{{ sensor_response.value }}">
{{ sensor_response.value|as_display_value:sensor_response.entity_state }}
</div>
diff --git a/src/hi/apps/system/api_health_status.py b/src/hi/apps/system/api_health_status.py
index 7aab0ddd..56529915 100644
--- a/src/hi/apps/system/api_health_status.py
+++ b/src/hi/apps/system/api_health_status.py
@@ -142,7 +142,7 @@ class ApiHealthStatus:
ApiHealthStatusType.HEALTHY: "check-circle",
ApiHealthStatusType.DEGRADED: "warning",
ApiHealthStatusType.UNKNOWN: "question-circle",
- ApiHealthStatusType.FAILING: "times-circle",
+ ApiHealthStatusType.FAILING: "exclamation-circle",
ApiHealthStatusType.UNAVAILABLE: "exclamation-circle",
ApiHealthStatusType.DISABLED: "minus-circle"
}[self.status]
diff --git a/src/hi/apps/system/health_status.py b/src/hi/apps/system/health_status.py
index 30403c8f..b1c7e62e 100644
--- a/src/hi/apps/system/health_status.py
+++ b/src/hi/apps/system/health_status.py
@@ -144,7 +144,7 @@ class HealthStatus:
elif self.status.is_info:
return "info-circle"
elif self.status.is_critical:
- return "times-circle"
+ return "exclamation-circle"
elif self.status.is_error:
return "exclamation-circle"
else: # UNKNOWN
diff --git a/src/hi/apps/system/templates/system/tests/ui/home.html b/src/hi/apps/system/templates/system/tests/ui/home.html
index dfe8d80a..3d26e6dc 100644
--- a/src/hi/apps/system/templates/system/tests/ui/home.html
+++ b/src/hi/apps/system/templates/system/tests/ui/home.html
@@ -61,7 +61,7 @@
</li>
<li class="list-group-item">
<a href="{% url 'system_test_ui_health_status' status_type='error' api_flag='with-api' %}" data-async="modal">
- {% icon "times-circle" size="sm" css_class="mr-2 text-danger" %}
+ {% icon "exclamation-circle" size="sm" css_class="mr-2 text-danger" %}
Error Status + APIs
</a>
</li>
diff --git a/src/hi/context_processors.py b/src/hi/context_processors.py
index 7ce0a624..b03c16f2 100644
--- a/src/hi/context_processors.py
+++ b/src/hi/context_processors.py
@@ -1,8 +1,11 @@
+from django.conf import settings
+
from .constants import DIVID
def constants_context(request):
return {
'DIVID': DIVID,
+ 'STATIC_URL': settings.STATIC_URL,
}
diff --git a/src/hi/integrations/templates/integrations/panes/integration_health_banner.html b/src/hi/integrations/templates/integrations/panes/integration_health_banner.html
new file mode 100644
index 00000000..6a5007af
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/panes/integration_health_banner.html
@@ -0,0 +1,32 @@
+{% load icons %}
+{% comment %}
+Integration health banner — surfaces WARNING / ERROR / DISABLED states
+in any UI that depends on an integration's data. Renders nothing when
+the integration is HEALTHY or when health_status is unavailable.
+
+Parameters (supplied by the ``integration_health_banner`` template
+tag):
+ health_status : HealthStatus instance, or None.
+ integration_label : Display label for the integration (e.g.,
+ "Home Assistant").
+ context_message : Optional short string describing how this
+ integration's degraded state affects the
+ surrounding UI (e.g., "Values shown may be
+ stale; controls may not respond.").
+
+Styling defers to HealthStatus.status_alert_class (Bootstrap alert
+variant) and status_icon (icon name) so the visual treatment matches
+the rest of the health-status UI in the application.
+{% endcomment %}
+{% if health_status and not health_status.is_healthy %}
+<div class="alert {{ health_status.status_alert_class }} d-flex align-items-start mb-3 py-2"
+ role="alert">
+ {% icon health_status.status_icon size="sm" css_class="mr-2 mt-1" %}
+ <div>
+ <strong>{{ integration_label }}: {{ health_status.status_display }}</strong>
+ {% if context_message %}
+ <div class="small">{{ context_message }}</div>
+ {% endif %}
+ </div>
+</div>
+{% endif %}
diff --git a/src/hi/integrations/templatetags/integration_tags.py b/src/hi/integrations/templatetags/integration_tags.py
index bbb438aa..02679df6 100644
--- a/src/hi/integrations/templatetags/integration_tags.py
+++ b/src/hi/integrations/templatetags/integration_tags.py
@@ -63,3 +63,34 @@ def previous_integration_logo_path( model : IntegrationDetailsModel ) -> str:
metadata = _get_previous_integration_metadata( model )
return metadata.logo_static_path if metadata else ''
+
[email protected]_tag( 'integrations/panes/integration_health_banner.html' )
+def integration_health_banner( integration_id : str, context_message : str = None ):
+ """Render a banner when the integration is in a non-healthy state.
+
+ Renders nothing for HEALTHY or when the integration cannot be
+ resolved. Use from any UI that depends on an integration's data
+ so the operator is alerted when displayed state may be stale or
+ actions may not take effect.
+
+ Parameters:
+ integration_id : The entity's / surface's owning integration id.
+ context_message : Optional message describing how the integration's
+ degraded state affects the surrounding UI."""
+ if not integration_id:
+ return { 'health_status': None }
+ try:
+ gateway = IntegrationManager().get_integration_gateway( integration_id )
+ provider = gateway.get_health_status_provider()
+ health_status = provider.health_status
+ metadata = gateway.get_metadata()
+ except Exception:
+ logger.debug( 'integration_health_banner: lookup failed for %r',
+ integration_id )
+ return { 'health_status': None }
+ return {
+ 'health_status': health_status,
+ 'integration_label': metadata.label if metadata else integration_id,
+ 'context_message': context_message,
+ }
+
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index 354ccfb6..ac5bb4cf 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -1905,7 +1905,7 @@ class HassConverter:
# PRESENCE shares the [ACTIVE, IDLE] EntityStateValue
# vocabulary with MOVEMENT but renders under its own
# state-type label and styling decay (see
- # ``StatusDisplayData._get_presence_status_style``).
+ # ``EntityStateDisplayData._get_presence_status_style``).
sensor = HiModelHelper.create_presence_sensor(
entity = entity,
integration_key = integration_key,
diff --git a/src/hi/services/hass/tests/test_hass_converter_binary_sensor.py b/src/hi/services/hass/tests/test_hass_converter_binary_sensor.py
index c7903029..3cad7cf8 100644
--- a/src/hi/services/hass/tests/test_hass_converter_binary_sensor.py
+++ b/src/hi/services/hass/tests/test_hass_converter_binary_sensor.py
@@ -73,7 +73,7 @@ class TestSmokeBinarySensor(TestCase):
# previously had no SMOKE branch and fell through to
# ``create_blob_sensor`` — the EntityState ended up with
# ``entity_state_type_str='blob'``, breaking every smoke-
- # specific dispatch downstream (StatusDisplayData,
+ # specific dispatch downstream (EntityStateDisplayData,
# rendering, etc.).
device, _ = _build_binary_sensor_device(
'kitchen_smoke', device_class = 'smoke',
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index 82e6c106..90f8480c 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -247,6 +247,9 @@ PIPELINE = {
'css/attribute.css',
'css/stream-browser.css',
'css/control.css',
+ 'state_panels/smoke_detector/smoke_detector.css',
+ 'state_panels/camera/camera.css',
+ 'state_panels/thermostat/thermostat.css',
),
'output_filename': 'css/css_head.css',
},
@@ -265,7 +268,8 @@ PIPELINE = {
'js/antinode.js',
'js/autosize.min.js',
'js/main.js',
- 'js/controllers.js',
+ 'js/entity_state_status.js',
+ 'state_panels/fallback/fallback.js',
),
'output_filename': 'js/js_before_content.js',
},
@@ -291,7 +295,7 @@ PIPELINE = {
'js_hi_grid_content': {
'source_filenames': (
'js/svg-utils.js',
- 'js/entity_state_status.js',
+ 'state_panels/thermostat/thermostat.js',
'js/status.js',
'js/auto-view.js',
'js/edit-dragdrop.js',
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index 69c33208..42d8a0eb 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -727,7 +727,7 @@ g[status="past"] {
g[status="off"] path.hi-state-bg {
fill: var(--status-off-color);
}
-div[status="off"] {
+.hi-status-display[status="off"] {
color: var(--on-status-off-color);
background-color: var(--status-off-color);
}
@@ -737,7 +737,7 @@ g[status="on"] {
g[status="on"] path.hi-state-bg {
fill: var(--status-on-color);
}
-div[status="on"] {
+.hi-status-display[status="on"] {
color: var(--on-status-on-color);
background-color: var(--status-on-color);
}
@@ -745,7 +745,7 @@ g[status="dim"] {
filter: drop-shadow(0 0 5px var(--status-on-color));
opacity: 0.5;
}
-div[status="dim"] {
+.hi-status-display[status="dim"] {
color: var(--on-status-on-color);
background-color: var(--status-on-color);
opacity: 0.5;
@@ -780,7 +780,7 @@ g[status="gas_detected"] {
}
-div[status] {
+.hi-status-display[status] {
color: var(--black);
background-color: var(--white);
border-color: var(--black);
@@ -788,80 +788,80 @@ div[status] {
border-width: 2px;
border-radius: 8px;
}
-div[status="active"] {
+.hi-status-display[status="active"] {
color: var(--on-status-active-color);
background-color: var(--status-active-color);
}
-div[status="idle"] {
+.hi-status-display[status="idle"] {
color: var(--on-status-ok-color);
background-color: var(--status-ok-color);
}
-div[status="recent"] {
+.hi-status-display[status="recent"] {
color: var(--on-status-recent-color);
background-color: var(--status-recent-color);
}
-div[status="past"] {
+.hi-status-display[status="past"] {
color: var(--on-status-past-color);
background-color: var(--status-past-color);
}
-div[status="partial"] {
+.hi-status-display[status="partial"] {
color: var(--on-status-recent-color);
background-color: var(--status-recent-color);
}
-div[status="open"] {
+.hi-status-display[status="open"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
-div[status="closed"] {
+.hi-status-display[status="closed"] {
color: var(--on-status-idle-color);
background-color: var(--status-idle-color);
}
-div[status="RAID_OK"],
-div[status="connected"] {
+.hi-status-display[status="RAID_OK"],
+.hi-status-display[status="connected"] {
color: var(--on-status-ok-color);
background-color: var(--status-ok-color);
}
-div[status="disconnected"] {
+.hi-status-display[status="disconnected"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
-div[status="high"] {
+.hi-status-display[status="high"] {
color: var(--on-status-ok-color);
background-color: var(--status-ok-color);
}
-div[status="low"] {
+.hi-status-display[status="low"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
-div[status="smoke_clear"] {
+.hi-status-display[status="smoke_clear"] {
color: var(--on-status-ok-color);
background-color: var(--status-ok-color);
}
-div[status="smoke_detected"] {
+.hi-status-display[status="smoke_detected"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
-div[status="moisture_clear"] {
+.hi-status-display[status="moisture_clear"] {
color: var(--on-status-ok-color);
background-color: var(--status-ok-color);
}
-div[status="moisture_detected"] {
+.hi-status-display[status="moisture_detected"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
-div[status="co_clear"] {
+.hi-status-display[status="co_clear"] {
color: var(--on-status-ok-color);
background-color: var(--status-ok-color);
}
-div[status="co_detected"] {
+.hi-status-display[status="co_detected"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
-div[status="gas_clear"] {
+.hi-status-display[status="gas_clear"] {
color: var(--on-status-ok-color);
background-color: var(--status-ok-color);
}
-div[status="gas_detected"] {
+.hi-status-display[status="gas_detected"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
@@ -2209,6 +2209,17 @@ g[hover] {
border-left-color: var(--danger-color);
}
+/* Framework subheader rendered between the modal title bar and the
+ panel body. Shows entity-type icon + label on the left, integration
+ logo centered, and the modal-type label on the right. Panels
+ render below this strip and don't repeat any of this identifying
+ chrome. */
+.hi-entity-status-subheader__type-icon .hi-entity-display-only-icon {
+ width: 18px;
+ height: 18px;
+ vertical-align: middle;
+}
+
/* Light primary-tinted banner used as a section header (e.g., the
entity-history modal's per-state group headers). Uses the same
tint as ``.timeline-item:hover`` so the section header reads as
diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.js
index 46fc6e8d..23151412 100644
--- a/src/hi/static/js/antinode.js
+++ b/src/hi/static/js/antinode.js
@@ -287,7 +287,9 @@
});
},
+ addBeforeContentRemovalFunction: addBeforeContentRemovalFunction,
addAfterAsyncRenderFunction: addAfterAsyncRenderFunction,
+ addAfterModalRenderFunction: addAfterModalRenderFunction,
// Display modal content that was rendered server-side.
// Creates a modal wrapper, appends the content, and shows it.
@@ -557,11 +559,12 @@ function asyncUpdateData( $target, $mode, data, xhr ) {
// Alternatively, there are other types of more complicated response
// patterns, and each of these are encoded as a JSON document with
// corresponding content type.
-
+
let ct = xhr.getResponseHeader("content-type") || "";
-
+
if (ct.indexOf('html') > -1) {
if ( $target ) {
+ beforeContentRemoval( $target );
if ( $mode == 'replace' ) {
$target.replaceWith( data );
}
@@ -689,11 +692,19 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {
// In case any content with preserved scroll bars was refreshed.
//
afterAsyncRender();
-
+
if ( 'modal' in json ) {
let targetObj = getNewModal();
targetObj.append( json['modal'] )
showModal( targetObj );
+ // Modal content is now in the DOM. Fires a dedicated
+ // post-modal-insert hook so consumers (e.g., entity-status
+ // panel init handlers) can see the modal's DOM in place.
+ // Kept separate from ``afterAsyncRender`` because the
+ // latter is positioned earlier in this handler to keep
+ // ``restoreScrollBarPositions`` ahead of the
+ // ``resetScrollbar`` / ``scrollTo`` branches below.
+ afterModalRender();
}
// Allowing re-writing URL so it is preserved for navigation and refresh
@@ -782,15 +793,44 @@ function beforeAsyncCall( $node ) {
saveScrollBarPositions();
};
+//====================
+// Things that need to run BEFORE a subtree is detached from the DOM
+// by an antinode-driven operation — either an HTML content swap in
+// ``asyncUpdateData`` or a modal dismissal in
+// ``handleModalHiddenEvent``. Callbacks receive the outgoing
+// ``$subtree`` so they can act on what's about to be removed — e.g.,
+// the video connection manager force-closes long-lived stream
+// fetches before the browser orphans them.
+
+let beforeContentRemovalFunctionList = [];
+
+function beforeContentRemoval( $subtree ) {
+ for ( let i = 0; i < beforeContentRemovalFunctionList.length; i++ ) {
+ try {
+ beforeContentRemovalFunctionList[i]( $subtree );
+ } catch ( e ) {
+ console.error( 'beforeContentRemoval handler error:', e );
+ }
+ }
+};
+
+function addBeforeContentRemovalFunction( func ) {
+ beforeContentRemovalFunctionList.push( func );
+};
+
//====================
// Things that need to run after asynchronous content is rendered
let afterAsyncRenderFunctionList = [];
-
+
function afterAsyncRender() {
for ( let i = 0; i < afterAsyncRenderFunctionList.length; i++ ) {
- afterAsyncRenderFunctionList[i]();
+ try {
+ afterAsyncRenderFunctionList[i]();
+ } catch ( e ) {
+ console.error( 'afterAsyncRender handler error:', e );
+ }
}
restoreScrollBarPositions();
};
@@ -801,6 +841,30 @@ function addAfterAsyncRenderFunction( func_name ) {
afterAsyncRenderFunctionList.push( func_name );
};
+//====================
+// Things that need to run after a modal (delivered as the ``modal``
+// field of a JSON response) has been appended and shown. Distinct
+// from ``afterAsyncRender`` because that fires earlier in the JSON
+// response handler — before modal insertion — to keep scroll-bar
+// restore ahead of explicit scroll directives. Consumers that need
+// to react to the inserted modal DOM register here.
+
+let afterModalRenderFunctionList = [];
+
+function afterModalRender() {
+ for ( let i = 0; i < afterModalRenderFunctionList.length; i++ ) {
+ try {
+ afterModalRenderFunctionList[i]();
+ } catch ( e ) {
+ console.error( 'afterModalRender handler error:', e );
+ }
+ }
+};
+
+function addAfterModalRenderFunction( func_name ) {
+ afterModalRenderFunctionList.push( func_name );
+};
+
//====================
// Preserving scroll bars should be called just prior to an async request
// (for both form submissions and click events). Restoring them should come
@@ -930,14 +994,15 @@ function handleModalHiddenEvent( modalObj ) {
modalHideStartMs = null;
if ( deferredModalShowObj ) {
showModal( deferredModalShowObj );
- }
-
+ }
+
} catch (e) {
console.error('Problem handling modal hidden event');
}
finally {
modalHideStartMs = null;
deferredModalShowObj = null;
+ beforeContentRemoval( $(modalObj) );
$(modalObj).remove();
}
};
diff --git a/src/hi/static/js/controllers.js b/src/hi/static/js/controllers.js
deleted file mode 100644
index 301c6043..00000000
--- a/src/hi/static/js/controllers.js
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * Home Information - Controller widget interaction
- *
- * Two responsibilities:
- *
- * 1. Wire UI affordances on controller templates that need
- * behavior beyond what antinode's onchange-async handler
- * provides (e.g., the dimmer's Off / Full convenience
- * buttons that drive the brightness slider).
- *
- * 2. Apply server-pushed controller widget state via
- * ``Hi.controllers.applyValueMap``. Each map entry is keyed
- * by CSS class and carries a controller-state dict
- * ({value, ...}); every element matching the class gets its
- * widget property updated (slider ``.value``, checkbox
- * ``.checked``, ``<select>`` ``.value``, etc.).
- */
-(function() {
- 'use strict';
-
- window.Hi = window.Hi || {};
- Hi.controllers = Hi.controllers || {};
-
- // Sliders the user is actively dragging. Polling-driven value
- // updates skip these elements so a server refresh mid-drag
- // doesn't yank the thumb out from under the operator's
- // fingers. Cleared on pointerup / change so subsequent polls
- // resume normally — by definition the change-async submit on
- // release will reconcile the value at that point.
- const _activeSliders = new WeakSet();
-
- /**
- * Apply a class-name → controller-state map by finding each
- * matching element and updating the appropriate widget
- * property. Only applies updates when the new value differs
- * from the widget's current state — avoids interfering with
- * an in-progress user interaction (e.g., a slider mid-drag
- * whose optimistic update already matches the polled value).
- *
- * @param {Object} controllerMap - { className: { value, ... } }
- */
- Hi.controllers.applyValueMap = function( controllerMap ) {
- if ( !controllerMap ) return;
- Object.entries( controllerMap ).forEach( function( [ cssClass, controllerDict ] ) {
- const value = controllerDict.value;
- const $elements = $( '.' + cssClass );
- $elements.each( function() {
- _applyValueToElement( this, value );
- });
- });
- };
-
- function _applyValueToElement( element, value ) {
- const tag = element.tagName;
- if ( tag === 'INPUT' ) {
- const type = element.type;
- if ( type === 'range' || type === 'number' || type === 'text' ) {
- if ( type === 'range' && _activeSliders.has( element ) ) {
- return;
- }
- _setIfDifferent( element, 'value', String( value ) );
- _syncSliderDisplay( element );
- return;
- }
- if ( type === 'checkbox' ) {
- const checked = _coerceCheckboxValue( element, value );
- if ( element.checked !== checked ) {
- element.checked = checked;
- }
- _syncCheckboxStatusText( element, checked );
- return;
- }
- }
- if ( tag === 'SELECT' ) {
- _setIfDifferent( element, 'value', String( value ) );
- return;
- }
- // Other shapes (color picker, etc.) get their own branches
- // here as widgets are added. Silently no-op so unrelated
- // class-targeted elements (e.g., the wrapper div sharing
- // the same class for CSS purposes) are unaffected.
- }
-
- function _syncSliderDisplay( slider ) {
- // Mirror a slider's current value into a paired display
- // element. Sliders opt in by declaring two data
- // attributes on the ``<input type=range>``:
- //
- // Hi.CONTROLLER_DISPLAY_TARGET_ATTR CSS selector for
- // the display element, looked up within the
- // enclosing form.
- // Hi.CONTROLLER_DISPLAY_FORMAT_ATTR Format string with
- // ``{n}`` as the value placeholder, e.g. ``{n}%``,
- // ``{n}°``, ``{n}K``. Optional; defaults to ``{n}``.
- //
- // Attribute names are defined in DIVID (server) and
- // mirrored in main.js (client) — templates emit them via
- // the DIVID entries and this code reads them via Hi.
- //
- // Called whenever the slider's value changes (drag,
- // button click, controller-value polling) so the
- // displayed value stays in lock-step with the thumb.
- const selector = slider.getAttribute( Hi.CONTROLLER_DISPLAY_TARGET_ATTR );
- if ( ! selector ) return;
- const $display = $( slider ).closest( 'form' ).find( selector );
- if ( ! $display.length ) return;
- const format = slider.getAttribute( Hi.CONTROLLER_DISPLAY_FORMAT_ATTR ) || '{n}';
- $display.text( format.replace( '{n}', slider.value ) );
- }
-
- function _syncCheckboxStatusText( checkbox, checked ) {
- // Mirror a checkbox's checked-state into a paired text
- // label (e.g., the "On"/"Off" caption under a toggle).
- // Labels are carried as ``data-on-text`` and
- // ``data-off-text`` on the checkbox so different
- // controller variants can use domain-specific wording
- // (e.g., "Open"/"Closed", "Locked"/"Unlocked"). The
- // status text lives in a sibling ``.status-text`` within
- // the enclosing ``.on-off-control`` container — opt-in:
- // checkboxes without the data attributes or container
- // are silently skipped so unrelated checkboxes are
- // unaffected.
- const onText = checkbox.getAttribute( 'data-on-text' );
- const offText = checkbox.getAttribute( 'data-off-text' );
- if ( ! onText || ! offText ) return;
- const $statusText = $( checkbox ).closest( '.on-off-control' )
- .find( '.status-text' );
- if ( ! $statusText.length ) return;
- $statusText.text( checked ? onText : offText );
- }
-
- function _setIfDifferent( element, prop, newValue ) {
- if ( element[ prop ] !== newValue ) {
- element[ prop ] = newValue;
- }
- }
-
- function _coerceCheckboxValue( element, value ) {
- // The truthy wire value comes from the checkbox's own
- // ``value`` attribute (server-rendered), so each domain's
- // vocabulary lives in templates rather than duplicated
- // here. Browsers default unset checkbox ``value`` to
- // ``'on'``, which is exactly what ON_OFF needs;
- // OPEN_CLOSE templates set ``value="open"``. ``true`` /
- // ``1`` remain accepted as universal truthy strings.
- if ( typeof value === 'boolean' ) return value;
- if ( typeof value === 'number' ) return value !== 0;
- if ( typeof value === 'string' ) {
- const lowered = value.toLowerCase();
- const truthy = ( element.value || 'on' ).toLowerCase();
- if ( lowered === truthy ) return true;
- return lowered === 'true' || lowered === '1';
- }
- return Boolean( value );
- }
-
- jQuery(function($) {
- // Continuous-slider preset buttons (e.g., the dimmer's
- // Off/Full). The button's ``data-value`` is written to
- // the sibling slider and ``change`` is triggered so
- // antinode's ``onchange-async`` handler submits the form
- // — identical round-trip to dragging the slider.
- $('body').on(
- 'click',
- `.${Hi.CONTROLLER_PRESET_BTN_CLASS}`,
- function() {
- const $btn = $(this);
- const $slider = $btn.closest( `.${Hi.CONTROLLER_SLIDER_CONTROL_CLASS}` )
- .find( `.${Hi.CONTROLLER_SLIDER_CLASS}` );
- $slider.val( $btn.attr( Hi.DATA_VALUE_ATTR ) ).trigger( 'change' );
- _syncSliderDisplay( $slider[ 0 ] );
- }
- );
-
- // Mirror the value into the display element as the
- // operator drags any slider that opted in. ``input``
- // fires continuously during a drag; ``change`` only
- // fires on release, which would let the displayed value
- // lag behind the thumb position.
- $('body').on(
- 'input',
- `input[type=range][${Hi.CONTROLLER_DISPLAY_TARGET_ATTR}]`,
- function() {
- _syncSliderDisplay( this );
- }
- );
-
- // Track active drag so polling-driven value updates can
- // skip sliders the operator is currently manipulating.
- // Set on pointer-down (mouse / touch / pen via Pointer
- // Events). Cleared on pointer release and on ``change``
- // (the canonical "value committed" signal — covers
- // keyboard arrow adjustments too).
- //
- // Release-side handlers live on ``document``, not ``body``:
- // a pointer release that happens off the slider element
- // (or even outside the viewport) still bubbles to document,
- // ensuring the flag clears so subsequent polls can resume
- // updating. Listening on body alone would leak the flag if
- // the user dragged the thumb past the page edge before
- // releasing.
- $('body').on(
- 'mousedown touchstart pointerdown',
- 'input[type=range]',
- function() { _activeSliders.add( this ); }
- );
- $(document).on(
- 'mouseup touchend touchcancel pointerup pointercancel change blur',
- 'input[type=range]',
- function() { _activeSliders.delete( this ); }
- );
- });
-
-})();
diff --git a/src/hi/static/js/entity_state_status.js b/src/hi/static/js/entity_state_status.js
index eafbec98..8dbdbe2b 100644
--- a/src/hi/static/js/entity_state_status.js
+++ b/src/hi/static/js/entity_state_status.js
@@ -1,15 +1,44 @@
/*
- * Home Information - Entity-state status updates
+ * Home Information — Entity-state polling-update dispatcher.
*
* Consumes the ``entityStateStatusMap`` from the polling response
- * and applies per-EntityState UI updates. Each map entry is keyed
- * by CSS class and may carry:
+ * and applies per-EntityState DOM updates. The map is keyed by the
+ * EntityState id (as a string); each entry may carry a status
+ * value, a controller value, a display projection, and an SVG
+ * style bundle.
*
- * attributes DOM attributes to set on every matching element
- * (status, stroke, fill, etc.).
- * controller Controller widget state ({value, ...}) for the
- * matching elements; absent for sensor-only states.
- * display_value Display strings for the sensor card.
+ * Element-level contract: every DOM element that wants polling
+ * updates carries ``data-state-id="<entity_state_id>"`` plus one or
+ * more declaration attributes. Each declaration is presence-only:
+ *
+ * data-status → set the element's ``status`` attr to
+ * ``entry.status`` (singular status push;
+ * CSS rules elsewhere react to it).
+ * data-controller-value → set the form value / checked / selected
+ * from ``entry.controller.value``.
+ * data-display-text → set element text to ``entry.display.text``.
+ * data-display-magnitude → set element text to ``entry.display.magnitude``.
+ * data-display-unit → set element text to ``entry.display.unit``.
+ * data-svg-style → set every attribute in ``entry.svg_style``
+ * (status, stroke, fill, stroke-width,
+ * fill-opacity, stroke-dasharray) on this
+ * element. Used by LocationView SVG icon /
+ * path elements.
+ *
+ * The dispatcher walks ``[data-state-id]`` once, looks up the
+ * entry, and applies each declaration the element opts into. No
+ * descendant traversal and no class-based join — each element is
+ * self-describing, so authors place the markers on whichever
+ * element they want updated.
+ *
+ * After the universal apply pass, registered EntityStatusPanel
+ * handlers run. Panels that need behavior beyond what the universal
+ * dispatcher handles (e.g., a thermostat dial whose SVG marker
+ * angles are computed from numeric values) register a handler via
+ * ``Hi.statePanels.registerUpdate``. The fallback flat-list rendering is
+ * itself a panel; its panel JS registers a handler for the
+ * flat-list-specific behaviors (checkbox status-text mirror, dimmer
+ * preset buttons, etc.).
*/
(function() {
'use strict';
@@ -17,69 +46,216 @@
window.Hi = window.Hi || {};
Hi.entityStateStatus = Hi.entityStateStatus || {};
+ // EntityStatusPanel JS that wants to react to polling updates
+ // beyond what CSS keyed on the ``status`` attribute can do
+ // registers an update handler via ``registerUpdate``. Update
+ // handlers receive the full statusMap keyed by state id and
+ // scope their own work using ``data-state-id`` on the elements
+ // they manage. They run after the universal apply pass on each
+ // polling tick.
+ //
+ // Panels that need a per-insertion init step (e.g., a thermostat
+ // dial that has to position SVG markers from server-rendered
+ // ``data-temp-value`` attributes before any polling tick) register
+ // an init handler via ``registerInit``. Init handlers fire at
+ // jQuery ready for the initial page render AND after every async
+ // content insertion (via antinode), so panels in dynamically-loaded
+ // modals get a chance to initialize before the first polling tick.
+ // Init handlers must be idempotent — they re-scan the whole
+ // document on each call and should be safe to invoke on already-
+ // initialized elements.
+ const panelUpdateHandlers = [];
+ const panelInitHandlers = [];
+ Hi.statePanels = Hi.statePanels || {
+ registerUpdate: function( handler ) {
+ if ( typeof handler === 'function' ) panelUpdateHandlers.push( handler );
+ },
+ registerInit: function( handler ) {
+ if ( typeof handler === 'function' ) panelInitHandlers.push( handler );
+ }
+ };
+
+ function runPanelInitHandlers() {
+ for ( const handler of panelInitHandlers ) {
+ try {
+ handler();
+ } catch ( e ) {
+ console.error( 'EntityStatusPanel init handler error:', e );
+ }
+ }
+ }
+
+ // Sliders the user is actively dragging. Polling-driven value
+ // updates skip these elements so a server refresh mid-drag
+ // doesn't yank the thumb out from under the operator's fingers.
+ const activeSliders = new WeakSet();
+
Hi.entityStateStatus.apply = function( statusMap ) {
if ( ! statusMap ) return;
- const controllerSubMap = {};
- for ( const cssClass in statusMap ) {
- const entry = statusMap[ cssClass ];
- if ( entry.attributes ) {
- _applyAttributes( cssClass, entry.attributes );
+ $( '[data-state-id]' ).each( function() {
+ const $el = $( this );
+ const entry = statusMap[ $el.attr( 'data-state-id' ) ];
+ if ( ! entry ) return;
+
+ if ( entry.status != null && this.hasAttribute( 'data-status' ) ) {
+ setAttrIfDifferent( this, 'status', entry.status );
+ }
+ if ( entry.svg_style && this.hasAttribute( 'data-svg-style' ) ) {
+ for ( const attrName in entry.svg_style ) {
+ const attrValue = entry.svg_style[ attrName ];
+ if ( attrValue == null ) continue;
+ setAttrIfDifferent( this, attrName, attrValue );
+ }
+ }
+ if ( entry.display ) {
+ if ( entry.display.text != null
+ && this.hasAttribute( 'data-display-text' ) ) {
+ setTextIfDifferent( this, entry.display.text );
+ }
+ if ( entry.display.magnitude != null
+ && this.hasAttribute( 'data-display-magnitude' ) ) {
+ setTextIfDifferent( this, String( entry.display.magnitude ) );
+ }
+ if ( entry.display.unit != null
+ && this.hasAttribute( 'data-display-unit' ) ) {
+ setTextIfDifferent( this, entry.display.unit );
+ }
}
- if ( entry.display_value ) {
- _applyDisplay( cssClass, entry.display_value );
+ if ( entry.controller
+ && this.hasAttribute( 'data-controller-value' ) ) {
+ applyControllerValue( this, entry.controller.value );
}
- if ( entry.controller ) {
- controllerSubMap[ cssClass ] = entry.controller;
+ });
+
+ for ( const handler of panelUpdateHandlers ) {
+ try {
+ handler( statusMap );
+ } catch ( e ) {
+ console.error( 'EntityStatusPanel handler error:', e );
}
}
- Hi.controllers.applyValueMap( controllerSubMap );
};
- function _applyAttributes( cssClass, attrMap ) {
- // When a matched element does not carry the named
- // attribute directly, the ``status`` attribute is
- // forwarded to descendent ``div[status]`` elements so CSS
- // selectors keyed on ``[status="..."]`` match through the
- // wrapper. Other attribute names are silently ignored on
- // that element.
- const elements = $( '.' + cssClass );
- for ( const attrName in attrMap ) {
- const attrValue = attrMap[ attrName ];
- elements.each( function() {
- if ( this.hasAttribute( attrName ) ) {
- const currentValue = $( this ).attr( attrName );
- if ( attrValue != null && ( currentValue !== String( attrValue ) ) ) {
- $( this ).attr( attrName, attrValue );
- }
- } else if ( attrName == 'status' ) {
- $( this ).find( 'div[status]' ).attr( attrName, attrValue );
- }
- });
+ function setAttrIfDifferent( element, attrName, attrValue ) {
+ const newValue = String( attrValue );
+ if ( element.getAttribute( attrName ) !== newValue ) {
+ element.setAttribute( attrName, newValue );
}
}
- function _applyDisplay( cssClass, displayValue ) {
- // Templates opt in to display refresh by tagging the
- // target element with one of ``display-text``,
- // ``display-magnitude``, ``display-unit``. The attribute
- // is presence-only; the polled ``display_value`` field of
- // the same name supplies the text. Fields absent on the
- // server side (e.g., ``magnitude`` for unit-less states)
- // leave the target element's existing text untouched.
- const $scope = $( '.' + cssClass );
- _setTextWhereAttr( $scope, 'display-text', displayValue.text );
- _setTextWhereAttr( $scope, 'display-magnitude', displayValue.magnitude );
- _setTextWhereAttr( $scope, 'display-unit', displayValue.unit_symbol );
+ function setTextIfDifferent( element, text ) {
+ if ( element.textContent !== text ) {
+ element.textContent = text;
+ }
}
- function _setTextWhereAttr( $scope, attrName, text ) {
- if ( text == null ) return;
- const selector = '[' + attrName + ']';
- $scope.find( selector ).addBack( selector ).each( function() {
- if ( $( this ).text() !== text ) {
- $( this ).text( text );
+ function applyControllerValue( element, value ) {
+ const tag = element.tagName;
+ if ( tag === 'INPUT' ) {
+ const type = element.type;
+ if ( type === 'range' || type === 'number' || type === 'text' ) {
+ if ( type === 'range' && activeSliders.has( element ) ) return;
+ setPropIfDifferent( element, 'value', String( value ) );
+ syncSliderDisplay( element );
+ return;
}
- });
+ if ( type === 'checkbox' ) {
+ const checked = coerceCheckboxValue( element, value );
+ if ( element.checked !== checked ) element.checked = checked;
+ return;
+ }
+ }
+ if ( tag === 'SELECT' ) {
+ setPropIfDifferent( element, 'value', String( value ) );
+ return;
+ }
+ // Other shapes (color picker, etc.) get their own branches
+ // here as widgets are added.
+ }
+
+ function setPropIfDifferent( element, prop, newValue ) {
+ if ( element[ prop ] !== newValue ) element[ prop ] = newValue;
}
+ function coerceCheckboxValue( element, value ) {
+ // The truthy wire value comes from the checkbox's own
+ // ``value`` attribute (server-rendered), so each domain's
+ // vocabulary lives in templates rather than duplicated here.
+ // Browsers default unset checkbox ``value`` to ``'on'``,
+ // which is exactly what ON_OFF needs; OPEN_CLOSE templates
+ // set ``value="open"``. ``true`` / ``1`` are accepted as
+ // universal truthy strings.
+ if ( typeof value === 'boolean' ) return value;
+ if ( typeof value === 'number' ) return value !== 0;
+ if ( typeof value === 'string' ) {
+ const lowered = value.toLowerCase();
+ const truthy = ( element.value || 'on' ).toLowerCase();
+ if ( lowered === truthy ) return true;
+ return lowered === 'true' || lowered === '1';
+ }
+ return Boolean( value );
+ }
+
+ function syncSliderDisplay( slider ) {
+ // Mirror a slider's current value into a paired display
+ // element. Sliders opt in by declaring two data attributes
+ // on the ``<input type=range>``:
+ // Hi.CONTROLLER_DISPLAY_TARGET_ATTR CSS selector for the
+ // display element, looked up within the enclosing
+ // form.
+ // Hi.CONTROLLER_DISPLAY_FORMAT_ATTR Format string with
+ // ``{n}`` as the value placeholder, e.g. ``{n}%``,
+ // ``{n}°``. Optional; defaults to ``{n}``.
+ const selector = slider.getAttribute( Hi.CONTROLLER_DISPLAY_TARGET_ATTR );
+ if ( ! selector ) return;
+ const $display = $( slider ).closest( 'form' ).find( selector );
+ if ( ! $display.length ) return;
+ const format = slider.getAttribute( Hi.CONTROLLER_DISPLAY_FORMAT_ATTR ) || '{n}';
+ $display.text( format.replace( '{n}', slider.value ) );
+ }
+
+ jQuery(function($) {
+ // Slider drag mirror — keep the paired display in lock-step
+ // with the thumb during user drag. ``input`` fires
+ // continuously; ``change`` only fires on release, which
+ // would let the displayed value lag behind the thumb.
+ $( 'body' ).on(
+ 'input',
+ `input[type=range][${Hi.CONTROLLER_DISPLAY_TARGET_ATTR}]`,
+ function() { syncSliderDisplay( this ); }
+ );
+
+ // Track active drag so polling-driven value updates can
+ // skip sliders the operator is currently manipulating.
+ // Release-side handlers live on ``document`` so a pointer
+ // release outside the viewport still bubbles and clears
+ // the flag — listening on body alone would leak the flag
+ // if the user dragged the thumb past the page edge.
+ $( 'body' ).on(
+ 'mousedown touchstart pointerdown',
+ 'input[type=range]',
+ function() { activeSliders.add( this ); }
+ );
+ $( document ).on(
+ 'mouseup touchend touchcancel pointerup pointercancel change blur',
+ 'input[type=range]',
+ function() { activeSliders.delete( this ); }
+ );
+
+ // Initial pass for the first page render. Async-loaded
+ // fragments piggyback on antinode's afterAsyncRender hook
+ // (for HTML and set-attribute responses) and its dedicated
+ // afterModalRender hook (for JSON-delivered modals, which
+ // are inserted after afterAsyncRender fires).
+ runPanelInitHandlers();
+ if ( window.AN ) {
+ if ( typeof window.AN.addAfterAsyncRenderFunction === 'function' ) {
+ window.AN.addAfterAsyncRenderFunction( runPanelInitHandlers );
+ }
+ if ( typeof window.AN.addAfterModalRenderFunction === 'function' ) {
+ window.AN.addAfterModalRenderFunction( runPanelInitHandlers );
+ }
+ }
+ });
+
})();
diff --git a/src/hi/static/js/video-timeline.js b/src/hi/static/js/video-timeline.js
index 11a82639..ec18204f 100644
--- a/src/hi/static/js/video-timeline.js
+++ b/src/hi/static/js/video-timeline.js
@@ -4,111 +4,105 @@
(function() {
'use strict';
-
- // Video Connection Management
+
+ const TRANSPARENT_GIF_SRC =
+ 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
+
+ // Tracks every long-lived video connection currently attached to
+ // the document. An <img> opts in by carrying ``data-video-stream``;
+ // both live MJPEG streams and event-video playback elements need
+ // this because surveillance users typically browse between events
+ // faster than playback completes, leaving recorded-video fetches
+ // holding browser per-host connection slots if not closed.
+ //
+ // Responsibilities split with antinode:
+ // - Antinode fires ``beforeAsyncRender($target)`` immediately
+ // before replacing a subtree. We register a callback that
+ // force-closes any tracked streams within the outgoing
+ // subtree by swapping ``src`` to a 1x1 transparent GIF. This
+ // terminates the fetch before the browser orphans the
+ // element.
+ // - On each ``afterAsyncRender`` / ``afterModalRender``, we
+ // reconcile: drop entries for elements no longer in the DOM,
+ // register any newly-attached marked elements.
+ // - On page unload we force-close everything.
const VideoConnectionManager = {
- currentVideo: null,
- previousVideos: [],
- maxCachedVideos: 3, // Keep a few previous videos cached for back navigation
-
- registerVideo: function(videoElement) {
- if (!videoElement) return;
-
- // Clean up old videos before registering new one
- this.cleanupOldVideos();
-
- // Store reference to current video
- this.currentVideo = videoElement;
-
- // Add error handling and load event listeners
- videoElement.addEventListener('error', this.handleVideoError.bind(this));
- videoElement.addEventListener('loadstart', this.handleVideoLoadStart.bind(this));
- },
-
- cleanupOldVideos: function() {
- // If we have a current video, move it to the previous videos cache
- if (this.currentVideo && this.currentVideo.src) {
- this.previousVideos.unshift(this.currentVideo);
-
- // Keep only the most recent N videos cached
- if (this.previousVideos.length > this.maxCachedVideos) {
- const videosToCleanup = this.previousVideos.splice(this.maxCachedVideos);
- videosToCleanup.forEach(video => this.forceCloseVideo(video));
- }
- }
+
+ streams: new Set(),
+
+ register: function( element ) {
+ if ( ! element ) return;
+ if ( ! element.src || element.src.startsWith('data:') ) return;
+ if ( this.streams.has( element )) return;
+ this.streams.add( element );
+ element.addEventListener( 'error', () => this._handleError( element ));
},
-
- forceCloseVideo: function(videoElement) {
- if (!videoElement || !videoElement.src) return;
-
+
+ forceClose: function( element ) {
+ if ( ! element ) return;
try {
- // Create a 1x1 pixel transparent GIF data URL to replace the stream
- const transparentGif = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
-
- // Replace the streaming URL with the data URL to close the connection
- videoElement.src = transparentGif;
-
- // Also set srcset if present
- if (videoElement.srcset) {
- videoElement.srcset = '';
+ if ( element.src && ! element.src.startsWith('data:') ) {
+ element.src = TRANSPARENT_GIF_SRC;
+ }
+ if ( element.srcset ) {
+ element.srcset = '';
}
-
- console.debug('Video connection closed:', videoElement.getAttribute('data-event-id') || 'unknown');
- } catch (e) {
- console.warn('Error closing video connection:', e);
+ } catch ( e ) {
+ console.warn( 'Error closing stream:', e );
}
+ this.streams.delete( element );
},
-
- handleVideoError: function(event) {
- const video = event.target;
- console.warn('Video error for event:', video.getAttribute('data-event-id'), event);
-
- // If we've hit connection limits, try to free up connections
- if (this.previousVideos.length > 0) {
- console.info('Video error detected, cleaning up old connections...');
- const oldVideo = this.previousVideos.pop();
- this.forceCloseVideo(oldVideo);
-
- // Try to reload the current video after a brief delay
- setTimeout(() => {
- if (video.src && !video.src.startsWith('data:')) {
- video.load();
- }
- }, 500);
- }
+
+ // Walk the outgoing subtree and force-close every marked
+ // element within it. Called by antinode's beforeAsyncRender
+ // hook before content is replaced.
+ closeWithin: function( $scope ) {
+ if ( ! $scope || ! $scope.find ) return;
+ const manager = this;
+ $scope.find( 'img[data-video-stream]' ).each(function() {
+ manager.forceClose( this );
+ });
},
-
- handleVideoLoadStart: function(event) {
- const video = event.target;
- console.debug('Video loading started for event:', video.getAttribute('data-event-id'));
+
+ // Re-derive the tracked set from the live DOM. Drops removed
+ // elements, registers newly-attached ones.
+ reconcile: function() {
+ for ( const element of Array.from( this.streams )) {
+ if ( ! document.contains( element )) {
+ this.streams.delete( element );
+ }
+ }
+ document.querySelectorAll( 'img[data-video-stream]' ).forEach(
+ (el) => this.register( el )
+ );
},
-
- // Force cleanup all connections (for page unload)
+
cleanup: function() {
- if (this.currentVideo) {
- this.forceCloseVideo(this.currentVideo);
+ for ( const element of Array.from( this.streams )) {
+ this.forceClose( element );
}
- this.previousVideos.forEach(video => this.forceCloseVideo(video));
- this.previousVideos = [];
- this.currentVideo = null;
+ },
+
+ _handleError: function( element ) {
+ console.warn( 'Video stream error:', element.src );
}
};
-
+
// Video Timeline Scrollbar Management
const VideoTimelineScrollManager = {
init: function() {
this.timeline = document.getElementById('event-timeline');
if (!this.timeline) return;
-
+
// Handle initial page loads - scroll to active item if needed
this.handleInitialLoad();
-
+
},
-
+
handleInitialLoad: function() {
const activeItem = this.timeline.querySelector('.timeline-item.active');
if (!activeItem) return;
-
+
// Check if coming from live stream
const fromLive = sessionStorage.getItem('navigatingFromLiveStream');
if (fromLive) {
@@ -121,29 +115,29 @@
setTimeout(() => this.scrollToItem(activeItem, 'initial'), 50);
}
},
-
-
+
+
scrollToItem: function(item, context) {
if (!item) return;
-
+
const timeline = this.timeline;
const timelineRect = timeline.getBoundingClientRect();
const itemRect = item.getBoundingClientRect();
-
+
const isVisible = (
itemRect.top >= timelineRect.top &&
itemRect.bottom <= timelineRect.bottom
);
-
+
if (context === 'initial') {
// For initial page loads, center the item (unless already visible)
if (!isVisible) {
const itemTop = item.offsetTop;
const timelineHeight = timeline.clientHeight;
const itemHeight = item.clientHeight;
-
+
const targetScroll = itemTop - (timelineHeight / 2) + (itemHeight / 2);
-
+
timeline.scrollTo({
top: Math.max(0, targetScroll),
behavior: 'auto'
@@ -162,9 +156,9 @@
const itemHeight = item.clientHeight;
const timelineHeight = timeline.clientHeight;
const margin = 20; // Small margin from edge
-
+
let targetScroll;
-
+
if (itemRect.top < timelineRect.top) {
// Item is above visible area - scroll up to show it near top
targetScroll = itemTop - margin;
@@ -172,7 +166,7 @@
// Item is below visible area - scroll down to show it near bottom
targetScroll = itemTop - timelineHeight + itemHeight + margin;
}
-
+
timeline.scrollTo({
top: Math.max(0, targetScroll),
behavior: 'smooth'
@@ -180,67 +174,80 @@
}
}
},
-
+
handleAsyncUpdate: function() {
- // Register the new video element with connection manager
- this.registerCurrentVideo();
+ // Tag the current video element with its event id for
+ // debug visibility in console logs / DOM inspection. The
+ // connection manager handles registration itself via the
+ // ``data-video-stream`` marker.
+ this.tagCurrentVideoWithEventId();
},
-
- registerCurrentVideo: function() {
- // Find the main video element in the video detail container
+
+ tagCurrentVideoWithEventId: function() {
const videoElement = document.querySelector('.video-container img');
if (videoElement && videoElement.src && !videoElement.src.startsWith('data:')) {
- // Set event ID for debugging if available
const eventId = this.extractEventIdFromUrl(videoElement.src);
if (eventId) {
videoElement.setAttribute('data-event-id', eventId);
}
-
- VideoConnectionManager.registerVideo(videoElement);
}
},
-
+
extractEventIdFromUrl: function(url) {
// Extract event ID from ZoneMinder URL pattern: ...&event=12345
const match = url.match(/[&?]event=(\d+)/);
return match ? match[1] : null;
}
};
-
+
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
VideoTimelineScrollManager.init();
- VideoTimelineScrollManager.registerCurrentVideo();
+ VideoTimelineScrollManager.tagCurrentVideoWithEventId();
+ VideoConnectionManager.reconcile();
});
} else {
VideoTimelineScrollManager.init();
- VideoTimelineScrollManager.registerCurrentVideo();
+ VideoTimelineScrollManager.tagCurrentVideoWithEventId();
+ VideoConnectionManager.reconcile();
}
-
- // Hook into antinode.js updates
- if (typeof addAfterAsyncRenderFunction === 'function') {
- addAfterAsyncRenderFunction(() => VideoTimelineScrollManager.handleAsyncUpdate());
- } else {
- const original = window.handlePostAsyncUpdate;
- window.handlePostAsyncUpdate = function() {
- if (original) original();
- VideoTimelineScrollManager.handleAsyncUpdate();
- };
+
+ // Hook into antinode lifecycle. ``beforeContentRemoval`` runs
+ // before any subtree is detached — HTML content swap or modal
+ // dismissal — with the outgoing subtree. That's where we close
+ // stream connections cleanly. ``afterAsyncRender`` and
+ // ``afterModalRender`` run after content is in the DOM — that's
+ // where we reconcile our tracked set against the new state.
+ function registerHook( hookName, fn ) {
+ if ( typeof window.AN === 'object'
+ && typeof window.AN[ hookName ] === 'function' ) {
+ window.AN[ hookName ]( fn );
+ }
}
-
+ registerHook( 'addBeforeContentRemovalFunction', ($subtree) => {
+ VideoConnectionManager.closeWithin( $subtree );
+ });
+ registerHook( 'addAfterAsyncRenderFunction', () => {
+ VideoTimelineScrollManager.handleAsyncUpdate();
+ VideoConnectionManager.reconcile();
+ });
+ registerHook( 'addAfterModalRenderFunction', () => {
+ VideoConnectionManager.reconcile();
+ });
+
// Cleanup on page unload to free connections
window.addEventListener('beforeunload', () => {
VideoConnectionManager.cleanup();
});
-
+
// Also cleanup on navigation away from video pages
window.addEventListener('pagehide', () => {
VideoConnectionManager.cleanup();
});
-
-
+
+
// Expose for potential external use and debugging
window.VideoTimelineScrollManager = VideoTimelineScrollManager;
window.VideoConnectionManager = VideoConnectionManager;
-})();
\ No newline at end of file
+})();
diff --git a/src/hi/static/state_panels/camera/camera.css b/src/hi/static/state_panels/camera/camera.css
new file mode 100644
index 00000000..29194d3b
--- /dev/null
+++ b/src/hi/static/state_panels/camera/camera.css
@@ -0,0 +1,102 @@
+/* EntityStatusPanel for CAMERA entities.
+ *
+ * All rules nested under .hi-state-panel-camera. The panel composes
+ * existing video-stream and state-status partials; this CSS supplies
+ * the per-context layout (modal / list / grid) around them.
+ */
+
+:root {
+ --hi-camera-offline-color: #6b7280;
+ --hi-camera-offline-bg: #2c2c2c;
+}
+
+.hi-state-panel-camera .stream {
+ position: relative;
+ overflow: hidden;
+ background: #1a1a1a;
+}
+
+.hi-state-panel-camera .stream-unavailable {
+ background: var(--hi-camera-offline-bg);
+ color: var(--hi-camera-offline-color);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ font-size: 11px;
+ font-weight: 600;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ height: 100%;
+ min-height: 60px;
+}
+
+/* The existing entity_video_stream wrapper renders an anchor + img. */
+.hi-state-panel-camera .stream a {
+ display: block;
+ text-decoration: none;
+}
+.hi-state-panel-camera .stream .video-container img,
+.hi-state-panel-camera .stream img.img-fluid {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+
+/* ============================================================== */
+/* Modal layout */
+/* ============================================================== */
+
+.hi-state-panel-camera--modal .stream {
+ aspect-ratio: 16 / 9;
+ margin-bottom: 16px;
+}
+
+/* ============================================================== */
+/* List card layout */
+/* ============================================================== */
+
+.hi-state-panel-camera--list {
+ display: grid;
+ grid-template-columns: 160px 1fr;
+ gap: 12px;
+ align-items: center;
+}
+.hi-state-panel-camera--list .stream {
+ width: 160px;
+ aspect-ratio: 16 / 9;
+}
+.hi-state-panel-camera--list .list-meta { min-width: 0; }
+.hi-state-panel-camera--list .entity-name {
+ font-size: 13px; font-weight: 600; line-height: 1.2;
+}
+
+/* ============================================================== */
+/* Grid card layout — video fills, name overlay along the bottom. */
+/* ============================================================== */
+
+.hi-state-panel-camera--grid {
+ position: relative;
+ width: 100%;
+ height: 100%;
+}
+.hi-state-panel-camera--grid .stream {
+ width: 100%;
+ height: 100%;
+}
+.hi-state-panel-camera--grid .grid-overlay {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ padding: 8px 8px 6px;
+ background: linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.75) 100%);
+ color: white;
+}
+.hi-state-panel-camera--grid .entity-name {
+ font-size: 11px;
+ font-weight: 600;
+ line-height: 1.2;
+ text-shadow: 0 0 4px rgba(0,0,0,0.6);
+}
diff --git a/src/hi/static/state_panels/fallback/fallback.js b/src/hi/static/state_panels/fallback/fallback.js
new file mode 100644
index 00000000..da9f91e3
--- /dev/null
+++ b/src/hi/static/state_panels/fallback/fallback.js
@@ -0,0 +1,66 @@
+/*
+ * Fallback EntityStatusPanel — client-side behaviors specific to
+ * the flat-list rendering used when no per-EntityType panel is
+ * registered.
+ *
+ * Registered like any other panel JS. Adds two behaviors the
+ * legacy flat-list controller templates depend on:
+ *
+ * 1. Checkbox status-text mirror. The flat-list on-off / open-close
+ * controller templates wrap a checkbox in a ``.on-off-control``
+ * container with a sibling ``.status-text`` caption. When the
+ * checkbox's checked state changes via polling, the caption
+ * mirror updates the text from the checkbox's
+ * ``data-on-text`` / ``data-off-text`` attributes. Opt-in
+ * via those attributes and the ``.on-off-control`` /
+ * ``.status-text`` container/sibling pair.
+ *
+ * 2. Continuous-slider preset buttons (e.g., the dimmer's Off /
+ * Full convenience buttons). The button's ``data-value`` is
+ * written into the sibling slider and ``change`` is fired so
+ * antinode's ``onchange-async`` handler submits the form —
+ * identical round-trip to the user dragging the slider.
+ */
+(function() {
+ 'use strict';
+
+ function syncCheckboxStatusText( checkbox ) {
+ const onText = checkbox.getAttribute( 'data-on-text' );
+ const offText = checkbox.getAttribute( 'data-off-text' );
+ if ( ! onText || ! offText ) return;
+ const $statusText = $( checkbox ).closest( '.on-off-control' )
+ .find( '.status-text' );
+ if ( ! $statusText.length ) return;
+ $statusText.text( checkbox.checked ? onText : offText );
+ }
+
+ // Registers with the framework's post-apply hook so the caption
+ // mirror runs after the universal dispatcher has already updated
+ // each checkbox's ``.checked`` state.
+ if ( window.Hi && Hi.statePanels && typeof Hi.statePanels.registerUpdate === 'function' ) {
+ Hi.statePanels.registerUpdate( function( statusMap ) {
+ for ( const stateId in statusMap ) {
+ $( `[data-state-id="${stateId}"][type="checkbox"]` ).each( function() {
+ syncCheckboxStatusText( this );
+ });
+ }
+ });
+ }
+
+ jQuery( function( $ ) {
+ // Continuous-slider preset buttons — write the
+ // ``data-value`` into the sibling slider and fire change
+ // for the antinode form submission.
+ $( 'body' ).on(
+ 'click',
+ `.${Hi.CONTROLLER_PRESET_BTN_CLASS}`,
+ function() {
+ const $btn = $( this );
+ const $slider = $btn.closest( `.${Hi.CONTROLLER_SLIDER_CONTROL_CLASS}` )
+ .find( `.${Hi.CONTROLLER_SLIDER_CLASS}` );
+ $slider.val( $btn.attr( Hi.DATA_VALUE_ATTR ) ).trigger( 'change' );
+ }
+ );
+ });
+
+})();
diff --git a/src/hi/static/state_panels/smoke_detector/smoke_detector.css b/src/hi/static/state_panels/smoke_detector/smoke_detector.css
new file mode 100644
index 00000000..b2cb68eb
--- /dev/null
+++ b/src/hi/static/state_panels/smoke_detector/smoke_detector.css
@@ -0,0 +1,185 @@
+/* EntityStatusPanel for SMOKE_DETECTOR entities.
+ *
+ * All rules nested under .hi-state-panel-smoke_detector so the short
+ * scoped class names (.icon, .label, .badge, .hero, .aux-item, etc.)
+ * don't leak. Variant switching is CSS-only and driven by the
+ * ``status`` attribute on the panel root. Two status vocabularies
+ * land on the root over a panel's lifetime: the raw sensor value
+ * (smoke_clear / smoke_detected) on initial server render, and the
+ * decay-aware value (idle / active / recent / past) once the first
+ * polling refresh lands. CSS handles both so the panel reads
+ * correctly at any moment.
+ */
+
+:root {
+ --hi-smoke-clear-color: #059669;
+ --hi-smoke-clear-bg: rgba(5, 150, 105, 0.10);
+ --hi-smoke-alarm-color: #dc2626;
+ --hi-smoke-alarm-bg: rgba(220, 38, 38, 0.15);
+ --hi-smoke-recent-color: #d97706;
+ --hi-smoke-recent-bg: rgba(217, 119, 6, 0.12);
+ --hi-smoke-past-color: #ca8a04;
+ --hi-smoke-past-bg: rgba(202, 138, 4, 0.10);
+}
+
+/* ============================================================== */
+/* Variant visibility: which icon and label show per status value. */
+/* ============================================================== */
+
+.hi-state-panel-smoke_detector .icon,
+.hi-state-panel-smoke_detector .status-label {
+ display: none;
+}
+
+.hi-state-panel-smoke_detector[status="smoke_clear"] .icon--clear,
+.hi-state-panel-smoke_detector[status="idle"] .icon--clear,
+.hi-state-panel-smoke_detector[status="smoke_clear"] .status-label--clear,
+.hi-state-panel-smoke_detector[status="idle"] .status-label--clear {
+ display: inline-block;
+}
+
+.hi-state-panel-smoke_detector[status="smoke_detected"] .icon--alarm,
+.hi-state-panel-smoke_detector[status="active"] .icon--alarm,
+.hi-state-panel-smoke_detector[status="smoke_detected"] .status-label--alarm,
+.hi-state-panel-smoke_detector[status="active"] .status-label--alarm {
+ display: inline-block;
+}
+
+.hi-state-panel-smoke_detector[status="recent"] .icon--recent,
+.hi-state-panel-smoke_detector[status="recent"] .status-label--clear {
+ display: inline-block;
+}
+
+.hi-state-panel-smoke_detector[status="past"] .icon--past,
+.hi-state-panel-smoke_detector[status="past"] .status-label--clear {
+ display: inline-block;
+}
+
+/* ============================================================== */
+/* Color tints — applied to badge background per status. */
+/* ============================================================== */
+
+.hi-state-panel-smoke_detector .badge {
+ background: var(--hi-smoke-clear-bg);
+ color: var(--hi-smoke-clear-color);
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+}
+
+.hi-state-panel-smoke_detector[status="smoke_detected"] .badge,
+.hi-state-panel-smoke_detector[status="active"] .badge {
+ background: var(--hi-smoke-alarm-bg);
+ color: var(--hi-smoke-alarm-color);
+}
+.hi-state-panel-smoke_detector[status="recent"] .badge {
+ background: var(--hi-smoke-recent-bg);
+ color: var(--hi-smoke-recent-color);
+}
+.hi-state-panel-smoke_detector[status="past"] .badge {
+ background: var(--hi-smoke-past-bg);
+ color: var(--hi-smoke-past-color);
+}
+
+.hi-state-panel-smoke_detector .icon {
+ width: 60%;
+ height: 60%;
+}
+
+/* Status label color follows visual treatment. */
+.hi-state-panel-smoke_detector .status-label { font-weight: 600; }
+.hi-state-panel-smoke_detector[status="smoke_clear"] .status-label,
+.hi-state-panel-smoke_detector[status="idle"] .status-label { color: var(--hi-smoke-clear-color); }
+.hi-state-panel-smoke_detector[status="smoke_detected"] .status-label,
+.hi-state-panel-smoke_detector[status="active"] .status-label { color: var(--hi-smoke-alarm-color); }
+.hi-state-panel-smoke_detector[status="recent"] .status-label { color: var(--hi-smoke-recent-color); }
+.hi-state-panel-smoke_detector[status="past"] .status-label { color: var(--hi-smoke-past-color); }
+
+/* ============================================================== */
+/* Modal layout */
+/* ============================================================== */
+
+.hi-state-panel-smoke_detector--modal .hero {
+ padding: 24px 20px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 10px;
+ text-align: center;
+}
+.hi-state-panel-smoke_detector--modal .badge { width: 120px; height: 120px; }
+.hi-state-panel-smoke_detector--modal .status-label {
+ font-size: 22px;
+ line-height: 1.1;
+}
+
+.hi-state-panel-smoke_detector--modal .auxiliary {
+ border-top: 1px solid var(--line-color, #d0d7de);
+ padding: 14px 20px;
+ display: flex;
+ justify-content: space-around;
+}
+.hi-state-panel-smoke_detector--modal .aux-item {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 2px;
+}
+.hi-state-panel-smoke_detector--modal .aux-label {
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--text-muted, #6c757d);
+ font-weight: 600;
+}
+.hi-state-panel-smoke_detector--modal .aux-value { font-size: 14px; font-weight: 500; }
+
+/* ============================================================== */
+/* List card layout */
+/* ============================================================== */
+
+.hi-state-panel-smoke_detector--list {
+ display: grid;
+ grid-template-columns: 60px 1fr auto;
+ gap: 12px;
+ align-items: center;
+ padding: 4px;
+}
+.hi-state-panel-smoke_detector--list .badge { width: 60px; height: 60px; }
+.hi-state-panel-smoke_detector--list .list-meta { min-width: 0; }
+.hi-state-panel-smoke_detector--list .entity-name {
+ font-size: 14px; font-weight: 600; line-height: 1.2;
+}
+.hi-state-panel-smoke_detector--list .status-line { font-size: 12px; }
+.hi-state-panel-smoke_detector--list .status-label { font-size: 12px; }
+.hi-state-panel-smoke_detector--list .aux-bits {
+ font-size: 11px;
+ color: var(--text-muted, #6c757d);
+}
+
+/* ============================================================== */
+/* Grid card layout */
+/* ============================================================== */
+
+.hi-state-panel-smoke_detector--grid {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ text-align: center;
+ padding: 8px;
+ gap: 6px;
+}
+.hi-state-panel-smoke_detector--grid .badge { width: 64px; height: 64px; margin-top: 4px; }
+.hi-state-panel-smoke_detector--grid .status-label { font-size: 13px; line-height: 1.1; }
+.hi-state-panel-smoke_detector--grid .entity-name {
+ font-size: 11px;
+ color: var(--text-muted, #6c757d);
+ line-height: 1.2;
+}
+
+.hi-state-panel-smoke_detector--grid[status="smoke_detected"],
+.hi-state-panel-smoke_detector--grid[status="active"] { background: var(--hi-smoke-alarm-bg); }
+.hi-state-panel-smoke_detector--grid[status="recent"] { background: var(--hi-smoke-recent-bg); }
+.hi-state-panel-smoke_detector--grid[status="past"] { background: var(--hi-smoke-past-bg); }
diff --git a/src/hi/static/state_panels/thermostat/thermostat.css b/src/hi/static/state_panels/thermostat/thermostat.css
new file mode 100644
index 00000000..6907090d
--- /dev/null
+++ b/src/hi/static/state_panels/thermostat/thermostat.css
@@ -0,0 +1,162 @@
+/* EntityStatusPanel for THERMOSTAT entities.
+ *
+ * All rules nested under .hi-state-panel-thermostat. The dial's
+ * SVG markers (setpoint, current temperature) are positioned by
+ * thermostat.js because their angle depends on the numeric
+ * magnitude of the temperature values — CSS can't compute that.
+ * Color tint and the HVAC-action text label are CSS-driven from
+ * the ``status`` attribute the polling system maintains on the
+ * panel root (which carries the HVAC_ACTION state's CSS class).
+ */
+
+:root {
+ --hi-thermo-idle-color: #6c757d;
+ --hi-thermo-heating-color: #d9430d;
+ --hi-thermo-heating-bg: rgba(244, 95, 54, 0.10);
+ --hi-thermo-cooling-color: #1a73c2;
+ --hi-thermo-cooling-bg: rgba(45, 130, 220, 0.10);
+}
+
+/* ============================================================== */
+/* Dial — shared across modal and list contexts. */
+/* ============================================================== */
+
+.hi-state-panel-thermostat .dial {
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 50%;
+ background: rgba(0, 0, 0, 0.03);
+ transition: background-color 0.4s ease;
+ flex-shrink: 0;
+}
+.hi-state-panel-thermostat[status="heating"] .dial { background: var(--hi-thermo-heating-bg); }
+.hi-state-panel-thermostat[status="cooling"] .dial { background: var(--hi-thermo-cooling-bg); }
+
+.hi-state-panel-thermostat .dial-svg {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+}
+.hi-state-panel-thermostat .dial-track {
+ stroke: rgba(0, 0, 0, 0.10);
+}
+
+.hi-state-panel-thermostat .dial-setpoint-marker line {
+ stroke: var(--hi-thermo-idle-color);
+}
+.hi-state-panel-thermostat[status="heating"] .dial-setpoint-marker line { stroke: var(--hi-thermo-heating-color); }
+.hi-state-panel-thermostat[status="cooling"] .dial-setpoint-marker line { stroke: var(--hi-thermo-cooling-color); }
+
+.hi-state-panel-thermostat .dial-current-marker circle {
+ fill: var(--hi-thermo-idle-color);
+}
+.hi-state-panel-thermostat[status="heating"] .dial-current-marker circle { fill: var(--hi-thermo-heating-color); }
+.hi-state-panel-thermostat[status="cooling"] .dial-current-marker circle { fill: var(--hi-thermo-cooling-color); }
+
+.hi-state-panel-thermostat .dial-center {
+ text-align: center;
+ z-index: 1;
+}
+.hi-state-panel-thermostat .dial-temp {
+ font-weight: 300;
+ line-height: 1;
+ display: block;
+ color: #1f2328;
+}
+
+/* HVAC-action label: only the variant matching the current status renders. */
+.hi-state-panel-thermostat .dial-mode-label { display: none; }
+.hi-state-panel-thermostat[status="idle"] .dial-mode-label[for-status="idle"],
+.hi-state-panel-thermostat[status="heating"] .dial-mode-label[for-status="heating"],
+.hi-state-panel-thermostat[status="cooling"] .dial-mode-label[for-status="cooling"],
+.hi-state-panel-thermostat[status="off"] .dial-mode-label[for-status="off"] {
+ display: inline;
+ font-size: 12px;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ font-weight: 600;
+}
+.hi-state-panel-thermostat[status="idle"] .dial-mode-label { color: var(--hi-thermo-idle-color); }
+.hi-state-panel-thermostat[status="heating"] .dial-mode-label { color: var(--hi-thermo-heating-color); }
+.hi-state-panel-thermostat[status="cooling"] .dial-mode-label { color: var(--hi-thermo-cooling-color); }
+.hi-state-panel-thermostat[status="off"] .dial-mode-label { color: var(--hi-thermo-idle-color); }
+
+/* ============================================================== */
+/* Modal layout */
+/* ============================================================== */
+
+.hi-state-panel-thermostat--modal {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+}
+.hi-state-panel-thermostat--modal .dial {
+ width: 220px;
+ height: 220px;
+ margin-bottom: 16px;
+}
+.hi-state-panel-thermostat--modal .dial-temp { font-size: 56px; }
+.hi-state-panel-thermostat--modal .dial-mode-label { margin-top: 6px; }
+.hi-state-panel-thermostat--modal .states {
+ width: 100%;
+}
+
+/* ============================================================== */
+/* List card layout */
+/* ============================================================== */
+
+.hi-state-panel-thermostat--list {
+ display: grid;
+ grid-template-columns: 96px 1fr;
+ gap: 14px;
+ align-items: center;
+}
+.hi-state-panel-thermostat--list .dial {
+ width: 96px;
+ height: 96px;
+}
+.hi-state-panel-thermostat--list .dial-temp { font-size: 26px; }
+.hi-state-panel-thermostat--list .entity-name {
+ font-size: 14px; font-weight: 600; line-height: 1.2;
+}
+.hi-state-panel-thermostat--list .setpoint-summary {
+ font-size: 12px; color: var(--text-muted, #6c757d); margin-top: 2px;
+}
+
+/* ============================================================== */
+/* Grid card layout — flat number, color-tinted background. */
+/* ============================================================== */
+
+.hi-state-panel-thermostat--grid {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ padding: 8px;
+ height: 100%;
+}
+.hi-state-panel-thermostat--grid[status="heating"] { background: var(--hi-thermo-heating-bg); }
+.hi-state-panel-thermostat--grid[status="cooling"] { background: var(--hi-thermo-cooling-bg); }
+.hi-state-panel-thermostat--grid .grid-temp {
+ font-size: 44px;
+ font-weight: 300;
+ line-height: 1;
+}
+.hi-state-panel-thermostat--grid .entity-name {
+ font-size: 11px; color: var(--text-muted, #6c757d);
+ margin-top: 6px; line-height: 1.2;
+}
+.hi-state-panel-thermostat--grid .setpoint-line {
+ font-size: 9px;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--text-muted, #6c757d);
+ margin-top: 3px;
+ font-weight: 600;
+}
+.hi-state-panel-thermostat--grid[status="heating"] .setpoint-line { color: var(--hi-thermo-heating-color); }
+.hi-state-panel-thermostat--grid[status="cooling"] .setpoint-line { color: var(--hi-thermo-cooling-color); }
diff --git a/src/hi/static/state_panels/thermostat/thermostat.js b/src/hi/static/state_panels/thermostat/thermostat.js
new file mode 100644
index 00000000..70764466
--- /dev/null
+++ b/src/hi/static/state_panels/thermostat/thermostat.js
@@ -0,0 +1,94 @@
+/*
+ * EntityStatusPanel JS — thermostat.
+ *
+ * The dial's setpoint marker and current-temperature marker need
+ * SVG rotations computed from the numeric temperature magnitude.
+ * CSS keyed on the ``status`` attribute can't compute angles, so
+ * this panel registers a polling handler with the framework: the
+ * handler runs after each polling apply pass and re-positions the
+ * markers based on the latest values delivered in the statusMap.
+ *
+ * Each marker carries its own ``data-marker-state-id`` attribute
+ * naming the EntityState whose magnitude drives its angle. This is
+ * a panel-private attribute (distinct from the framework's
+ * ``data-state-id``) so the universal dispatcher doesn't try to
+ * apply text/attr updates to the SVG marker group — those updates
+ * are inappropriate here. The handler looks up the entry directly
+ * by state id, so the dispatch works uniformly across the modal /
+ * list / grid render contexts even though their non-dial layouts
+ * differ.
+ *
+ * Initial positioning on page load uses ``data-temp-value`` baked
+ * in by the server-rendered template so the dial reads correctly
+ * before the first polling refresh. The template seeds this from
+ * the user's display-unit magnitude, matching the polling-time
+ * unit so the dial calibration is consistent across both paths.
+ */
+(function() {
+ 'use strict';
+
+ // Temperature range that maps to the dial's visible arc.
+ // 50°F at -135° (lower-left) → 90°F at +135° (lower-right);
+ // bottom 90° is the dial's "gap" and not part of the range.
+ const TEMP_RANGE_LOW = 50;
+ const TEMP_RANGE_HIGH = 90;
+ const ANGLE_LOW = -135;
+ const ANGLE_HIGH = 135;
+
+ const MARKER_SELECTOR = '.dial-setpoint-marker, .dial-current-marker';
+
+ function temperatureToAngle( tempValue ) {
+ const value = parseFloat( tempValue );
+ if ( isNaN( value ) ) return 0;
+ const clamped = Math.max( TEMP_RANGE_LOW, Math.min( TEMP_RANGE_HIGH, value ) );
+ const fraction = ( clamped - TEMP_RANGE_LOW ) / ( TEMP_RANGE_HIGH - TEMP_RANGE_LOW );
+ return ANGLE_LOW + fraction * ( ANGLE_HIGH - ANGLE_LOW );
+ }
+
+ function applyAngleToMarker( $marker, tempValue ) {
+ const angle = temperatureToAngle( tempValue );
+ $marker.attr( 'transform', 'rotate(' + angle + ' 110 110)' );
+ }
+
+ // Initial render: each marker has the numeric value baked in
+ // as ``data-temp-value``. Position them from those values so
+ // the dial reads correctly before the first polling cycle.
+ function applyInitialMarkerAngles() {
+ $( '.hi-state-panel-thermostat' ).find( MARKER_SELECTOR ).each( function() {
+ applyAngleToMarker( $( this ), $( this ).attr( 'data-temp-value' ) );
+ });
+ }
+
+ // Polling-driven updates: each marker self-identifies via
+ // ``data-marker-state-id`` — the EntityState whose magnitude
+ // drives its angle. Look up that state id in the statusMap
+ // and refresh both the cached ``data-temp-value`` and the
+ // rotation.
+ function applyMarkerAnglesFromStatusMap( statusMap ) {
+ $( '.hi-state-panel-thermostat' ).find( MARKER_SELECTOR ).each( function() {
+ const $marker = $( this );
+ const stateId = $marker.attr( 'data-marker-state-id' );
+ if ( ! stateId ) return;
+ const entry = statusMap[ stateId ];
+ if ( ! entry || ! entry.display ) return;
+ const magnitude = entry.display.magnitude;
+ if ( magnitude == null ) return;
+ $marker.attr( 'data-temp-value', magnitude );
+ applyAngleToMarker( $marker, magnitude );
+ });
+ }
+
+ if ( window.Hi && Hi.statePanels ) {
+ if ( typeof Hi.statePanels.registerUpdate === 'function' ) {
+ Hi.statePanels.registerUpdate( applyMarkerAnglesFromStatusMap );
+ }
+ if ( typeof Hi.statePanels.registerInit === 'function' ) {
+ // Fires on initial page load and after each async fragment
+ // insert, so dial markers in dynamically-loaded modals get
+ // their angles set from server-rendered ``data-temp-value``
+ // before the first polling tick.
+ Hi.statePanels.registerInit( applyInitialMarkerAngles );
+ }
+ }
+
+})();
diff --git a/src/hi/templates/service-worker.js b/src/hi/templates/service-worker.js
index bb6def0a..3a507371 100644
--- a/src/hi/templates/service-worker.js
+++ b/src/hi/templates/service-worker.js
@@ -1,74 +1,68 @@
-{% load static %}
+// Static-asset cache + pass-through for everything else.
+//
+// The service worker intercepts only requests whose path begins with
+// Django's STATIC_URL. Cache-first with on-demand population on miss.
+// Everything else — dynamic pages, the polling endpoint, MJPEG video
+// streams (multipart/x-mixed-replace) — passes through to the
+// browser's native fetch path. Firefox in particular mishandles
+// multiple concurrent multipart streams routed through a service
+// worker's respondWith, so this scoping is deliberate.
-var CACHE_VERSION = 1;
-var OFFLINE_CACHE_NAME = 'offline-cache-' + CACHE_VERSION;
+var CACHE_VERSION = 2;
var STATIC_CACHE_NAME = 'static-cache-' + CACHE_VERSION;
+var STATIC_URL_PREFIX = '{{ STATIC_URL }}';
-// Assets to cache for offline use
-var STATIC_ASSETS = [
- '/',
- '{% static "css/main.css" %}',
- '{% static "css/icons.css" %}',
- '{% static "css/attribute.css" %}',
- '{% static "js/jquery-3.7.0.min.js" %}',
- '{% static "js/antinode.js" %}',
- '{% static "js/main.js" %}',
- '{% static "bootstrap/css/bootstrap.css" %}',
- '{% static "bootstrap/js/bootstrap.js" %}',
- '{% static "img/hi-icon-128x128.png" %}',
- '{% static "img/hi-icon-196x196.png" %}',
- '{% static "img/hi-icon-512x512.png" %}',
- '{% static "favicon.png" %}'
-];
-
-// Install event - cache static assets
self.addEventListener('install', function(event) {
- console.log('Service Worker: Installing...');
- event.waitUntil(
- caches.open(STATIC_CACHE_NAME)
- .then(function(cache) {
- console.log('Service Worker: Caching static assets');
- return cache.addAll(STATIC_ASSETS);
- })
- .then(function() {
- console.log('Service Worker: Installation complete');
- return self.skipWaiting();
- })
- );
+ // Take over immediately rather than waiting for all existing
+ // controlled pages to close. Combined with ``clients.claim()`` on
+ // activate, this ensures the new SW handles fetches as soon as it
+ // is installed.
+ event.waitUntil(self.skipWaiting());
});
-// Activate event - clean up old caches
self.addEventListener('activate', function(event) {
- console.log('Service Worker: Activating...');
+ // Sweep any caches that don't match the current version. Bumping
+ // CACHE_VERSION invalidates everything previously cached.
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
- cacheNames.map(function(cacheName) {
- if (cacheName !== STATIC_CACHE_NAME && cacheName !== OFFLINE_CACHE_NAME) {
- console.log('Service Worker: Deleting old cache:', cacheName);
- return caches.delete(cacheName);
+ cacheNames.map(function(name) {
+ if (name !== STATIC_CACHE_NAME) {
+ return caches.delete(name);
}
})
);
}).then(function() {
- console.log('Service Worker: Activation complete');
return self.clients.claim();
})
);
});
-// Fetch event - no caching, always use network
self.addEventListener('fetch', function(event) {
- // Only handle GET requests
if (event.request.method !== 'GET') {
return;
}
-
- // Skip non-HTTP(S) requests
if (!event.request.url.startsWith('http')) {
return;
}
-
- // Always fetch from network, no caching
- event.respondWith(fetch(event.request));
+ var pathname = new URL(event.request.url).pathname;
+ if (!pathname.startsWith(STATIC_URL_PREFIX)) {
+ return;
+ }
+ event.respondWith(
+ caches.match(event.request).then(function(cached) {
+ if (cached) {
+ return cached;
+ }
+ return fetch(event.request).then(function(response) {
+ if (response && response.ok) {
+ var clone = response.clone();
+ caches.open(STATIC_CACHE_NAME).then(function(cache) {
+ cache.put(event.request, clone);
+ });
+ }
+ return response;
+ });
+ })
+ );
});