Skip to content

Home Information - Your home, your data, organized.

Python

Editor & integration tweaks (2026-06-10) (#401)

Tony C8eb564546709
diff --git a/src/hi/apps/attribute/templatetags/attribute_extras.py b/src/hi/apps/attribute/templatetags/attribute_extras.py
index 497af1e1..fff82966 100644
--- a/src/hi/apps/attribute/templatetags/attribute_extras.py
+++ b/src/hi/apps/attribute/templatetags/attribute_extras.py
@@ -6,24 +6,55 @@ from django.utils.html import escape, format_html
from django.utils.safestring import mark_safe
register = template.Library()
-_URL_IN_TEXT_PATTERN = re.compile(r'https?://[^\s<>"\']+')
+
+# Schemes are split by URI shape so both the validator and the
+# free-text regex can be driven from one list. To add a scheme, add it
+# to whichever group matches its syntax — _URL_IN_TEXT_PATTERN and
+# _is_valid_url automatically pick it up.
+#
+# Netloc-form (``scheme://netloc/...``): http, https, rtsp.
+# Path-only-form (``scheme:path``, no ``//``): mailto, tel, sms.
+#
+# Note on rtsp: most browsers don't open it natively — clicking only
+# works for users with a registered handler (e.g., VLC). Keeping it
+# linkable lets users right-click → copy URL.
+_NETLOC_SCHEMES = ( 'http', 'https', 'rtsp' )
+_PATH_ONLY_SCHEMES = ( 'mailto', 'tel', 'sms' )
+_LINKABLE_URL_SCHEMES = frozenset( _NETLOC_SCHEMES + _PATH_ONLY_SCHEMES )
+
+# One regex finds every linkable URL form in free text. Built from the
+# scheme lists so the allowlist and the matcher can never drift.
+_URL_IN_TEXT_PATTERN = re.compile(
+ r'(?:(?:%s)://|(?:%s):)[^\s<>"\']+' % (
+ '|'.join( _NETLOC_SCHEMES ),
+ '|'.join( _PATH_ONLY_SCHEMES ),
+ )
+)
+
_TRAILING_PUNCTUATION = '.,;:!?)]}'
def _is_valid_url(value):
- """Return True when value looks like an http(s) URL with a host.
+ """Return True when value is a linkable URL.
- Single-label intranet hostnames (e.g. ``http://cassandra:4100/…``)
- are accepted; Django's URLValidator rejects those because they
- lack a TLD, but they're common on LANs.
+ Netloc-form schemes (http, https, rtsp) require a non-empty
+ ``netloc`` — single-label intranet hostnames (e.g.
+ ``http://cassandra:4100/…``) are accepted; Django's URLValidator
+ rejects those because they lack a TLD, but they're common on LANs.
+
+ Path-only schemes (mailto, tel, sms) require a non-empty ``path``
+ (the email address / phone number), since they carry no netloc.
"""
try:
parsed = urlparse(value)
except ValueError:
return False
- if parsed.scheme not in ('http', 'https'):
- return False
- return bool(parsed.netloc)
+ scheme = parsed.scheme
+ if scheme in _NETLOC_SCHEMES:
+ return bool(parsed.netloc)
+ if scheme in _PATH_ONLY_SCHEMES:
+ return bool(parsed.path)
+ return False
def _split_url_and_trailing_punctuation(candidate):
diff --git a/src/hi/apps/attribute/tests/test_templatetags.py b/src/hi/apps/attribute/tests/test_templatetags.py
index 1e56d460..24c2c37f 100644
--- a/src/hi/apps/attribute/tests/test_templatetags.py
+++ b/src/hi/apps/attribute/tests/test_templatetags.py
@@ -169,6 +169,46 @@ class TestAttributeUrlFilter(TestCase):
self.assertEqual(attribute_url(""), "")
self.assertEqual(attribute_url(None), "")
+ def test_attribute_url_accepts_path_only_schemes(self):
+ # mailto / tel / sms have no netloc — the address/number is in
+ # the path. Regression: earlier code required netloc and broke
+ # these.
+ self.assertEqual(
+ attribute_url("mailto:[email protected]"), "mailto:[email protected]"
+ )
+ self.assertEqual(
+ attribute_url("tel:+15551234567"), "tel:+15551234567"
+ )
+ self.assertEqual(
+ attribute_url("sms:+15551234567"), "sms:+15551234567"
+ )
+
+ def test_attribute_url_accepts_rtsp(self):
+ self.assertEqual(
+ attribute_url("rtsp://10.0.0.1:554/stream"),
+ "rtsp://10.0.0.1:554/stream",
+ )
+
+ def test_attribute_url_rejects_path_only_scheme_without_address(self):
+ # A bare ``mailto:`` / ``tel:`` / ``sms:`` is not a usable link.
+ self.assertEqual(attribute_url("mailto:"), "")
+ self.assertEqual(attribute_url("tel:"), "")
+ self.assertEqual(attribute_url("sms:"), "")
+
+ def test_attribute_url_rejects_netloc_scheme_without_host(self):
+ self.assertEqual(attribute_url("http://"), "")
+ self.assertEqual(attribute_url("rtsp://"), "")
+
+ def test_attribute_url_rejects_disallowed_schemes(self):
+ # Security boundary — every scheme outside _LINKABLE_URL_SCHEMES
+ # must be refused. ``javascript:`` is the canonical XSS vector;
+ # ``data:`` can embed scripts; ``ftp:`` / ``file:`` are dropped
+ # by modern browsers and only leak content shape.
+ self.assertEqual(attribute_url("javascript:alert(1)"), "")
+ self.assertEqual(attribute_url("data:text/html,<script>"), "")
+ self.assertEqual(attribute_url("ftp://foo.com"), "")
+ self.assertEqual(attribute_url("file:///etc/passwd"), "")
+
class TestAttributeTextUrlFilters(TestCase):
"""Test URL detection and inline linkification for text attributes."""
@@ -242,6 +282,60 @@ class TestAttributeTextUrlFilters(TestCase):
self.assertIn('<a href="https://example.com" target="_blank" rel="noopener noreferrer">', rendered)
self.assertNotIn('&lt;a href=', rendered)
+ def test_attribute_text_has_url_detects_path_only_schemes(self):
+ # mailto / tel / sms embedded in free text — regex must match
+ # the ``scheme:`` (no ``//``) shape, not just ``scheme://``.
+ self.assertTrue(attribute_text_has_url("Email mailto:[email protected] for support"))
+ self.assertTrue(attribute_text_has_url("Call tel:+15551234567 anytime"))
+ self.assertTrue(attribute_text_has_url("Or text sms:+15551234567 directly"))
+
+ def test_attribute_text_has_url_detects_rtsp(self):
+ self.assertTrue(
+ attribute_text_has_url("Stream at rtsp://10.0.0.1:554/live now")
+ )
+
+ def test_attribute_text_has_url_ignores_disallowed_schemes(self):
+ self.assertFalse(attribute_text_has_url("Click javascript:alert(1) for fun"))
+ self.assertFalse(attribute_text_has_url("Get the file ftp://foo.com/bin"))
+
+ def test_attribute_text_linkify_renders_path_only_schemes(self):
+ # All four path-only / netloc schemes in one mixed prose blob.
+ rendered = attribute_text_linkify(
+ "Email mailto:[email protected], call tel:+15551234567, "
+ "text sms:+15551234567, stream rtsp://10.0.0.1:554/live"
+ )
+ self.assertIn(
+ '<a href="mailto:[email protected]" target="_blank" rel="noopener noreferrer">mailto:[email protected]</a>',
+ rendered,
+ )
+ self.assertIn(
+ '<a href="tel:+15551234567" target="_blank" rel="noopener noreferrer">tel:+15551234567</a>',
+ rendered,
+ )
+ self.assertIn(
+ '<a href="sms:+15551234567" target="_blank" rel="noopener noreferrer">sms:+15551234567</a>',
+ rendered,
+ )
+ self.assertIn(
+ '<a href="rtsp://10.0.0.1:554/live" target="_blank" rel="noopener noreferrer">rtsp://10.0.0.1:554/live</a>',
+ rendered,
+ )
+
+ def test_attribute_text_linkify_does_not_link_disallowed_schemes(self):
+ # ``javascript:`` content stays as escaped text — no anchor tag.
+ rendered = attribute_text_linkify("Run javascript:alert(1) here")
+ self.assertNotIn('<a href="javascript:', rendered)
+ self.assertIn('javascript:alert(1)', rendered)
+
+ def test_attribute_text_linkify_keeps_trailing_punctuation_outside_path_only_schemes(self):
+ # The same trailing-punctuation strip that protects http(s)
+ # links has to work for mailto / tel / sms too.
+ rendered = attribute_text_linkify("Reach me at mailto:[email protected], anytime.")
+ self.assertIn(
+ '<a href="mailto:[email protected]" target="_blank" rel="noopener noreferrer">mailto:[email protected]</a>,',
+ rendered,
+ )
+
def test_attribute_text_has_url_filter_works_in_template_condition(self):
template_str = """
{% load attribute_extras %}
diff --git a/src/hi/apps/collection/collection_manager.py b/src/hi/apps/collection/collection_manager.py
index 77e4f5cf..80cdb662 100644
--- a/src/hi/apps/collection/collection_manager.py
+++ b/src/hi/apps/collection/collection_manager.py
@@ -7,7 +7,7 @@ from django.http import HttpRequest
from hi.apps.collection.edit.forms import CollectionPositionForm
from hi.apps.common.singleton import Singleton
from hi.apps.entity.enums import DisplayContext, EntityGroupType
-from hi.apps.entity.models import Entity
+from hi.apps.entity.models import Entity, EntityStateDelegation
from hi.apps.entity.state_panel_dispatch import EntityStatePanelData, StatePanelDispatcher
from hi.apps.location.models import Location, LocationView
from hi.apps.location.svg_item_factory import SvgItemFactory
@@ -24,6 +24,7 @@ from .models import (
from .transient_models import (
CollectionData,
CollectionEditModeData,
+ CollectionEntityPickerData,
CollectionViewGroup,
CollectionViewItem,
EntityCollectionGroup,
@@ -341,6 +342,41 @@ class CollectionManager(Singleton):
collection_position_form = collection_position_form,
)
+ def _collection_member_entity_id_set( self, collection : Collection ) -> set:
+ return set(
+ CollectionEntity.objects.filter( collection = collection )
+ .values_list( 'entity_id', flat = True )
+ )
+
+ def _build_entity_collection_group_list( self,
+ collection : Collection,
+ entities : List[ Entity ],
+ member_entity_id_set : set,
+ unused_entity_ids : set,
+ ) -> List[EntityCollectionGroup]:
+ """Type-group the given entities, flagging each as in/out of the
+ collection from ``member_entity_id_set`` (no per-entity query)."""
+ entity_collection_group_dict = dict()
+ for entity in entities:
+ entity_collection_item = EntityCollectionItem(
+ entity = entity,
+ exists_in_collection = entity.id in member_entity_id_set,
+ is_unused = entity.id in unused_entity_ids,
+ )
+
+ entity_group_type = EntityGroupType.from_entity_type( entity.entity_type )
+ if entity_group_type not in entity_collection_group_dict:
+ entity_collection_group_dict[entity_group_type] = EntityCollectionGroup(
+ collection = collection,
+ entity_group_type = entity_group_type,
+ )
+ entity_collection_group_dict[entity_group_type].item_list.append( entity_collection_item )
+ continue
+
+ entity_collection_group_list = list( entity_collection_group_dict.values() )
+ entity_collection_group_list.sort( key = lambda item : item.entity_group_type.label )
+ return entity_collection_group_list
+
def create_entity_collection_group_list( self,
collection : Collection,
unused_entity_ids : set = None,
@@ -356,36 +392,53 @@ class CollectionManager(Singleton):
if unused_entity_ids is None:
unused_entity_ids = set()
- entity_collection_group_dict = dict()
- for entity in entity_queryset:
+ return self._build_entity_collection_group_list(
+ collection = collection,
+ entities = list( entity_queryset ),
+ member_entity_id_set = self._collection_member_entity_id_set( collection ),
+ unused_entity_ids = unused_entity_ids,
+ )
- exists_in_collection = False
- for collection_entity in entity.collections.all():
- if collection_entity.collection == collection:
- exists_in_collection = True
- break
- continue
+ def create_collection_entity_picker_data( self,
+ collection : Collection,
+ unused_entity_ids : set = None,
+ ) -> CollectionEntityPickerData:
+ """Build both Collection item-picker sections in a single entity
+ scan: the type-grouped non-delegate entities and the flat delegate
+ ("Paired Items") list. Replaces a separate query per section --
+ entities are loaded once and partitioned in Python by whether they
+ act as a delegate, sharing one collection-membership lookup."""
+ if unused_entity_ids is None:
+ unused_entity_ids = set()
+ member_entity_id_set = self._collection_member_entity_id_set( collection )
+ delegate_entity_id_set = set(
+ EntityStateDelegation.objects.values_list( 'delegate_entity_id', flat = True ).distinct()
+ )
+ all_entities = list( Entity.objects.all() )
- entity_collection_item = EntityCollectionItem(
+ non_delegate_entities = [ entity for entity in all_entities
+ if entity.id not in delegate_entity_id_set ]
+ entity_collection_group_list = self._build_entity_collection_group_list(
+ collection = collection,
+ entities = non_delegate_entities,
+ member_entity_id_set = member_entity_id_set,
+ unused_entity_ids = unused_entity_ids,
+ )
+
+ delegate_view_item_list = [
+ EntityCollectionItem(
entity = entity,
- exists_in_collection = exists_in_collection,
+ exists_in_collection = entity.id in member_entity_id_set,
is_unused = entity.id in unused_entity_ids,
)
+ for entity in all_entities if entity.id in delegate_entity_id_set
+ ]
+ delegate_view_item_list.sort( key = lambda item : item.entity.name )
- entity_group_type = EntityGroupType.from_entity_type( entity.entity_type )
-
- if entity_group_type not in entity_collection_group_dict:
- entity_collection_group = EntityCollectionGroup(
- collection = collection,
- entity_group_type = entity_group_type,
- )
- entity_collection_group_dict[entity_group_type] = entity_collection_group
- entity_collection_group_dict[entity_group_type].item_list.append( entity_collection_item )
- continue
-
- entity_collection_group_list = list( entity_collection_group_dict.values() )
- entity_collection_group_list.sort( key = lambda item : item.entity_group_type.label )
- return entity_collection_group_list
+ return CollectionEntityPickerData(
+ entity_collection_group_list = entity_collection_group_list,
+ delegate_view_item_list = delegate_view_item_list,
+ )
def toggle_entity_in_collection( self, entity : Entity, collection : Collection ) -> bool:
diff --git a/src/hi/apps/collection/edit/views.py b/src/hi/apps/collection/edit/views.py
index 9fc5b5ac..d51044e4 100644
--- a/src/hi/apps/collection/edit/views.py
+++ b/src/hi/apps/collection/edit/views.py
@@ -252,13 +252,14 @@ class CollectionManageItemsView( HiSideView ):
collection = CollectionManager().get_default_collection( request = request )
unused_entity_ids = EditViewHelpers.get_unused_entity_ids()
- entity_collection_group_list = CollectionManager().create_entity_collection_group_list(
+ entity_picker_data = CollectionManager().create_collection_entity_picker_data(
collection = collection,
unused_entity_ids = unused_entity_ids,
- exclude_delegates = True,
)
return {
- 'entity_collection_group_list': entity_collection_group_list,
+ 'collection': collection,
+ 'entity_collection_group_list': entity_picker_data.entity_collection_group_list,
+ 'delegate_view_item_list': entity_picker_data.delegate_view_item_list,
}
diff --git a/src/hi/apps/collection/templates/collection/edit/panes/collection_manage_items.html b/src/hi/apps/collection/templates/collection/edit/panes/collection_manage_items.html
index 4196b5fa..acd95fc8 100644
--- a/src/hi/apps/collection/templates/collection/edit/panes/collection_manage_items.html
+++ b/src/hi/apps/collection/templates/collection/edit/panes/collection_manage_items.html
@@ -22,3 +22,23 @@
{% include "edit/panes/no_entities_message.html" %}
{% endfor %}
{% endblock %}
+
+{% block delegates_section %}
+{% if delegate_view_item_list %}
+<div class="{{ DIVID.ENTITY_PICKER_GROUP_SECTION_CLASS }}" data-group="paired-items">
+ <div class="entity-group-header"
+ data-toggle="collapse"
+ data-target="#group-paired-items"
+ aria-expanded="false"
+ aria-controls="group-paired-items">
+ <span class="entity-group-title">Paired Items</span>
+ {% icon "chevron-down" css_class="entity-group-toggle" %}
+ </div>
+ <div class="entity-group-items collapse" id="group-paired-items">
+ {% for entity_collection_item in delegate_view_item_list %}
+ {% include "collection/edit/panes/collection_entity_toggle.html" with collection=collection entity=entity_collection_item.entity exists_in_collection=entity_collection_item.exists_in_collection is_unused=entity_collection_item.is_unused %}
+ {% endfor %}
+ </div>
+</div>
+{% endif %}
+{% endblock %}
diff --git a/src/hi/apps/collection/tests/test_collection_manager.py b/src/hi/apps/collection/tests/test_collection_manager.py
index 87b62b83..0b9c8d14 100644
--- a/src/hi/apps/collection/tests/test_collection_manager.py
+++ b/src/hi/apps/collection/tests/test_collection_manager.py
@@ -723,6 +723,95 @@ class TestCreateEntityCollectionGroupListExcludeDelegates(BaseTestCase):
collection_view_type_str='LIST',
)
+ def _make_named_delegate(self, principal_name, delegate_name):
+ principal = Entity.objects.create(
+ name=principal_name,
+ entity_type_str=str(EntityType.MOTION_SENSOR),
+ )
+ state = EntityState.objects.create(
+ entity=principal,
+ entity_state_type_str=str(EntityStateType.MOVEMENT),
+ name='movement',
+ )
+ delegate = Entity.objects.create(
+ name=delegate_name,
+ entity_type_str=str(EntityType.AREA),
+ )
+ EntityStateDelegation.objects.create(
+ entity_state=state,
+ delegate_entity=delegate,
+ )
+ return delegate
+
+ def _picker_groups_and_delegates(self, collection, unused_entity_ids=None):
+ """Bridges the current two-method picker API (type-grouped list +
+ delegate list). The query-optimization refactor will repoint this
+ single helper at the combined method without touching the test
+ bodies, so these tests double as a behavior-preserving net."""
+ if unused_entity_ids is None:
+ unused_entity_ids = set()
+ picker_data = CollectionManager().create_collection_entity_picker_data(
+ collection=collection,
+ unused_entity_ids=unused_entity_ids,
+ )
+ return picker_data.entity_collection_group_list, picker_data.delegate_view_item_list
+
+ def test_collection_delegate_partition_is_mutually_exclusive(self):
+ # A delegate appears only in the delegate list; a non-delegate
+ # (principal or standalone) appears only in the type-grouped
+ # list. The two halves never overlap.
+ principal, delegate_area = self._make_principal_with_delegate()
+ standalone = Entity.objects.create(
+ name='Standalone Light',
+ entity_type_str=str(EntityType.LIGHT),
+ )
+ collection = self._make_collection()
+
+ group_list, delegate_item_list = self._picker_groups_and_delegates(collection)
+ group_names = self._names_in_groups(group_list)
+ delegate_names = { item.entity.name for item in delegate_item_list }
+
+ self.assertEqual(delegate_names, { delegate_area.name })
+ self.assertIn(principal.name, group_names)
+ self.assertIn(standalone.name, group_names)
+ self.assertNotIn(delegate_area.name, group_names)
+ self.assertNotIn(principal.name, delegate_names)
+ self.assertNotIn(standalone.name, delegate_names)
+
+ def test_collection_delegate_exists_in_collection_flag(self):
+ # A delegate already in the collection is flagged in-collection so
+ # the picker renders it as a toggle-off; one not in it is not.
+ delegate_in = self._make_named_delegate('Front Motion', 'Front Area')
+ delegate_out = self._make_named_delegate('Back Motion', 'Back Area')
+ collection = self._make_collection()
+ CollectionEntity.objects.create(collection=collection, entity=delegate_in)
+
+ _, delegate_item_list = self._picker_groups_and_delegates(collection)
+ exists_by_name = {
+ item.entity.name: item.exists_in_collection for item in delegate_item_list
+ }
+
+ self.assertTrue(exists_by_name[delegate_in.name])
+ self.assertFalse(exists_by_name[delegate_out.name])
+
+ def test_is_unused_propagates_to_collection_delegate_list(self):
+ # The delegate list carries the is_unused flag through from the
+ # caller-supplied set, same as the type-grouped list.
+ _, delegate_area = self._make_principal_with_delegate()
+ collection = self._make_collection()
+
+ _, delegate_item_list = self._picker_groups_and_delegates(
+ collection, unused_entity_ids={ delegate_area.id },
+ )
+ item = next( i for i in delegate_item_list if i.entity == delegate_area )
+ self.assertTrue(item.is_unused)
+
+ _, delegate_item_list = self._picker_groups_and_delegates(
+ collection, unused_entity_ids=set(),
+ )
+ item = next( i for i in delegate_item_list if i.entity == delegate_area )
+ self.assertFalse(item.is_unused)
+
def test_delegate_hidden_when_exclude_delegates_true(self):
principal, delegate_area = self._make_principal_with_delegate()
collection = self._make_collection()
diff --git a/src/hi/apps/collection/transient_models.py b/src/hi/apps/collection/transient_models.py
index 5621e8a9..a6b9aa2b 100644
--- a/src/hi/apps/collection/transient_models.py
+++ b/src/hi/apps/collection/transient_models.py
@@ -52,6 +52,16 @@ class EntityCollectionGroup:
item_list : List[EntityCollectionItem] = field( default_factory = list )
+@dataclass
+class CollectionEntityPickerData:
+ """The two sections of the Collection item picker, built together from
+ a single entity scan: the type-grouped non-delegate entities and the
+ flat delegate ("Paired Items") list."""
+
+ entity_collection_group_list : List[EntityCollectionGroup] = field( default_factory = list )
+ delegate_view_item_list : List[EntityCollectionItem] = field( default_factory = list )
+
+
@dataclass
class CollectionEditModeData:
""" All the data needed to render the Collection details pane. """
diff --git a/src/hi/apps/edit/templates/edit/panes/entity_picker.html b/src/hi/apps/edit/templates/edit/panes/entity_picker.html
index 24671aa5..591bc0bf 100644
--- a/src/hi/apps/edit/templates/edit/panes/entity_picker.html
+++ b/src/hi/apps/edit/templates/edit/panes/entity_picker.html
@@ -56,6 +56,15 @@
{# Override this block in child templates #}
{% endblock %}
+ {% comment %}
+ Paired Items render with the entity groups (they are just another
+ grouping of entities); Collections render last as they are a
+ different kind of item -- a navigable reference, not an entity.
+ {% endcomment %}
+ {% block delegates_section %}
+ {# Override this block for pickers that surface delegate (paired) items #}
+ {% endblock %}
+
{% block collections_section %}
{# Override this block for location views that need collections section #}
{% endblock %}
diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.py
index df03850c..43032fcf 100644
--- a/src/hi/apps/entity/entity_manager.py
+++ b/src/hi/apps/entity/entity_manager.py
@@ -26,6 +26,7 @@ from .transient_models import (
EntityEditModeData,
EntityViewGroup,
EntityViewItem,
+ LocationViewEntityPickerData,
)
logger = logging.getLogger(__name__)
@@ -100,6 +101,48 @@ class EntityManager(Singleton):
unused_entity_ids = unused_entity_ids,
)
+ def create_location_entity_picker_data( self,
+ location_view : LocationView,
+ unused_entity_ids : set = None,
+ ) -> LocationViewEntityPickerData:
+ """Build both LocationView item-picker sections in a single entity
+ scan: the type-grouped non-delegate entities and the flat delegate
+ ("Paired Items") list. Replaces a separate query per section --
+ the entities are loaded once and partitioned in Python by whether
+ they act as a delegate, sharing one ``entity_views`` lookup."""
+ if unused_entity_ids is None:
+ unused_entity_ids = set()
+ existing_entities = [ x.entity
+ for x in location_view.entity_views.select_related('entity').all() ]
+ existing_entity_id_set = { x.id for x in existing_entities }
+ delegate_entity_id_set = set(
+ EntityStateDelegation.objects.values_list( 'delegate_entity_id', flat = True ).distinct()
+ )
+ all_entities = list( Entity.objects.all() )
+
+ non_delegate_entities = [ entity for entity in all_entities
+ if entity.id not in delegate_entity_id_set ]
+ entity_view_group_list = self.create_entity_view_group_list(
+ existing_entities = existing_entities,
+ all_entities = non_delegate_entities,
+ unused_entity_ids = unused_entity_ids,
+ )
+
+ delegate_view_item_list = [
+ EntityViewItem(
+ entity = entity,
+ exists_in_view = entity.id in existing_entity_id_set,
+ is_unused = entity.id in unused_entity_ids,
+ )
+ for entity in all_entities if entity.id in delegate_entity_id_set
+ ]
+ delegate_view_item_list.sort( key = lambda item : item.entity.name )
+
+ return LocationViewEntityPickerData(
+ entity_view_group_list = entity_view_group_list,
+ delegate_view_item_list = delegate_view_item_list,
+ )
+
def create_entity_view_group_list( self,
existing_entities : List[ Entity ],
all_entities : Sequence[ Entity ],
diff --git a/src/hi/apps/entity/templates/entity/state_panels/fallback/state_compact.html b/src/hi/apps/entity/templates/entity/state_panels/fallback/state_compact.html
index 812fc0c9..25e2872a 100644
--- a/src/hi/apps/entity/templates/entity/state_panels/fallback/state_compact.html
+++ b/src/hi/apps/entity/templates/entity/state_panels/fallback/state_compact.html
@@ -1,17 +1,34 @@
-{# Per-state compact rendering for fallback ROW / TILE contexts. #}
-{# Label above value/controller widget. Used by fallback row.html and #}
-{# tile.html, capped to a small number of states per the framework's #}
-{# "fallback is intentionally minimal" stance. #}
+{% comment %}
+Per-state compact rendering for fallback ROW / TILE contexts. Label above
+value/controller widget. Used by fallback row.html and tile.html, capped to
+a small number of states per the framework's "fallback is intentionally
+minimal" stance.
+
+Value rendering mirrors the modal's chip pattern from
+``sensor_response_status_row.html``: ``hi-status-display`` class +
+``data-status`` marker + ``status="..."`` attribute drive the CSS chip
+styling keyed on the recognized status token (connected, disconnected, on,
+off, open, closed, etc.). The status attribute is always lowercased so CSS
+selectors stay consistent regardless of whether the value came from an
+explicit ``StatusStyle`` mapping or the raw sensor value (free-form TEXT
+from a Command Line sensor, etc.).
+{% endcomment %}
<div class="state-compact">
+ {% if state_data.entity_state.short_name != entity.name %}
<div class="state-compact__label">{{ state_data.entity_state.short_name }}</div>
+ {% endif %}
<div class="state-compact__value">
{% if state_data.controller_data_list %}
{% for controller_data in state_data.controller_data_list %}
{% include "control/panes/controller_data.html" with controller_data=controller_data %}
{% endfor %}
{% elif state_data.latest_display_label %}
- <span data-state-id="{{ state_data.entity_state.id }}"
- data-display-text>{{ state_data.latest_display_label }}</span>
+ {% with status_value=state_data.attribute_dict.status %}
+ <span class="hi-status-display"
+ data-state-id="{{ state_data.entity_state.id }}"
+ data-status data-display-text
+ {% if status_value %}status="{{ status_value }}"{% endif %}>{{ state_data.latest_display_label }}</span>
+ {% endwith %}
{% endif %}
</div>
</div>
diff --git a/src/hi/apps/entity/templates/entity/svg/type.ups.svg b/src/hi/apps/entity/templates/entity/svg/type.ups.svg
index dcd2bada..376ced86 100644
--- a/src/hi/apps/entity/templates/entity/svg/type.ups.svg
+++ b/src/hi/apps/entity/templates/entity/svg/type.ups.svg
@@ -1,7 +1,7 @@
<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
-<rect x="16" y="22" width="32" height="20" rx="2" fill="#333333" stroke="#333333" stroke-width="2"/>
-<rect x="20" y="26" width="24" height="12" fill="#00ff00" opacity="0.8" stroke="#333333" stroke-width="1"/>
-<text x="32" y="35" text-anchor="middle" font-family="monospace" font-size="8" font-weight="bold" fill="#ffffff">UPS</text>
-<rect x="14" y="30" width="4" height="4" fill="#808080"/>
-<rect x="46" y="30" width="4" height="4" fill="#808080"/>
-<circle cx="32" cy="18" r="2" fill="#00ff00"/>
\ No newline at end of file
+<rect x="4" y="19.75" width="56" height="35" rx="3.5" fill="#333333" stroke="#333333" stroke-width="3.5"/>
+<rect x="11" y="26.75" width="42" height="21" fill="#00ff00" opacity="0.8" stroke="#333333" stroke-width="1.75"/>
+<text x="32" y="42.5" text-anchor="middle" font-family="monospace" font-size="14" font-weight="bold" fill="#ffffff">UPS</text>
+<rect x="0.5" y="33.75" width="7" height="7" fill="#808080"/>
+<rect x="56.5" y="33.75" width="7" height="7" fill="#808080"/>
+<circle cx="32" cy="12.75" r="3.5" fill="#00ff00"/>
diff --git a/src/hi/apps/entity/tests/test_entity_manager.py b/src/hi/apps/entity/tests/test_entity_manager.py
index 5bd308d5..71d15140 100644
--- a/src/hi/apps/entity/tests/test_entity_manager.py
+++ b/src/hi/apps/entity/tests/test_entity_manager.py
@@ -5,6 +5,7 @@ from hi.apps.entity.models import (
Entity,
EntityState,
EntityStateDelegation,
+ EntityView,
)
from hi.apps.entity.enums import EntityGroupType, EntityStateType, EntityType
from hi.apps.location.tests.synthetic_data import LocationSyntheticData
@@ -230,6 +231,19 @@ class TestCreateLocationEntityViewGroupListExcludeDelegates(BaseTestCase):
for item in group.item_list
}
+ def _picker_groups_and_delegates(self, location_view, unused_entity_ids=None):
+ """Bridges the current two-method picker API (type-grouped list +
+ delegate list). The query-optimization refactor will repoint this
+ single helper at the combined method without touching the test
+ bodies, so these tests double as a behavior-preserving net."""
+ if unused_entity_ids is None:
+ unused_entity_ids = set()
+ picker_data = EntityManager().create_location_entity_picker_data(
+ location_view=location_view,
+ unused_entity_ids=unused_entity_ids,
+ )
+ return picker_data.entity_view_group_list, picker_data.delegate_view_item_list
+
def test_delegate_hidden_when_exclude_delegates_true(self):
principal, delegate_area = self._make_principal_with_delegate()
location_view = LocationSyntheticData.create_test_location_view()
@@ -275,4 +289,97 @@ class TestCreateLocationEntityViewGroupListExcludeDelegates(BaseTestCase):
names = self._names_in_groups(group_list)
self.assertIn(plain.name, names)
+ def test_delegate_view_item_list_contains_only_delegates(self):
+ # The "Paired Items" section is the complement of the excluded
+ # type-grouped list: just the delegates, neither the principal
+ # nor unrelated standalone entities.
+ principal, delegate_area = self._make_principal_with_delegate()
+ Entity.objects.create(
+ name='Standalone Light',
+ entity_type_str=str(EntityType.LIGHT),
+ )
+ location_view = LocationSyntheticData.create_test_location_view()
+
+ _, item_list = self._picker_groups_and_delegates(location_view)
+
+ names = { item.entity.name for item in item_list }
+ self.assertEqual(names, { delegate_area.name })
+
+ def _make_named_delegate(self, principal_name, delegate_name):
+ principal = Entity.objects.create(
+ name=principal_name,
+ entity_type_str=str(EntityType.MOTION_SENSOR),
+ )
+ state = EntityState.objects.create(
+ entity=principal,
+ entity_state_type_str=str(EntityStateType.MOVEMENT),
+ name='movement',
+ )
+ delegate = Entity.objects.create(
+ name=delegate_name,
+ entity_type_str=str(EntityType.AREA),
+ )
+ EntityStateDelegation.objects.create(
+ entity_state=state,
+ delegate_entity=delegate,
+ )
+ return delegate
+
+ def test_delegate_view_item_exists_in_view_flag(self):
+ # A delegate already placed in the view is flagged in-view so the
+ # picker renders it as a toggle-off; one not in the view is not.
+ delegate_area = self._make_named_delegate('Front Motion', 'Front Area')
+ other_delegate = self._make_named_delegate('Back Motion', 'Back Area')
+ location_view = LocationSyntheticData.create_test_location_view()
+ EntityView.objects.create(
+ entity=delegate_area,
+ location_view=location_view,
+ )
+
+ _, item_list = self._picker_groups_and_delegates(location_view)
+ exists_by_name = { item.entity.name: item.exists_in_view for item in item_list }
+
+ self.assertTrue(exists_by_name[delegate_area.name])
+ self.assertFalse(exists_by_name[other_delegate.name])
+
+ def test_delegate_partition_is_mutually_exclusive(self):
+ # A delegate appears only in the delegate list; a non-delegate
+ # (principal or standalone) appears only in the type-grouped
+ # list. The two halves never overlap.
+ principal, delegate_area = self._make_principal_with_delegate()
+ standalone = Entity.objects.create(
+ name='Standalone Light',
+ entity_type_str=str(EntityType.LIGHT),
+ )
+ location_view = LocationSyntheticData.create_test_location_view()
+
+ group_list, delegate_item_list = self._picker_groups_and_delegates(location_view)
+ group_names = self._names_in_groups(group_list)
+ delegate_names = { item.entity.name for item in delegate_item_list }
+
+ self.assertEqual(delegate_names, { delegate_area.name })
+ self.assertIn(principal.name, group_names)
+ self.assertIn(standalone.name, group_names)
+ self.assertNotIn(delegate_area.name, group_names)
+ self.assertNotIn(principal.name, delegate_names)
+ self.assertNotIn(standalone.name, delegate_names)
+
+ def test_is_unused_propagates_to_delegate_list(self):
+ # The delegate list carries the is_unused flag through from the
+ # caller-supplied set, same as the type-grouped list.
+ _, delegate_area = self._make_principal_with_delegate()
+ location_view = LocationSyntheticData.create_test_location_view()
+
+ _, delegate_item_list = self._picker_groups_and_delegates(
+ location_view, unused_entity_ids={ delegate_area.id },
+ )
+ item = next( i for i in delegate_item_list if i.entity == delegate_area )
+ self.assertTrue(item.is_unused)
+
+ _, delegate_item_list = self._picker_groups_and_delegates(
+ location_view, unused_entity_ids=set(),
+ )
+ item = next( i for i in delegate_item_list if i.entity == delegate_area )
+ self.assertFalse(item.is_unused)
+
diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.py
index 332d5125..a9677838 100644
--- a/src/hi/apps/entity/transient_models.py
+++ b/src/hi/apps/entity/transient_models.py
@@ -52,10 +52,20 @@ class EntityViewItem:
@dataclass
class EntityViewGroup:
"""All entities of a given type and flagged as in the view or not."""
-
+
entity_group_type : EntityGroupType
item_list : List[EntityViewItem] = field( default_factory = list )
+
+@dataclass
+class LocationViewEntityPickerData:
+ """The two sections of the LocationView item picker, built together
+ from a single entity scan: the type-grouped non-delegate entities and
+ the flat delegate ("Paired Items") list."""
+
+ entity_view_group_list : List[EntityViewGroup] = field( default_factory = list )
+ delegate_view_item_list : List[EntityViewItem] = field( default_factory = list )
+
@dataclass
class EntityPairing:
diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.py
index d039d4c8..5647d490 100644
--- a/src/hi/apps/location/edit/views.py
+++ b/src/hi/apps/location/edit/views.py
@@ -487,17 +487,17 @@ class LocationViewManageItemsView( HiSideView ):
location_view = LocationManager().get_default_location_view( request = request )
unused_entity_ids = EditViewHelpers.get_unused_entity_ids()
- entity_view_group_list = EntityManager().create_location_entity_view_group_list(
+ entity_picker_data = EntityManager().create_location_entity_picker_data(
location_view = location_view,
unused_entity_ids = unused_entity_ids,
- exclude_delegates = True,
)
collection_view_group = CollectionManager().create_location_collection_view_group(
location_view = location_view,
)
return {
'location_view': location_view,
- 'entity_view_group_list': entity_view_group_list,
+ 'entity_view_group_list': entity_picker_data.entity_view_group_list,
+ 'delegate_view_item_list': entity_picker_data.delegate_view_item_list,
'collection_view_group': collection_view_group,
}
diff --git a/src/hi/apps/location/enums.py b/src/hi/apps/location/enums.py
index 4b0726f6..b865b0fa 100644
--- a/src/hi/apps/location/enums.py
+++ b/src/hi/apps/location/enums.py
@@ -3,15 +3,19 @@ from hi.apps.common.enums import LabeledEnum
class LocationViewType(LabeledEnum):
"""View-level intent for a LocationView. Drives which interactions
- are offered: AUTOMATION enables one-click control on entity icons;
- DEFAULT and SECURITY route the click to the EntityStatus modal.
+ are offered on an entity icon tap: AUTOMATION enables one-click
+ control; DEFAULT and SECURITY route to the EntityStatus modal;
+ INFORMATION routes to the EntityEdit modal (entity details/config)
+ even when the entity has states. For AUTOMATION and INFORMATION a
+ long-press is the escape hatch back to the EntityStatus modal.
Per-entity state selection (visual primary, one-click target) is
handled by the role-based orderings in
``hi.apps.entity.entity_state_role_order``."""
- DEFAULT = ( 'Default' , '' )
- SECURITY = ( 'Security' , '' )
- AUTOMATION = ( 'Automation', '' )
+ DEFAULT = ( 'Default' , '' )
+ SECURITY = ( 'Security' , '' )
+ AUTOMATION = ( 'Automation' , '' )
+ INFORMATION = ( 'Information', '' )
class SvgItemType(LabeledEnum):
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.html b/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.html
index 741936b5..007d464f 100644
--- a/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.html
+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.html
@@ -25,13 +25,16 @@
{% block collections_section %}
{% if collection_view_group.item_list %}
-<div class="{{ DIVID.ENTITY_PICKER_GROUP_SECTION_CLASS }}" data-group="collections">
+<div class="{{ DIVID.ENTITY_PICKER_GROUP_SECTION_CLASS }} mt-4" data-group="collections">
<div class="entity-group-header"
data-toggle="collapse"
data-target="#group-collections"
aria-expanded="true"
aria-controls="group-collections">
- <span class="entity-group-title">Collections</span>
+ <div class="flex-grow-1">
+ <span class="entity-group-title d-block">{% icon "collection" size="sm" css_class="hi-icon-left" %}Collections</span>
+ <small class="text-muted-custom d-block">Adds a collection reference</small>
+ </div>
{% icon "chevron-down" css_class="entity-group-toggle" %}
</div>
<div class="entity-group-items collapse show" id="group-collections">
@@ -42,3 +45,23 @@
</div>
{% endif %}
{% endblock %}
+
+{% block delegates_section %}
+{% if delegate_view_item_list %}
+<div class="{{ DIVID.ENTITY_PICKER_GROUP_SECTION_CLASS }}" data-group="paired-items">
+ <div class="entity-group-header"
+ data-toggle="collapse"
+ data-target="#group-paired-items"
+ aria-expanded="false"
+ aria-controls="group-paired-items">
+ <span class="entity-group-title">Paired Items</span>
+ {% icon "chevron-down" css_class="entity-group-toggle" %}
+ </div>
+ <div class="entity-group-items collapse" id="group-paired-items">
+ {% for entity_view_item in delegate_view_item_list %}
+ {% include "location/edit/panes/location_view_entity_toggle.html" with location_view=location_view entity=entity_view_item.entity exists_in_view=entity_view_item.exists_in_view is_unused=entity_view_item.is_unused %}
+ {% endfor %}
+ </div>
+</div>
+{% endif %}
+{% endblock %}
diff --git a/src/hi/apps/location/tests/test_views.py b/src/hi/apps/location/tests/test_views.py
index 98566b80..7993930e 100644
--- a/src/hi/apps/location/tests/test_views.py
+++ b/src/hi/apps/location/tests/test_views.py
@@ -515,6 +515,15 @@ class TestLocationItemStatusView(SyncViewTestCase):
svg_rotate=0.0,
order_id=2
)
+
+ self.information_view = LocationView.objects.create(
+ location=self.location,
+ name='Information View',
+ location_view_type_str='information',
+ svg_view_box_str='0 0 100 100',
+ svg_rotate=0.0,
+ order_id=3
+ )
# Create test entity with controllable state
self.entity = Entity.objects.create(
@@ -769,6 +778,68 @@ class TestLocationItemStatusView(SyncViewTestCase):
expected_url = reverse('entity_status', kwargs={'entity_id': self.entity.id})
self.assertEqual(response.url, expected_url)
+ def test_information_view_tap_redirects_to_entity_edit(self):
+ """An INFORMATION view routes a plain entity tap to the edit
+ (details/config) modal even though the entity has states — where
+ a DEFAULT view would show status."""
+ from hi.enums import ItemType
+ session = self.client.session
+ session['view_type'] = str(ViewType.LOCATION_VIEW)
+ session['location_view_id'] = self.information_view.id
+ session.save()
+
+ html_id = ItemType.ENTITY.html_id(self.entity.id)
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
+
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, 302)
+ expected_url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
+ self.assertEqual(response.url, expected_url)
+
+ def test_information_view_long_press_redirects_to_status(self):
+ """Long-press is the escape hatch in an INFORMATION view: it
+ bypasses the edit modal and reaches entity status."""
+ from hi.enums import ItemType
+ session = self.client.session
+ session['view_type'] = str(ViewType.LOCATION_VIEW)
+ session['location_view_id'] = self.information_view.id
+ session.save()
+
+ html_id = ItemType.ENTITY.html_id(self.entity.id)
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
+
+ response = self.client.get(url + '?long_press=1')
+
+ self.assertEqual(response.status_code, 302)
+ expected_url = reverse('entity_status', kwargs={'entity_id': self.entity.id})
+ self.assertEqual(response.url, expected_url)
+
+ def test_information_view_tap_redirects_to_edit_even_without_states(self):
+ """The INFORMATION branch short-circuits to the edit modal before
+ the status route, so it applies regardless of whether the entity
+ has states (a stateless entity would otherwise also reach edit,
+ but via the status view's own fallback -- this confirms the
+ INFORMATION branch itself owns the routing)."""
+ from hi.enums import ItemType
+ stateless_entity = Entity.objects.create(
+ name='Decorative Marker',
+ entity_type_str='OTHER',
+ )
+ session = self.client.session
+ session['view_type'] = str(ViewType.LOCATION_VIEW)
+ session['location_view_id'] = self.information_view.id
+ session.save()
+
+ html_id = ItemType.ENTITY.html_id(stateless_entity.id)
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
+
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, 302)
+ expected_url = reverse('entity_edit', kwargs={'entity_id': stateless_entity.id})
+ self.assertEqual(response.url, expected_url)
+
@patch('hi.apps.control.one_click_control_service.ControllerManager')
def test_long_press_param_truthy_variants_all_bypass(self, mock_controller_manager):
"""The view consumes ``long_press`` via ``str_to_bool``, so any
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index a94b7fd1..98a00fa1 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -180,15 +180,27 @@ class LocationItemStatusView( View, LocationViewMixin, EntityViewMixin ):
location_view_id = request.view_parameters.location_view_id
location_view = LocationView.objects.get( id = location_view_id )
- # ``long_press`` signals that the gesture-based escape hatch
- # was used; in AUTOMATION views a tap fires one-click control,
- # so the long-press is the only way operators have to reach
- # status / history / edit for a controllable entity in that
- # view. The JS doesn't dictate which view to surface -- it
- # just reports the gesture -- and the server picks the route.
+ # ``long_press`` signals that the gesture-based escape hatch was
+ # used. It is the universal route back to the status modal: in
+ # AUTOMATION a tap fires one-click control, and in INFORMATION a
+ # tap opens the entity edit modal, so the long-press is the only
+ # way operators have to reach status / history / edit in those
+ # views. The JS doesn't dictate which view to surface -- it just
+ # reports the gesture -- and the server picks the route.
# ``str_to_bool`` tolerates ``1``/``true``/``yes``/``on``/etc.
# and returns False for a missing param.
long_press = str_to_bool( request.GET.get( 'long_press' ) )
+
+ # INFORMATION views default an entity tap to the edit (details /
+ # config) modal even when the entity has states, where DEFAULT /
+ # SECURITY would show status.
+ if ( not long_press
+ and location_view.location_view_type == LocationViewType.INFORMATION ):
+ return self._entity_edit_response(
+ request = request,
+ entity = entity,
+ )
+
if ( long_press
or location_view.location_view_type not in [ LocationViewType.AUTOMATION ] ):
return self._entity_status_response(
@@ -235,6 +247,10 @@ class LocationItemStatusView( View, LocationViewMixin, EntityViewMixin ):
def _entity_status_response( self, request : HttpRequest, entity : Entity ):
url = reverse( 'entity_status', kwargs = { 'entity_id': entity.id } )
return HttpResponseRedirect( url )
+
+ def _entity_edit_response( self, request : HttpRequest, entity : Entity ):
+ url = reverse( 'entity_edit', kwargs = { 'entity_id': entity.id } )
+ return HttpResponseRedirect( url )
class LocationEditView( HiModalView, LocationViewMixin, AttributeEditViewMixin ):
diff --git a/src/hi/apps/monitor/display_data.py b/src/hi/apps/monitor/display_data.py
index bbb9b009..aabe83f4 100644
--- a/src/hi/apps/monitor/display_data.py
+++ b/src/hi/apps/monitor/display_data.py
@@ -409,7 +409,11 @@ class EntityStateDisplayData:
# status display matches what the initial server-side
# template render produced (combined magnitude + unit
# suffix for unit-bearing values, raw value otherwise).
- status_value = str( self.latest_display_value )
+ # Lowercased so CSS ``[status="..."]`` selectors stay
+ # canonical regardless of the source value's original
+ # case — explicit StatusStyle constants are already
+ # lowercase, so this normalizes only the fallback path.
+ status_value = str( self.latest_display_value ).lower()
if not status_value:
status_value = StatusStyle.DEFAULT_STATUS_VALUE
return StatusStyle.default( status_value = status_value )
diff --git a/src/hi/apps/profiles/templates/profiles/modals/edit_reference_help.html b/src/hi/apps/profiles/templates/profiles/modals/edit_reference_help.html
index 7cf7af25..f7b69cee 100644
--- a/src/hi/apps/profiles/templates/profiles/modals/edit_reference_help.html
+++ b/src/hi/apps/profiles/templates/profiles/modals/edit_reference_help.html
@@ -34,12 +34,12 @@ Editing Help
<span class="action-description">Zoom in/out</span>
</li>
<li>
- <span class="action-method">S + Drag/Wheel</span>
- <span class="action-description">Scale mode</span>
+ <span class="action-method">CTRL+S + Drag/Wheel</span>
+ <span class="action-description">Scale the view</span>
</li>
<li>
- <span class="action-method">R + Drag/Wheel</span>
- <span class="action-description">Rotate mode</span>
+ <span class="action-method">CTRL+R + Drag/Wheel</span>
+ <span class="action-description">Rotate the view</span>
</li>
<li>
<span class="action-method">SHIFT + Drag</span>
@@ -95,9 +95,13 @@ Editing Help
<div class="help-actions-columns">
<ul class="help-actions">
<li>
- <span class="action-method">Click</span>
+ <span class="action-method">Click Path</span>
<span class="action-description">Select path to edit vertices</span>
</li>
+ <li>
+ <span class="action-method">Click Canvas</span>
+ <span class="action-description">Extend path (add vertex)</span>
+ </li>
<li>
<span class="action-method">Drag Point</span>
<span class="action-description">Move single vertex</span>
@@ -106,12 +110,12 @@ Editing Help
<span class="action-method">CTRL + Drag</span>
<span class="action-description">Move entire path</span>
</li>
+ </ul>
+ <ul class="help-actions">
<li>
<span class="action-method">I / INSERT</span>
<span class="action-description">Insert vertex</span>
</li>
- </ul>
- <ul class="help-actions">
<li>
<span class="action-method">X / DEL</span>
<span class="action-description">Delete vertex</span>
diff --git a/src/hi/hi_async_view.py b/src/hi/hi_async_view.py
index 90c8bc6f..051046fb 100644
--- a/src/hi/hi_async_view.py
+++ b/src/hi/hi_async_view.py
@@ -95,7 +95,7 @@ class HiSideView( HiAsyncView ):
referrer_query_params = urllib.parse.parse_qs( referrer_url.query )
if self.should_push_url():
referrer_query_params[self.SIDE_URL_PARAM_NAME] = side_url
- else:
+ elif self.SIDE_URL_PARAM_NAME in referrer_query_params:
del referrer_query_params[self.SIDE_URL_PARAM_NAME]
# parse_qs returns list-valued params; doseq=True emits each value
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index af004f26..8f36fc3e 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -156,8 +156,11 @@ class HassConverter:
HassApi.NEXT_DUSK_ID_SUFFIX,
HassApi.NEXT_DAWN_ID_SUFFIX,
- # Printer
+ # Printer (IPP)
HassApi.BLACK_CARTRIDGE_ID_SUFFIX,
+ HassApi.CYAN_CARTRIDGE_ID_SUFFIX,
+ HassApi.MAGENTA_CARTRIDGE_ID_SUFFIX,
+ HassApi.YELLOW_CARTRIDGE_ID_SUFFIX,
}
# Domains for controllable devices that support on/off operations
@@ -267,7 +270,17 @@ class HassConverter:
(HassApi.SENSOR_DOMAIN, HassApi.WIND_SPEED_DEVICE_CLASS, None): EntityStateType.WIND_SPEED,
(HassApi.SENSOR_DOMAIN, HassApi.TIMESTAMP_DEVICE_CLASS, None): EntityStateType.DATETIME,
(HassApi.SENSOR_DOMAIN, HassApi.ENUM_DEVICE_CLASS, None): EntityStateType.DISCRETE,
- (HassApi.SENSOR_DOMAIN, None, None): EntityStateType.BLOB, # Generic sensor
+ # Generic sensor (no device_class). DISCRETE rather than BLOB so
+ # history persists (BLOB is in EXCLUDE_FROM_SENSOR_HISTORY by design).
+ # HA's convention is that continuously-varying numeric sensors carry
+ # a device_class (temperature, humidity, power, battery, pressure,
+ # wind_speed, illuminance); a sensor without one is almost always
+ # status-like text (command_line script output, template sensor
+ # emitting a state string, custom integration reporting categorical
+ # state). DISCRETE is a heuristic — for the rare continuous case
+ # we trade range/unit affordances for history retention, which is
+ # the right call when history loss is the alternative.
+ (HassApi.SENSOR_DOMAIN, None, None): EntityStateType.DISCRETE,
# Other domains (read-only)
# Note: CAMERA_DOMAIN entities expose video_snapshot capability
@@ -2223,6 +2236,18 @@ class HassConverter:
return EntityType.LIGHT
return None
+ # Cartridge entity_id suffixes that identify an HA IPP printer
+ # device. Mirrors the printer entries in ``STATE_SUFFIXES`` — any
+ # state in the grouped device ending with one of these signals the
+ # device is a networked printer (HA's IPP integration emits one
+ # ``sensor.X_<color>_cartridge`` per installed cartridge).
+ _PRINTER_CARTRIDGE_SUFFIXES = (
+ HassApi.BLACK_CARTRIDGE_ID_SUFFIX,
+ HassApi.CYAN_CARTRIDGE_ID_SUFFIX,
+ HassApi.MAGENTA_CARTRIDGE_ID_SUFFIX,
+ HassApi.YELLOW_CARTRIDGE_ID_SUFFIX,
+ )
+
@classmethod
def hass_device_to_entity_type( cls, hass_device : HassDevice ) -> EntityType:
domain_set = hass_device.domain_set
@@ -2232,6 +2257,17 @@ class HassConverter:
return EntityType.CAMERA
if HassApi.WEATHER_DOMAIN in domain_set:
return EntityType.WEATHER_STATION
+ # Printer (IPP) — identified by the presence of any cartridge
+ # sensor in the grouped device. The cartridges and the primary
+ # state sensor share a short_name via the printer entries in
+ # STATE_SUFFIXES, so by the time we get here a printer device
+ # carries one to four cartridge states alongside its primary.
+ if any(
+ state.entity_id.endswith( suffix )
+ for state in hass_device.hass_state_list
+ for suffix in cls._PRINTER_CARTRIDGE_SUFFIXES
+ ):
+ return EntityType.PRINTER
if HassApi.TIMESTAMP_DEVICE_CLASS in device_class_set:
return EntityType.TIME_SOURCE
if ( HassApi.BINARY_SENSOR_DOMAIN in domain_set
diff --git a/src/hi/services/hass/hass_models.py b/src/hi/services/hass/hass_models.py
index b3c10e36..9ed32a83 100644
--- a/src/hi/services/hass/hass_models.py
+++ b/src/hi/services/hass/hass_models.py
@@ -91,8 +91,11 @@ class HassApi:
NEXT_NOON_ID_SUFFIX = '_next_noon'
NEXT_RISING_ID_SUFFIX = '_next_rising'
NEXT_SETTING_ID_SUFFIX = '_next_setting'
- # Printer
+ # Printer (IPP integration cartridge sensors)
BLACK_CARTRIDGE_ID_SUFFIX = '_black_cartridge'
+ CYAN_CARTRIDGE_ID_SUFFIX = '_cyan_cartridge'
+ MAGENTA_CARTRIDGE_ID_SUFFIX = '_magenta_cartridge'
+ YELLOW_CARTRIDGE_ID_SUFFIX = '_yellow_cartridge'
DEVICE_CLASS_ATTR = 'device_class'
FRIENDLY_NAME_ATTR = 'friendly_name'
diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.py
index 69a28026..f09c1179 100644
--- a/src/hi/simulator/management/commands/seed_sim_profiles.py
+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py
@@ -81,6 +81,7 @@ from hi.simulator.services.hass.sim_models import (
HassCameraSimEntityFields,
HassCarbonMonoxideDetectorFields,
HassColorSmartBulbFields,
+ HassCommandLineSensorFields,
HassFanFields,
HassGarageCoverFields,
HassGasDetectorFields,
@@ -99,8 +100,11 @@ from hi.simulator.services.hass.sim_models import (
HassOccupancyLightSensorFields,
HassOpeningSensorFields,
HassOutletFields,
+ HassPingFields,
HassPowerMeterFields,
HassPresenceSensorFields,
+ HassPrinterColorFields,
+ HassPrinterMonoFields,
HassSmartBulbFields,
HassSmokeDetectorFields,
HassSmokeDetectorWithBatteryFields,
@@ -329,6 +333,10 @@ class Command(BaseCommand):
self._add_hass_presence_sensor( profile, 'Zoo Presence' )
self._add_hass_opening_sensor( profile, 'Zoo Opening' )
self._add_hass_power_meter( profile, 'Zoo Power Meter' )
+ self._add_hass_command_line_sensor( profile, 'Zoo Command Line Sensor' )
+ self._add_hass_ping( profile, 'Zoo Ping', host = '192.168.1.10' )
+ self._add_hass_printer_mono( profile, 'Zoo Mono Printer' )
+ self._add_hass_printer_color( profile, 'Zoo Color Printer' )
self._add_hass_weather_station( profile, 'Zoo Weather Station' )
self._add_hass_occupancy_light_sensor( profile, 'Zoo Room Sensor' )
self._add_hass_water_leak_sensor( profile, 'Zoo Leak Sensor' )
@@ -1126,6 +1134,28 @@ class Command(BaseCommand):
fields_kwargs = {'name': name},
)
+ def _add_hass_command_line_sensor(self, profile, name, icon = 'mdi:console-line'):
+ self._create_db_entity(
+ profile = profile,
+ fields_class = HassCommandLineSensorFields,
+ sim_entity_type = SimEntityType.HEALTHCHECK,
+ fields_kwargs = {
+ 'name': name,
+ 'icon': icon,
+ },
+ )
+
+ def _add_hass_ping(self, profile, name, host = '192.168.1.1'):
+ self._create_db_entity(
+ profile = profile,
+ fields_class = HassPingFields,
+ sim_entity_type = SimEntityType.COMPUTER,
+ fields_kwargs = {
+ 'name': name,
+ 'host': host,
+ },
+ )
+
def _add_hass_power_meter(self, profile, name):
self._create_db_entity(
profile = profile,
@@ -1134,6 +1164,22 @@ class Command(BaseCommand):
fields_kwargs = {'name': name},
)
+ def _add_hass_printer_mono(self, profile, name):
+ self._create_db_entity(
+ profile = profile,
+ fields_class = HassPrinterMonoFields,
+ sim_entity_type = SimEntityType.PRINTER,
+ fields_kwargs = {'name': name},
+ )
+
+ def _add_hass_printer_color(self, profile, name):
+ self._create_db_entity(
+ profile = profile,
+ fields_class = HassPrinterColorFields,
+ sim_entity_type = SimEntityType.PRINTER,
+ fields_kwargs = {'name': name},
+ )
+
def _add_hass_weather_station(self, profile, name, temperature_unit = '°F'):
self._create_db_entity(
profile = profile,
diff --git a/src/hi/simulator/services/enums.py b/src/hi/simulator/services/enums.py
index 88ca59ae..55a27891 100644
--- a/src/hi/simulator/services/enums.py
+++ b/src/hi/simulator/services/enums.py
@@ -7,6 +7,7 @@ class SimStateType(LabeledEnum):
# General types
DISCRETE = ( 'Discrete' , 'Single value, fixed set of possible values' )
CONTINUOUS = ( 'Continuous' , 'For single value with a float type value' )
+ TEXT = ( 'Text' , 'Free-form string value (e.g., output of a shell command)' )
# Specific types
AIR_PRESSURE = ( 'Air Pressure' , '' )
@@ -89,6 +90,7 @@ class SimEntityType(LabeledEnum):
OPEN_CLOSE_SENSOR = ( 'Open/Close Sensor', '' )
OTHER = ( 'Other', '' ) # Will use generic visual element
PRESENCE_SENSOR = ( 'Presence Sensor', '' )
+ PRINTER = ( 'Printer', '' )
SEWER_LINE = ( 'Sewer Wire', '' )
SHOWER = ( 'Shower', '' )
SINK = ( 'Sink', '' )
diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.py
index 76849ed0..c4888253 100644
--- a/src/hi/simulator/services/hass/sim_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -1553,6 +1553,429 @@ class HassOpeningSensorState( HassState ):
}
+# --------------------------------------------------------------------------
+# Command Line Sensor (free-form string output)
+# --------------------------------------------------------------------------
+#
+# HA's ``command_line`` integration creates a ``sensor.x`` whose state is
+# whatever string the configured shell command emits to stdout (trimmed).
+# Typical homelab uses: RAID health check via SSH (``OK`` / ``Degraded`` /
+# ``Failed``), WAN IP lookup (``checkip.amazonaws.com``), certificate
+# expiry days, disk-space percentage, etc.
+#
+# The simulator represents this as a single TEXT state — the operator
+# types whatever string the command would have produced. ``icon`` is
+# operator-configurable since the YAML allows it per-sensor (e.g.,
+# ``mdi:harddisk`` for RAID, ``mdi:ip-network`` for WAN address).
+
+
+@dataclass( frozen = True )
+class HassCommandLineSensorFields( SimEntityFields ):
+ """Free-form ``sensor.x`` whose state is whatever string the
+ operator types in the simulator UI — mirrors HA's
+ ``command_line`` sensor (state = command stdout). ``icon`` and
+ ``unit_of_measurement`` are pass-through to the emitted
+ attributes."""
+ icon : str = 'mdi:console-line'
+ unit_of_measurement : str = ''
+
+
+@dataclass
+class HassCommandLineSensorState( HassState ):
+ sim_entity_fields : HassCommandLineSensorFields
+ sim_state_type : SimStateType = SimStateType.TEXT
+ sim_state_id : str = 'output'
+ value : str = 'OK'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Output'
+
+ @property
+ def entity_id(self):
+ return _sensor_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ # HA emits the command's stdout as the entity's state
+ # (string-typed). No coercion — pass through as-is.
+ return self.value
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ attrs = {
+ 'friendly_name': self.entity_name,
+ 'icon': self.sim_entity_fields.icon,
+ }
+ if self.sim_entity_fields.unit_of_measurement:
+ attrs[ 'unit_of_measurement' ] = self.sim_entity_fields.unit_of_measurement
+ return attrs
+
+
+# --------------------------------------------------------------------------
+# Printer (IPP)
+# --------------------------------------------------------------------------
+#
+# HA's IPP integration creates a primary ``sensor.<printer>`` for the
+# printer's overall state (HA wire vocabulary: ``idle`` / ``printing`` /
+# ``stopped``) plus per-cartridge ``sensor.<printer>_<color>`` percentage
+# sensors with ``unit_of_measurement='%'`` and no ``device_class``. Real
+# devices vary in cartridge count — mono lasers have just a black toner,
+# color lasers/inkjets have black + cyan + magenta + yellow. Modeled here
+# as two distinct entity types so the operator can exercise either shape.
+
+
+_PRINTER_STATE_CHOICES = [
+ ( 'idle' , 'Idle' ),
+ ( 'printing' , 'Printing' ),
+ ( 'stopped' , 'Stopped' ),
+]
+_PRINTER_STATE_OPTIONS = [ choice for choice, _label in _PRINTER_STATE_CHOICES ]
+
+
+def _printer_state_entity_id( name : str ) -> str:
+ return _sensor_entity_id( name )
+
+
+def _printer_cartridge_entity_id( name : str, color : str ) -> str:
+ # HA's IPP integration emits cartridge entity_ids with the
+ # ``_<color>_cartridge`` suffix (not just ``_<color>``). HI's
+ # converter groups by stripping these suffixes, so matching the
+ # wire format is required for the cartridges to fold into one
+ # HI Entity instead of importing as siblings.
+ return _sensor_entity_id( name, suffix = f'_{color}_cartridge' )
+
+
+def _printer_cartridge_attributes( entity_name : str, color : str ) -> dict:
+ """HA IPP cartridge attribute shape: ``%`` unit, ``measurement``
+ state class, plus the ``marker_*`` family that real printers report
+ (low_level / high_level thresholds and the cartridge type). Without
+ these, HI's import path can't distinguish a cartridge sensor from
+ any other generic percentage sensor."""
+ return {
+ 'friendly_name' : f'{entity_name} {color} cartridge',
+ 'marker_high_level' : 100,
+ 'marker_low_level' : 2,
+ 'marker_type' : 'toner-cartridge',
+ 'state_class' : 'measurement',
+ 'unit_of_measurement': '%',
+ }
+
+
+@dataclass( frozen = True )
+class HassPrinterMonoFields( SimEntityFields ):
+ """A monochrome IPP printer (B&W laser). Two states: printer
+ status (``sensor.<printer>``) and a single black toner level
+ (``sensor.<printer>_black``, percentage)."""
+ pass
+
+
+@dataclass( frozen = True )
+class HassPrinterColorFields( SimEntityFields ):
+ """A 4-cartridge color IPP printer (color laser or inkjet). Status
+ state plus four 0-100% cartridge levels — black + cyan + magenta +
+ yellow — each as a separate ``sensor.<printer>_<color>`` entity."""
+ pass
+
+
+def _printer_status_attributes( entity_name : str ) -> dict:
+ """HA IPP primary state attribute shape: ``device_class=enum`` with
+ an ``options`` list of valid states. HI's converter routes this to
+ ``EntityStateType.DISCRETE`` via the explicit ENUM device_class
+ mapping (rather than the no-device-class fallback)."""
+ return {
+ 'device_class' : 'enum',
+ 'friendly_name': entity_name,
+ 'icon' : 'mdi:printer',
+ 'options' : list( _PRINTER_STATE_OPTIONS ),
+ }
+
+
+@dataclass
+class HassPrinterMonoStatusState( HassState ):
+ sim_entity_fields : HassPrinterMonoFields
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ sim_state_id : str = 'state'
+ value : str = 'idle'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} State'
+
+ @property
+ def entity_id(self):
+ return _printer_state_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ] ]:
+ return _PRINTER_STATE_CHOICES
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return _printer_status_attributes( self.entity_name )
+
+
+@dataclass
+class HassPrinterMonoBlackState( HassState ):
+ sim_entity_fields : HassPrinterMonoFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'black'
+ value : str = '85'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Black'
+
+ @property
+ def entity_id(self):
+ return _printer_cartridge_entity_id( self.entity_name, 'black' )
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return _printer_cartridge_attributes( self.entity_name, 'black' )
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 100
+
+ @property
+ def display_unit(self) -> str:
+ return '%'
+
+
+@dataclass
+class HassPrinterColorStatusState( HassState ):
+ sim_entity_fields : HassPrinterColorFields
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ sim_state_id : str = 'state'
+ value : str = 'idle'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} State'
+
+ @property
+ def entity_id(self):
+ return _printer_state_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ] ]:
+ return _PRINTER_STATE_CHOICES
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return _printer_status_attributes( self.entity_name )
+
+
+@dataclass
+class HassPrinterColorBlackState( HassState ):
+ sim_entity_fields : HassPrinterColorFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'black'
+ value : str = '85'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Black'
+
+ @property
+ def entity_id(self):
+ return _printer_cartridge_entity_id( self.entity_name, 'black' )
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return _printer_cartridge_attributes( self.entity_name, 'black' )
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 100
+
+ @property
+ def display_unit(self) -> str:
+ return '%'
+
+
+@dataclass
+class HassPrinterColorCyanState( HassState ):
+ sim_entity_fields : HassPrinterColorFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'cyan'
+ value : str = '75'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Cyan'
+
+ @property
+ def entity_id(self):
+ return _printer_cartridge_entity_id( self.entity_name, 'cyan' )
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return _printer_cartridge_attributes( self.entity_name, 'cyan' )
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 100
+
+ @property
+ def display_unit(self) -> str:
+ return '%'
+
+
+@dataclass
+class HassPrinterColorMagentaState( HassState ):
+ sim_entity_fields : HassPrinterColorFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'magenta'
+ value : str = '60'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Magenta'
+
+ @property
+ def entity_id(self):
+ return _printer_cartridge_entity_id( self.entity_name, 'magenta' )
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return _printer_cartridge_attributes( self.entity_name, 'magenta' )
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 100
+
+ @property
+ def display_unit(self) -> str:
+ return '%'
+
+
+@dataclass
+class HassPrinterColorYellowState( HassState ):
+ sim_entity_fields : HassPrinterColorFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'yellow'
+ value : str = '40'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Yellow'
+
+ @property
+ def entity_id(self):
+ return _printer_cartridge_entity_id( self.entity_name, 'yellow' )
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return _printer_cartridge_attributes( self.entity_name, 'yellow' )
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 100
+
+ @property
+ def display_unit(self) -> str:
+ return '%'
+
+
+# --------------------------------------------------------------------------
+# Ping (ICMP) connectivity sensor
+# --------------------------------------------------------------------------
+#
+# HA's Ping integration creates one ``binary_sensor.X`` per host with
+# ``device_class=connectivity``. ``'on'`` means the host is reachable,
+# ``'off'`` means unreachable (HA's connectivity convention). The
+# ``host`` field carries the IP/hostname being pinged, emitted as an
+# entity attribute so HI can surface it on the device tile. Common
+# homelab use: tracking up/down for servers, NAS, routers, APs.
+
+
+@dataclass( frozen = True )
+class HassPingFields( SimEntityFields ):
+ """A Ping (ICMP) connectivity sensor — single binary_sensor with
+ ``device_class=connectivity``. ``host`` is the target being
+ pinged (informational; emitted as the ``host`` attribute)."""
+ host : str = '192.168.1.1'
+
+
+@dataclass
+class HassPingState( HassState ):
+ sim_entity_fields : HassPingFields
+ sim_state_type : SimStateType = SimStateType.CONNECTIVITY
+ sim_state_id : str = 'ping'
+ value : str = 'on'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Ping'
+
+ @property
+ def entity_id(self):
+ return _binary_sensor_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'on' if str_to_bool( self.value ) else 'off'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return {
+ 'device_class': 'connectivity',
+ 'friendly_name': self.entity_name,
+ 'host': self.sim_entity_fields.host,
+ 'icon': 'mdi:lan-connect',
+ }
+
+
# --------------------------------------------------------------------------
# Power meter (numeric ``sensor.x`` with ``device_class=power``)
# --------------------------------------------------------------------------
@@ -3269,6 +3692,43 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [
HassOpeningSensorState,
],
),
+ SimEntityDefinition(
+ class_label = 'Command Line Sensor',
+ sim_entity_type = SimEntityType.HEALTHCHECK,
+ sim_entity_fields_class = HassCommandLineSensorFields,
+ sim_state_class_list = [
+ HassCommandLineSensorState,
+ ],
+ ),
+ SimEntityDefinition(
+ class_label = 'Printer (IPP, Mono)',
+ sim_entity_type = SimEntityType.PRINTER,
+ sim_entity_fields_class = HassPrinterMonoFields,
+ sim_state_class_list = [
+ HassPrinterMonoStatusState,
+ HassPrinterMonoBlackState,
+ ],
+ ),
+ SimEntityDefinition(
+ class_label = 'Printer (IPP, Color)',
+ sim_entity_type = SimEntityType.PRINTER,
+ sim_entity_fields_class = HassPrinterColorFields,
+ sim_state_class_list = [
+ HassPrinterColorStatusState,
+ HassPrinterColorBlackState,
+ HassPrinterColorCyanState,
+ HassPrinterColorMagentaState,
+ HassPrinterColorYellowState,
+ ],
+ ),
+ SimEntityDefinition(
+ class_label = 'Ping (ICMP)',
+ sim_entity_type = SimEntityType.COMPUTER,
+ sim_entity_fields_class = HassPingFields,
+ sim_state_class_list = [
+ HassPingState,
+ ],
+ ),
SimEntityDefinition(
class_label = 'Power Meter',
sim_entity_type = SimEntityType.ELECTRICY_METER,
diff --git a/src/hi/simulator/services/templates/services/panes/sim_control_connectivity.html b/src/hi/simulator/services/templates/services/panes/sim_control_connectivity.html
new file mode 100644
index 00000000..b33d7b39
--- /dev/null
+++ b/src/hi/simulator/services/templates/services/panes/sim_control_connectivity.html
@@ -0,0 +1,8 @@
+DOWN
+<label class="switch">
+ <input type="checkbox" name="value"
+ {% if sim_state.is_on %}checked="true"{% endif %}
+ onchange-async="true" >
+ <span class="slider"></span>
+</label>
+UP
diff --git a/src/hi/simulator/services/templates/services/panes/sim_control_text.html b/src/hi/simulator/services/templates/services/panes/sim_control_text.html
new file mode 100644
index 00000000..b008c56e
--- /dev/null
+++ b/src/hi/simulator/services/templates/services/panes/sim_control_text.html
@@ -0,0 +1,3 @@
+<input type="text" name="value" class="form-control form-control-sm"
+ value="{{ sim_state.value|default_if_none:'' }}"
+ onchange-async="true">
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index 75e61816..bb6481c3 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -986,12 +986,20 @@ g[status="off"] path.hi-state-bg {
* source order. Previously this sat after on/off/dim and silently
* clobbered them. */
.hi-status-display[status] {
+ display: inline-block;
color: var(--black);
background-color: var(--white);
- border-color: var(--black);
- border-style: solid;
- border-width: 2px;
- border-radius: 8px;
+ border: 1px solid var(--black);
+ border-radius: 4px;
+ padding: 1px 8px;
+ font-size: 0.9em;
+ line-height: 1.4;
+ width: 10em;
+ text-align: center;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ box-sizing: border-box;
}
.hi-status-display[status="off"] {
color: var(--on-status-off-color);
@@ -1060,78 +1068,26 @@ g[status="connected"] {
g[status="disconnected"] {
filter: drop-shadow(0 0 5px var(--status-bad-color));
}
-g[status="high"] {
- filter: drop-shadow(0 0 5px var(--status-ok-color));
-}
-g[status="low"] {
- filter: drop-shadow(0 0 5px var(--status-bad-color));
-}
-g[status="smoke_detected"] {
- filter: drop-shadow(0 0 5px var(--status-bad-color));
-}
-g[status="moisture_detected"] {
- filter: drop-shadow(0 0 5px var(--status-bad-color));
-}
-g[status="co_detected"] {
- filter: drop-shadow(0 0 5px var(--status-bad-color));
-}
-g[status="gas_detected"] {
- filter: drop-shadow(0 0 5px var(--status-bad-color));
-}
-g[status="temperature_cold"] {
- filter: drop-shadow(0 0 5px var(--status-temp-cold-color));
-}
-g[status="temperature_cool"] {
- filter: drop-shadow(0 0 5px var(--status-temp-cool-color));
-}
-g[status="temperature_pleasant"] {
- filter: drop-shadow(0 0 5px var(--status-temp-pleasant-color));
-}
-g[status="temperature_warm"] {
- filter: drop-shadow(0 0 5px var(--status-temp-warm-color));
-}
-g[status="temperature_hot"] {
- filter: drop-shadow(0 0 5px var(--status-temp-hot-color));
-}
-
-
-.hi-status-display[status="active"] {
- color: var(--on-status-active-color);
- background-color: var(--status-active-color);
+g[status="degraded"] {
+ filter: drop-shadow(0 0 5px var(--status-recent-color));
}
-.hi-status-display[status="idle"] {
+.hi-status-display[status="raid_ok"],
+.hi-status-display[status="connected"] {
color: var(--on-status-ok-color);
background-color: var(--status-ok-color);
}
-.hi-status-display[status="recent"] {
- color: var(--on-status-recent-color);
- background-color: var(--status-recent-color);
-}
-.hi-status-display[status="past"] {
- color: var(--on-status-past-color);
- background-color: var(--status-past-color);
-}
-.hi-status-display[status="partial"] {
+.hi-status-display[status="printing"],
+.hi-status-display[status="degraded"] {
color: var(--on-status-recent-color);
background-color: var(--status-recent-color);
}
-.hi-status-display[status="open"] {
- color: var(--on-status-bad-color);
- background-color: var(--status-bad-color);
-}
-.hi-status-display[status="closed"] {
- color: var(--on-status-idle-color);
- background-color: var(--status-idle-color);
-}
-.hi-status-display[status="RAID_OK"],
-.hi-status-display[status="connected"] {
- color: var(--on-status-ok-color);
- background-color: var(--status-ok-color);
-}
+.hi-status-display[status="stopped"],
+.hi-status-display[status="failed"],
.hi-status-display[status="disconnected"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
+.hi-status-display[status="idle"],
.hi-status-display[status="ok"],
.hi-status-display[status="high"] {
color: var(--on-status-ok-color);
@@ -2099,6 +2055,17 @@ g[hover] {
.collection-tile-grid--small .entity-card--tile {
min-height: var(--hi-panel-tile-small-min-size);
}
+/* Sensor value chips inside the SMALL grid: the universal chip width
+ * (10em) overflows the narrower cells produced by
+ * --hi-panel-tile-small-min-size, so values truncate at the right edge.
+ * Scoping by the wrapper class keeps this shrinkage isolated — GRID,
+ * GRID_LARGE, LIST, and modal contexts continue to use the universal
+ * chip metrics defined in .hi-status-display[status]. */
+.collection-tile-grid--small .hi-status-display[status] {
+ width: 8em;
+ font-size: 0.8em;
+ padding: 1px 6px;
+}
.collection-default {
grid-template-columns: repeat(
auto-fit, minmax(var(--hi-panel-default-tile-min-size), 1fr)
@@ -2169,6 +2136,12 @@ g[hover] {
* visible below the panel content. */
display: grid;
min-height: var(--hi-panel-tile-min-size);
+ /* Override the default ``min-width: auto`` on grid items — without
+ * this, long content (entity names, status chips) expands the cell
+ * past its 1fr column width, then ``.entity-card { overflow: hidden }``
+ * clips raw on the right rather than letting children truncate with
+ * ellipsis. */
+ min-width: 0;
}
.entity-card--row {
diff --git a/src/hi/static/js/entity-picker.js b/src/hi/static/js/entity-picker.js
index c0390429..eb1fc7b6 100644
--- a/src/hi/static/js/entity-picker.js
+++ b/src/hi/static/js/entity-picker.js
@@ -16,9 +16,8 @@ $(document).ready(function() {
var $items = $(Hi.ENTITY_PICKER_FILTERABLE_ITEM_SELECTOR);
var $groups = $(Hi.ENTITY_PICKER_GROUP_SECTION_SELECTOR);
var self = this;
-
- // Reset all groups to visible first
- $groups.show();
+ var filtersActive = ( self.searchTerm !== ''
+ || self.currentFilter !== Hi.ENTITY_PICKER_FILTER_ALL );
$items.each(function() {
var $item = $(this);
@@ -62,14 +61,39 @@ $(document).ready(function() {
$item.toggle(show);
});
- // Show/hide groups based on visible items
+ // Show/hide groups based on items that MATCH the current
+ // filter -- using each item's own display rather than
+ // ':visible'. A collapsed group's items are display:none via
+ // Bootstrap's .collapse, so ':visible' reports zero matches
+ // and would wrongly hide an otherwise-matching group (and
+ // never reveal its matches). While a search/filter is active
+ // we also force a matching group's body open so its matches
+ // are actually shown; when cleared, we drop the override so
+ // the group's own collapsed/expanded state governs again.
$groups.each(function() {
var $group = $(this);
- var $visibleItems = $group.find(Hi.ENTITY_PICKER_FILTERABLE_ITEM_SELECTOR + ':visible');
- if ($visibleItems.length > 0) {
- $group.show();
- } else {
+ var $body = $group.find('.entity-group-items');
+ var $header = $group.find('.entity-group-header');
+ var matchCount = $group.find(Hi.ENTITY_PICKER_FILTERABLE_ITEM_SELECTOR).filter(function() {
+ return this.style.display !== 'none';
+ }).length;
+
+ if (matchCount === 0) {
$group.hide();
+ $body.css('display', '');
+ return;
+ }
+
+ $group.show();
+ if (filtersActive) {
+ // Reveal matches even inside a collapsed group.
+ $body.css('display', 'block');
+ $header.attr('aria-expanded', 'true');
+ } else {
+ // Restore the group's own collapse state (default or
+ // user-toggled), tracked by Bootstrap's 'show' class.
+ $body.css('display', '');
+ $header.attr('aria-expanded', $body.hasClass('show') ? 'true' : 'false');
}
});
},
diff --git a/src/hi/static/js/svg-entity-edit.js b/src/hi/static/js/svg-entity-edit.js
index 410aa5f9..aa7ba828 100644
--- a/src/hi/static/js/svg-entity-edit.js
+++ b/src/hi/static/js/svg-entity-edit.js
@@ -344,20 +344,14 @@
return Hi.SvgPanZoomCore.handleMouseWheel( event );
},
handleClick: function( event ) {
- /* Pan-zoom click suppression (after drag) must be checked first. */
- var suppressed = Hi.SvgPanZoomCore.handleClick( event );
- if ( suppressed ) { return true; }
-
- /* Select the location view SVG on background click — clear other selections. */
- if ( $( event.target ).closest( Hi.LOCATION_VIEW_BASE_SELECTOR ).length > 0 ) {
- var closest = $( event.target ).closest( Hi.LOCATION_VIEW_SVG_SELECTOR );
- if ( closest.length > 0 ) {
- Hi.SvgIconCore.clearSelection();
- Hi.SvgPathCore.clearSelection();
- return true;
- }
- }
- return false;
+ /* Location only suppresses the trailing click after a pan/scale/
+ rotate drag. A click on empty canvas is deliberately NOT
+ consumed here: it falls through to the path module so that,
+ while a path is being edited, clicking extends it (open or
+ closed paths alike). Deselecting is done with Escape -- a stray
+ background click no longer clears the icon/path selection or
+ exits path editing. */
+ return Hi.SvgPanZoomCore.handleClick( event );
},
handleLongPress: function( event ) {
return false;
diff --git a/src/hi/static/js/svg-icon-core.js b/src/hi/static/js/svg-icon-core.js
index 146c0361..0b42a3fc 100644
--- a/src/hi/static/js/svg-icon-core.js
+++ b/src/hi/static/js/svg-icon-core.js
@@ -175,11 +175,15 @@
if ( ! gSelectedGroup ) { return false; }
if ( ! isPointerInArea() ) { return false; }
- if ( event.key === ICON_ACTION_SCALE_KEY ) {
+ /* Plain s/r scale/rotate the SELECTED icon. Ctrl+s / Ctrl+r are
+ reserved as the global canvas transforms: let them fall through
+ (return false below) to the pan/zoom core so the canvas can be
+ scaled/rotated without first deselecting the icon. */
+ if ( event.key === ICON_ACTION_SCALE_KEY && ! event.ctrlKey ) {
rotateAbort();
startScale();
- } else if ( event.key === ICON_ACTION_ROTATE_KEY ) {
+ } else if ( event.key === ICON_ACTION_ROTATE_KEY && ! event.ctrlKey ) {
scaleAbort();
startRotate();
diff --git a/src/hi/static/js/svg-path-core.js b/src/hi/static/js/svg-path-core.js
index aa46758b..f23e4b3c 100644
--- a/src/hi/static/js/svg-path-core.js
+++ b/src/hi/static/js/svg-path-core.js
@@ -31,7 +31,8 @@
const PATH_ACTION_DELETE_KEY_CODES = [ 88, 8, 46 ]; // x, Backspace, Delete
const PATH_ACTION_INSERT_KEY_CODES = [ 73, 45 ]; // i, Insert
- const PATH_ACTION_ADD_KEY_CODES = [ 65, 61 ]; // a, +
+ const PATH_ACTION_ADD_KEY_CODES = [ 65, 61 ]; // a, + (legacy keyCode; 61 is Firefox-only for '+')
+ const PATH_ACTION_ADD_KEYS = [ 'a', '+', '=' ]; // event.key: browser-independent (Chrome/Safari report '+' as keyCode 187, not 61)
const PATH_ACTION_END_KEY_CODES = [ 27 ]; // Escape
const CURSOR_MOVEMENT_THRESHOLD_PIXELS = 3;
@@ -268,7 +269,8 @@
if ( $( event.target ).closest( '.modal' ).length > 0 ) { return false; }
if ( ! gSvgPathEditData ) { return false; }
- if ( PATH_ACTION_ADD_KEY_CODES.indexOf( event.keyCode ) >= 0 ) {
+ if ( PATH_ACTION_ADD_KEYS.indexOf( event.key ) >= 0
+ || PATH_ACTION_ADD_KEY_CODES.indexOf( event.keyCode ) >= 0 ) {
addProxyPath();
return true;
diff --git a/src/hi/static/state_panels/fallback/fallback.css b/src/hi/static/state_panels/fallback/fallback.css
index 640a33b2..eeed4c92 100644
--- a/src/hi/static/state_panels/fallback/fallback.css
+++ b/src/hi/static/state_panels/fallback/fallback.css
@@ -17,6 +17,13 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
+ /* Override default ``min-width: auto`` on flex items — without this,
+ * ``text-overflow: ellipsis`` never triggers because the flex item
+ * refuses to shrink below its content's intrinsic width. Combined
+ * with ``max-width: 100%`` (and the parent's own min-width: 0), the
+ * name finally respects the grid cell boundary. */
+ min-width: 0;
+ max-width: 100%;
}
/* Per-state compact block: label above value/control. Both contexts
@@ -70,9 +77,11 @@
font-size: 1rem;
}
.hi-state-panel-fallback--row .state-compact {
- flex: 1 1 0;
+ flex: 0 1 auto;
min-width: 0;
max-width: 280px;
+ margin-left: auto;
+ align-items: flex-end;
}
/* TILE: icon centered atop name; states stacked vertically below. */
@@ -83,6 +92,10 @@
gap: 6px;
padding: 12px;
text-align: center;
+ /* Allow this grid-item-as-flex-container to shrink below its
+ * content's intrinsic width so name truncation propagates from
+ * the cell boundary all the way to ``.hi-state-panel-fallback__name``. */
+ min-width: 0;
}
.hi-state-panel-fallback--tile .hi-state-panel-fallback__icon {
width: 48px;