Let every screen choose its top bar: clocks, date and entities (0.2.38)

The name stays on the left; up to six items go on the right: the time, an
analog clock, the date, or a Home Assistant entity with its icon, showing its
state or how long ago it changed, always or only while active. The add-on
formats entity text in Dutch and sends it as op: header right after the layout
to firmware 0.2.32+; older firmware keeps the clock of show_clock, which now
follows the clock item.

The firmware draws every value in one font on the name's baseline, centres
icons and the dial on the digit height and measures gaps between glyph ink, so
the bar looks even; the editor's mockup uses Roboto and the same integer rules.
tools/render_topbar.py renders the real LVGL code on a computer (ESPHome host +
SDL2). The editor's section buttons are gone.

Firmware 0.2.32 for both boards.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Max Gramser
2026-09-14 18:38:49 +02:00
parent ae308e37ab
commit 3f6889f750
25 changed files with 2365 additions and 94 deletions
+65 -5
View File
@@ -16,7 +16,7 @@ WEEKDAYS = ['ma', 'di', 'wo', 'do', 'vr', 'za', 'zo']
REPO = 'https://github.com/MaxGramser/homeassistant_espscreen'
REFS = {'cyd': 'main', 'guition': 'main'}
# Firmware shipped with this app release; screens below it get an update offer.
FIRMWARE_VERSION = '0.2.31'
FIRMWARE_VERSION = '0.2.32'
ATTRS = frozenset('brightness percentage current_position current_temperature temperature current_humidity min_temp max_temp target_temp_step supported_color_modes hvac_modes hvac_action hs_color color_temp_kelvin min_color_temp_kelvin max_color_temp_kelvin fan_speed_list unit_of_measurement battery_level fan_speed volume_level is_volume_muted media_title options min max step temperature_unit supported_features device_class next_rising next_setting finishes_at duration remaining humidity wind_speed wind_speed_unit apparent_temperature fan_modes swing_modes fan_mode swing_mode'.split())
# Attributes whose boolean value the screen needs; every other bool stays behind.
BOOL_ATTRS = frozenset(['is_volume_muted'])
@@ -149,6 +149,59 @@ def entity_id(value):
return False
return value in BUILTIN if value.startswith('screen.') else value.split('.')[0] in DOMAINS
# ----- Top bar (firmware 0.2.32+): the screen name on the left, up to six items on the right.
# Without a `header` the screen keeps its name and the clock of `show_clock`. -----
HEADER_MIN_FIRMWARE = (0, 2, 32)
HEADER_MAX_ITEMS = 6
# Items the screen draws on its own clock, without Home Assistant.
HEADER_BUILTIN = {'clock': 'Tijd', 'analog': 'Analoge klok', 'date': 'Datum'}
# Only shown, never controlled: the top bar takes these besides every tile domain.
HEADER_ONLY_DOMAINS = frozenset('device_tracker zone lock alarm_control_panel counter event input_datetime input_text water_heater humidifier'.split())
HEADER_CONTENTS = ('state', 'last_changed')
HEADER_SHOWS = ('always', 'active')
def header_entity(value):
return (isinstance(value, str) and len(value) <= 120 and re.fullmatch(r'[a-z0-9_]+\.[a-z0-9_]+', value) is not None
and value.split('.')[0] in (DOMAINS - {'screen'}) | HEADER_ONLY_DOMAINS)
def header_items(layout):
"""Items the top bar shows: the stored ones, else what firmware before the top bar drew (the clock)."""
if 'header' in layout:
return layout['header']['items']
return [{'type': 'clock'}] if layout.get('settings', {}).get('show_clock', True) else []
def validate_header(data):
if not isinstance(data, dict) or set(data) - {'items'} or not isinstance(data.get('items'), list):
raise ValueError('Ongeldige bovenbalk; vernieuw de beheerpagina.')
if len(data['items']) > HEADER_MAX_ITEMS:
raise ValueError(f'De bovenbalk heeft plaats voor maximaal {HEADER_MAX_ITEMS} onderdelen.')
items, seen = [], set()
for item in data['items']:
kind = item.get('type') if isinstance(item, dict) else None
if kind in HEADER_BUILTIN:
if set(item) != {'type'}:
raise ValueError('Ongeldige instelling in de bovenbalk.')
clean = {'type': kind}
elif kind == 'entity':
if set(item) - {'type', 'entity', 'content', 'icon', 'show'}:
raise ValueError('Onbekende instelling in de bovenbalk; vernieuw de beheerpagina.')
if not header_entity(item.get('entity')):
raise ValueError('Deze entiteit kan niet in de bovenbalk.')
clean = {'type': 'entity', 'entity': item['entity'], 'content': item.get('content', 'state'),
'icon': item.get('icon', 'auto'), 'show': item.get('show', 'always')}
if clean['content'] not in HEADER_CONTENTS or clean['show'] not in HEADER_SHOWS:
raise ValueError('Ongeldige instelling in de bovenbalk.')
if not (clean['icon'] in ('auto', 'none') or isinstance(clean['icon'], str) and clean['icon'] in tile_icons.ICONS):
raise ValueError('Kies een icoon uit de lijst.')
else:
raise ValueError('Onbekend onderdeel in de bovenbalk; vernieuw de beheerpagina.')
key = json.dumps(clean, sort_keys=True)
if key in seen:
raise ValueError('Dit onderdeel staat al in de bovenbalk.')
seen.add(key)
items.append(clean)
return {'items': items}
def min_firmware(layout):
"""Oldest firmware that still accepts this layout; None when any version works."""
if any(t.get('options', {}).get('background') == 'none' for t in layout['tiles']):
@@ -238,6 +291,8 @@ def validate_layout(data):
result['pages'] = data['pages']
if 'settings' in data:
result['settings'] = validate_settings(data['settings'])
if 'header' in data:
result['header'] = validate_header(data['header'])
return result
def local_clock(value, tz):
@@ -461,17 +516,22 @@ def discover(registry, states, devices, areas):
'device': device.get('name') or '',
'area': area, 'online': state.get('state') not in (None, 'unknown', 'unavailable'),
'status': state.get('state', 'Niet verbonden')})
if not entity_id(eid) or item.get('disabled_by'):
tile = entity_id(eid)
if not (tile or header_entity(eid)) or item.get('disabled_by'):
continue
entities.append({'id': eid, 'name': state.get('attributes', {}).get('friendly_name') or item.get('name') or item.get('original_name') or eid,
'device': device.get('name_by_user') or device.get('name') or '', 'area': area,
'state': state.get('state', 'unavailable'), 'icon': tile_icons.ha_icon(state.get('attributes'))})
'state': state.get('state', 'unavailable'), 'icon': tile_icons.ha_icon(state.get('attributes')),
# Top-bar-only domains (a phone's tracker, a lock) stay out of the tile picker.
**({} if tile else {'tile': False})})
# YAML entities may not have an entity-registry entry.
registered = {e['id'] for e in entities}
in_registry = {r['entity_id'] for r in registry}
for eid, state in states.items():
if entity_id(eid) and eid not in registered and not any(r['entity_id'] == eid for r in registry):
tile = entity_id(eid)
if (tile or header_entity(eid)) and eid not in registered and eid not in in_registry:
entities.append({'id': eid, 'name': state.get('attributes', {}).get('friendly_name', eid), 'device': '', 'area': '', 'state': state['state'],
'icon': tile_icons.ha_icon(state.get('attributes'))})
'icon': tile_icons.ha_icon(state.get('attributes')), **({} if tile else {'tile': False})})
return screens, sorted(entities, key=lambda e: e['name'].casefold())
def installation_yaml(data):
+342
View File
@@ -0,0 +1,342 @@
"""Top bar of a screen ("bovenbalk"): what the firmware draws right of the screen name.
Firmware 0.2.32+ only draws. This module decides everything that needs Home Assistant: an
entity's text in Dutch (number format, units, translated states), its icon, its accent colour
and whether it shows at all. Clock, analog clock and date tick on the screen itself, and a
relative time ("5 min geleden") travels as a unix time, so the screen counts the minutes
without any traffic.
Wire format, one message after the layout: {"v":1,"op":"header","items":[...]} with per item
"k" (clock, analog, date, text, ago), "i" (icon codepoint), "t" (text), "e" (unix time) and
"c" (accent colour RRGGBB).
"""
import math
import unicodedata
from datetime import datetime, time
import tile_icons
from core import HEADER_BUILTIN, HEADER_CONTENTS, HEADER_MAX_ITEMS, HEADER_MIN_FIRMWARE, HEADER_SHOWS, epoch, header_items, local_clock, short
# Characters the top bar's text font carries on both boards (`sublabel_big` in the profiles;
# tests/test_header_bar.py keeps them equal). Anything else folds to its base letter or goes.
GLYPHS = frozenset("<>—&@!,.?\"%()+-_:°0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyzäöüÄÖÜß/…·'#*=;²³µéèëêïîóôàáâçñúû–")
TEXT_BYTES = 40
MONTHS = ('jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec')
UNAVAILABLE = '—'
CONTENT_LABELS = {'state': 'Status', 'last_changed': 'Laatst gewijzigd'}
SHOW_LABELS = {'always': 'Altijd', 'active': 'Alleen als actief'}
# Home Assistant's own words where they fit a small bar; the screen shows the rest as they come.
STATES = {
'on': 'Aan', 'off': 'Uit', 'home': 'Thuis', 'not_home': 'Weg', 'open': 'Open', 'closed': 'Dicht',
'opening': 'Gaat open', 'closing': 'Gaat dicht', 'locked': 'Op slot', 'unlocked': 'Open', 'locking': 'Sluiten',
'unlocking': 'Openen', 'jammed': 'Vast', 'playing': 'Speelt', 'paused': 'Pauze', 'idle': 'Inactief',
'standby': 'Stand-by', 'buffering': 'Laden', 'cleaning': 'Bezig', 'docked': 'In dock', 'returning': 'Naar dock',
'error': 'Fout', 'heat': 'Verwarmen', 'cool': 'Koelen', 'heat_cool': 'Auto', 'auto': 'Auto', 'dry': 'Drogen',
'fan_only': 'Ventileren', 'disarmed': 'Uit', 'armed_home': 'Thuis', 'armed_away': 'Afwezig', 'armed_night': 'Nacht',
'armed_vacation': 'Vakantie', 'armed_custom_bypass': 'Aan', 'arming': 'Inschakelen', 'pending': 'Wachten',
'triggered': 'Alarm', 'active': 'Loopt', 'above_horizon': 'Op', 'below_horizon': 'Onder',
}
# device_class: (on, off)
BINARY_STATES = {
'battery': ('Laag', 'Normaal'), 'battery_charging': ('Laden', 'Niet laden'), 'carbon_monoxide': ('Gevaar', 'Veilig'),
'cold': ('Koud', 'Normaal'), 'connectivity': ('Verbonden', 'Verbroken'), 'door': ('Open', 'Dicht'),
'garage_door': ('Open', 'Dicht'), 'gas': ('Gevaar', 'Veilig'), 'heat': ('Heet', 'Normaal'), 'light': ('Licht', 'Donker'),
'lock': ('Open', 'Op slot'), 'moisture': ('Nat', 'Droog'), 'motion': ('Beweging', 'Geen beweging'),
'moving': ('Beweegt', 'Stil'), 'occupancy': ('Bezet', 'Vrij'), 'opening': ('Open', 'Dicht'), 'plug': ('Aangesloten', 'Los'),
'power': ('Aan', 'Uit'), 'presence': ('Thuis', 'Weg'), 'problem': ('Probleem', 'OK'), 'running': ('Actief', 'Inactief'),
'safety': ('Onveilig', 'Veilig'), 'smoke': ('Rook', 'Geen rook'), 'sound': ('Geluid', 'Stil'), 'tamper': ('Sabotage', 'OK'),
'update': ('Update', 'Bijgewerkt'), 'vibration': ('Trilling', 'Stil'), 'window': ('Open', 'Dicht'),
}
# Icon names from tile_icons; the fonts of both boards carry every one of them.
BINARY_ICONS = { # device_class: (on, off)
'motion': ('motion-sensor', 'motion-sensor'), 'occupancy': ('home-account', 'home-account'),
'presence': ('home-account', 'home-account'), 'door': ('door-open', 'door-closed'), 'garage_door': ('garage', 'garage'),
'opening': ('door-open', 'door-closed'), 'window': ('window-closed-variant', 'window-closed-variant'),
'connectivity': ('router-wireless', 'router-wireless'), 'plug': ('power-plug', 'power-plug'), 'power': ('flash', 'flash'),
'moisture': ('water-alert', 'water'), 'smoke': ('smoke-detector', 'smoke-detector'), 'gas': ('meter-gas', 'meter-gas'),
'carbon_monoxide': ('smoke-detector', 'smoke-detector'), 'lock': ('lock-open-variant', 'lock'),
'battery': ('battery-high', 'battery-high'), 'battery_charging': ('battery-high', 'battery-high'),
'problem': ('alert-outline', 'check'), 'safety': ('alert-outline', 'check'), 'tamper': ('alert-outline', 'check'),
'vibration': ('alert-outline', 'check'), 'heat': ('fire', 'fire'), 'cold': ('snowflake', 'snowflake'),
'light': ('weather-sunny', 'weather-night'), 'running': ('play', 'stop'), 'sound': ('music-note', 'music-note'),
'update': ('cog', 'cog'), 'moving': ('run', 'run'),
}
SENSOR_ICONS = {
'temperature': 'thermometer', 'humidity': 'water-percent', 'moisture': 'water-percent', 'power': 'flash', 'energy': 'flash',
'apparent_power': 'flash', 'reactive_power': 'flash', 'voltage': 'flash', 'current': 'flash', 'power_factor': 'flash',
'battery': 'battery-high', 'illuminance': 'weather-sunny', 'pressure': 'gauge', 'atmospheric_pressure': 'gauge',
'carbon_dioxide': 'molecule-co2', 'gas': 'meter-gas', 'water': 'water', 'signal_strength': 'router-wireless',
'timestamp': 'clock-outline', 'duration': 'timer-outline', 'pm1': 'air-purifier', 'pm25': 'air-purifier',
'pm10': 'air-purifier', 'aqi': 'air-purifier', 'volatile_organic_compounds': 'air-purifier', 'wind_speed': 'weather-windy',
'speed': 'weather-windy', 'precipitation': 'weather-rainy', 'precipitation_intensity': 'weather-rainy',
'irradiance': 'solar-power', 'date': 'calendar',
}
DOMAIN_ICONS = {
'light': 'lightbulb', 'switch': 'toggle-switch', 'input_boolean': 'toggle-switch', 'fan': 'fan', 'cover': 'window-shutter',
'climate': 'thermostat', 'vacuum': 'robot-vacuum', 'media_player': 'speaker', 'scene': 'palette', 'script': 'script-text',
'button': 'gesture-tap-button', 'input_button': 'gesture-tap-button', 'person': 'account', 'device_tracker': 'map-marker',
'zone': 'account-group', 'lock': 'lock', 'alarm_control_panel': 'shield-home', 'timer': 'timer-outline', 'counter': 'gauge',
'event': 'bell-ring', 'input_datetime': 'calendar', 'input_text': 'script-text', 'water_heater': 'water-boiler',
'humidifier': 'air-purifier', 'select': 'cog', 'input_select': 'cog', 'number': 'gauge', 'input_number': 'gauge',
'sensor': 'gauge', 'binary_sensor': 'gauge',
}
# Their state is the moment they last ran or fired: the bar shows how long ago.
MOMENT_DOMAINS = frozenset(['scene', 'button', 'input_button', 'event'])
INACTIVE = frozenset(['off', 'closed', 'not_home', 'idle', 'docked', 'standby', 'locked', 'disarmed', 'paused', 'below_horizon'])
AMBER, GREEN, RED, BLUE, ORANGE, TEAL = 'FFB300', '43A047', 'E53935', '2196F3', 'FF6F22', '009688'
ALARM_CLASSES = frozenset(['problem', 'safety', 'smoke', 'gas', 'carbon_monoxide', 'moisture', 'tamper'])
def clean_text(text):
"""Text the screen can draw: known glyphs, accents folded to the base letter, at most TEXT_BYTES."""
out = []
for char in unicodedata.normalize('NFC', str(text)):
if char in GLYPHS:
out.append(char)
continue
base = unicodedata.normalize('NFKD', char)[0]
if base in GLYPHS:
out.append(base)
return short(''.join(out).strip(), TEXT_BYTES)
def number_text(value, precision=None):
"""A number as Home Assistant writes it in Dutch: decimal comma, dots between thousands."""
if precision is None:
# Without a display precision HA keeps integers whole and shows at most three decimals.
digits = 0 if float(value).is_integer() else 3
text = f'{value:.{digits}f}'
if '.' in text:
text = text.rstrip('0').rstrip('.')
else:
text = f'{value:.{precision}f}'
negative = text.startswith('-')
whole, _, fraction = text.lstrip('-').partition('.')
grouped = f'{int(whole):,}'.replace(',', '.')
result = grouped + (',' + fraction if fraction else '')
# "-0" and "-0,0" are just zero.
return '-' + result if negative and any(c not in '0.,' for c in result) else result
def with_unit(text, unit):
"""Home Assistant's spacing in Dutch: "21,3 °C", "65%", "18°"."""
if not unit:
return text
return text + unit if unit in ('%', '°') else f'{text} {unit}'
def precision_of(entry):
options = ((entry or {}).get('options') or {}).get('sensor') or {}
for key in ('display_precision', 'suggested_display_precision'):
value = options.get(key)
if type(value) is int and 0 <= value <= 6:
return value
return None
def numeric(value):
try:
number = float(value)
except (TypeError, ValueError):
return None
return number if math.isfinite(number) else None
def short_date(moment):
return f'{moment.day} {MONTHS[moment.month - 1]}'
def value(entity, state, entry=None, units=None, tz=None):
"""(text, unix time) an entity shows as its state; exactly one of them is set."""
domain = entity.split('.')[0]
raw = state.get('state') if state else None
attrs = (state or {}).get('attributes') or {}
if raw in (None, '', 'unavailable', 'unknown'):
return UNAVAILABLE, None
if domain in MOMENT_DOMAINS:
return (None, epoch(raw)) if epoch(raw) else (UNAVAILABLE, None)
if domain == 'script':
moment = epoch(attrs.get('last_triggered'))
return ('Bezig', None) if raw == 'on' else (None, moment) if moment else ('Nog niet gestart', None)
if domain == 'sun':
# The next event: sunset while the sun is up, sunrise while it is down.
clock = local_clock(attrs.get('next_setting' if raw == 'above_horizon' else 'next_rising'), tz)
return (clock or STATES.get(raw, raw)), None
if domain == 'weather':
temperature = numeric(attrs.get('temperature'))
if temperature is None:
return UNAVAILABLE, None
return with_unit(number_text(temperature, 0), attrs.get('temperature_unit') or (units or {}).get('temperature', '°C')), None
if domain == 'climate':
current = numeric(attrs.get('current_temperature'))
if current is not None:
return with_unit(number_text(current, 1), (units or {}).get('temperature', '°C')), None
if domain in ('person', 'device_tracker'):
return STATES.get(raw, raw), None
if domain == 'binary_sensor':
pair = BINARY_STATES.get(attrs.get('device_class'), ('Aan', 'Uit'))
return (pair[0] if raw == 'on' else pair[1] if raw == 'off' else raw), None
if domain == 'input_datetime':
# "2026-09-15 07:30:00", "2026-09-15" or just "07:30:00".
try:
moment = datetime.fromisoformat(raw) if attrs.get('has_date') else datetime.combine(datetime.min, time.fromisoformat(raw))
except ValueError:
return raw, None
if attrs.get('has_date') and attrs.get('has_time'):
return f'{short_date(moment)} {moment:%H:%M}', None
return (short_date(moment) if attrs.get('has_date') else f'{moment:%H:%M}'), None
if domain == 'sensor' and attrs.get('device_class') == 'timestamp':
return (None, epoch(raw)) if epoch(raw) else (raw, None)
if domain == 'sensor' and attrs.get('device_class') == 'date':
try:
return short_date(datetime.fromisoformat(raw)), None
except ValueError:
return raw, None
number = numeric(raw)
if number is not None and domain in ('sensor', 'number', 'input_number', 'counter', 'zone'):
return with_unit(number_text(number, precision_of(entry)), attrs.get('unit_of_measurement')), None
if domain in ('input_text', 'input_select', 'select'):
return raw, None
if raw in STATES:
return STATES[raw], None
return raw[:1].upper() + raw[1:], None
def active(entity, state):
""""Alleen als actief": on, open, home, detected, playing, heating, or a number other than zero."""
raw = state.get('state') if state else None
domain = entity.split('.')[0]
if raw in (None, '', 'unavailable', 'unknown'):
return False
if domain in ('person', 'device_tracker'):
return raw == 'home'
if domain in MOMENT_DOMAINS or domain in ('weather', 'sun') and raw != 'below_horizon':
return True
number = numeric(raw)
if number is not None:
return number != 0
return raw not in INACTIVE
def accent(entity, state):
"""Icon colour while an entity is active, like Home Assistant's badges; None keeps the calm grey."""
raw = state.get('state') if state else None
domain = entity.split('.')[0]
attrs = (state or {}).get('attributes') or {}
if domain == 'binary_sensor' and raw == 'on':
return RED if attrs.get('device_class') in ALARM_CLASSES else AMBER
if domain in ('light', 'switch', 'input_boolean', 'fan') and raw == 'on':
return AMBER
if domain in ('person', 'device_tracker') and raw == 'home':
return GREEN
if domain == 'climate' and raw in ('heat', 'cool'):
return ORANGE if raw == 'heat' else BLUE
# Home Assistant's own state colours: armed and locked green, on their way orange, alarm and open red.
if domain == 'alarm_control_panel':
return RED if raw == 'triggered' else ORANGE if raw in ('arming', 'pending') else GREEN if raw and raw.startswith('armed') else None
if domain == 'lock':
return GREEN if raw == 'locked' else ORANGE if raw in ('locking', 'unlocking', 'opening') else RED if raw in ('unlocked', 'open', 'jammed') else None
if domain == 'media_player' and raw == 'playing':
return BLUE
if domain == 'vacuum' and raw == 'cleaning':
return TEAL
return None
def auto_icon(entity, state):
"""Codepoint of the icon Home Assistant would show: its own mdi icon, else the device class, else the domain."""
attrs = (state or {}).get('attributes') or {}
raw = (state or {}).get('state')
own = tile_icons.ha_icon(attrs)
if own:
return own
domain, device_class = entity.split('.')[0], attrs.get('device_class')
if domain == 'weather':
name = tile_icons.WEATHER.get(raw, 'weather-partly-cloudy')
elif domain == 'sun':
name = 'weather-sunset-down' if raw == 'above_horizon' else 'weather-sunset-up'
elif domain == 'binary_sensor' and device_class in BINARY_ICONS:
name = BINARY_ICONS[device_class][0 if raw == 'on' else 1]
elif domain == 'sensor' and device_class in SENSOR_ICONS:
name = SENSOR_ICONS[device_class]
elif domain == 'lock' and raw in ('unlocked', 'open', 'unlocking'):
name = 'lock-open-variant'
else:
name = DOMAIN_ICONS.get(domain, tile_icons.FALLBACK)
return tile_icons.GLYPHS[name]
def entity_item(item, states, registry=None, units=None, tz=None):
"""(wire item, shown) for one entity item; the wire item exists even while hidden, for the editor."""
entity = item['entity']
state = states.get(entity)
wire = {'k': 'text'}
if item['icon'] == 'auto':
wire['i'] = auto_icon(entity, state)
elif item['icon'] != 'none':
wire['i'] = tile_icons.ICONS[item['icon']][0]
if item['content'] == 'last_changed':
moment = epoch((state or {}).get('last_changed'))
text, moment = (None, moment) if moment else (UNAVAILABLE, None)
else:
text, moment = value(entity, state, (registry or {}).get(entity), units, tz)
if moment:
wire.update(k='ago', e=moment)
else:
wire['t'] = clean_text(text) or UNAVAILABLE
color = accent(entity, state)
if color:
wire['c'] = color
return wire, item['show'] == 'always' or active(entity, state)
def message(layout, states, registry=None, units=None, tz=None):
items = []
for item in header_items(layout):
if item['type'] in HEADER_BUILTIN:
items.append({'k': item['type']})
continue
wire, shown = entity_item(item, states, registry, units, tz)
if shown:
items.append(wire)
return {'v': 1, 'op': 'header', 'items': items}
def preview(header, states, registry=None, units=None, tz=None):
"""What the editor's mockup shows per item, hidden ones included and marked."""
result = []
for item in header['items']:
if item['type'] in HEADER_BUILTIN:
result.append({'k': item['type'], 'name': HEADER_BUILTIN[item['type']], 'shown': True})
continue
wire, shown = entity_item(item, states, registry, units, tz)
attrs = (states.get(item['entity']) or {}).get('attributes') or {}
result.append({**wire, 'name': attrs.get('friendly_name') or item['entity'], 'shown': shown,
'auto_icon': auto_icon(item['entity'], states.get(item['entity']))})
return result
def suggestions(screen, entities, states, registry=None, limit=8):
"""A handful of useful items for this screen: its own room's climate and power first, then the house.
The room is the screen's area, or an area named like the screen. Diagnostic entities (a plug's own
temperature) never qualify."""
rooms = {name.casefold() for name in (screen.get('area'), screen.get('name'), (screen.get('layout') or {}).get('title')) if name}
def attrs(entity):
return (states.get(entity['id']) or {}).get('attributes') or {}
def usable(entity):
return ((states.get(entity['id']) or {}).get('state') not in (None, 'unavailable', 'unknown')
and not ((registry or {}).get(entity['id']) or {}).get('entity_category'))
def pick(label, test, content='state'):
found = sorted((e for e in entities if test(e) and usable(e)), key=lambda e: (e['area'].casefold() not in rooms, e['name'].casefold()))
if found:
entity = found[0]
picks.append({'label': label, 'name': entity['name'], 'area': entity['area'], 'icon': auto_icon(entity['id'], states.get(entity['id'])),
'item': {'type': 'entity', 'entity': entity['id'], 'content': content, 'icon': 'auto', 'show': 'always'}})
def sensor(device_class):
return lambda e: e['id'].startswith('sensor.') and attrs(e).get('device_class') == device_class and numeric(states[e['id']]['state']) is not None
picks = []
pick('Temperatuur', sensor('temperature'))
pick('Luchtvochtigheid', sensor('humidity'))
pick('Stroomverbruik', sensor('power'))
pick('Laatste beweging', lambda e: e['id'].startswith('binary_sensor.') and attrs(e).get('device_class') in ('motion', 'occupancy', 'presence'), 'last_changed')
pick('Weer', lambda e: e['id'].startswith('weather.'))
pick('Aantal thuis', lambda e: e['id'] == 'zone.home')
pick('Zon op en onder', lambda e: e['id'] == 'sun.sun')
pick('CO₂', sensor('carbon_dioxide'))
return picks[:limit]
def catalogue():
"""Choices the editor offers; labels in the order the sheet shows them."""
return {'builtin': [{'type': key, 'label': label} for key, label in HEADER_BUILTIN.items()],
'contents': [{'key': key, 'label': CONTENT_LABELS[key]} for key in HEADER_CONTENTS],
'shows': [{'key': key, 'label': SHOW_LABELS[key]} for key in HEADER_SHOWS],
'max_items': HEADER_MAX_ITEMS, 'min_firmware': '.'.join(map(str, HEADER_MIN_FIRMWARE))}
+42 -3
View File
@@ -14,7 +14,8 @@ import tile_icons
from updates import Updater
from aiohttp import ClientSession, ClientTimeout, WSMsgType, web
from core import BUILTIN, TILE_BACKGROUNDS, alert_reference, alert_service, controls_catalogue, discover, extras, min_firmware, pack_slots, packets, state_message, validate_layout, validate_settings
from core import BUILTIN, HEADER_MIN_FIRMWARE, TILE_BACKGROUNDS, alert_reference, alert_service, controls_catalogue, discover, extras, header_items, min_firmware, pack_slots, packets, state_message, validate_header, validate_layout, validate_settings
import header_bar
from zoneinfo import ZoneInfo
LOG = logging.getLogger('screen_manager')
@@ -42,6 +43,8 @@ class HomeAssistant:
self.registry_changed = asyncio.Event()
self.setting_events = []
self.time_zone = None
# Home Assistant's unit system; a climate entity's temperature carries no unit of its own.
self.units = {}
async def request(self, kind, **data):
if self.ws is None or self.ws.closed:
@@ -119,7 +122,9 @@ class HomeAssistant:
self.states = {s['entity_id']: s for s in await self.request('get_states')}
await self.registries()
try:
self.time_zone = ZoneInfo((await self.request('get_config')).get('time_zone') or 'UTC')
config = await self.request('get_config')
self.units = config.get('unit_system') or {}
self.time_zone = ZoneInfo(config.get('time_zone') or 'UTC')
except Exception:
self.time_zone = timezone.utc
self.online = True
@@ -213,6 +218,7 @@ class Manager:
self.listeners = set() # asyncio.Event per open /api/events stream
self.firmware = Firmware(os.environ.get("ESPHOME_CONFIG", "/homeassistant/esphome"), self.path.parent)
self.updates = Updater(self, self.path.parent / 'updates.json')
self._registry_source, self._registry_index = None, {}
if self.path.exists():
raw = json.loads(self.path.read_text())
# Versioned persistent data. Never silently overwrite an unknown schema.
@@ -236,6 +242,19 @@ class Manager:
version=self.firmware_version(inbox)
return bool(version) and version >= (0,2,7)
def supports_header(self, inbox, screen=None):
return (self.firmware_version(inbox, screen) or (0, 0, 0)) >= HEADER_MIN_FIRMWARE
def registry_index(self):
"""Entity registry by id (display precision, entity category); rebuilt only when HA delivers a new registry."""
registry = getattr(self.ha, 'registry', [])
if self._registry_source is not registry:
self._registry_source, self._registry_index = registry, {item['entity_id']: item for item in registry}
return self._registry_index
def header_message(self, layout):
return header_bar.message(layout, self.ha.states, self.registry_index(), getattr(self.ha, 'units', {}), getattr(self.ha, 'time_zone', None))
def needs_firmware(self, inbox, layout, screen=None):
"""Version string the screen must run first, or None when the layout can be sent."""
needed=min_firmware(layout)
@@ -252,9 +271,14 @@ class Manager:
needed = self.needs_firmware(inbox, layout, screen)
if needed:
raise ValueError(f"Installeer eerst schermfirmware {needed} of nieuwer voor deze tegels.")
# A still-open older UI may save tiles without the new optional settings.
# A still-open older UI may save tiles without the new optional settings or top bar.
if 'settings' not in layout and 'settings' in self.layouts.get(inbox, {}):
layout['settings'] = self.layouts[inbox]['settings'].copy()
if 'header' not in layout and 'header' in self.layouts.get(inbox, {}):
layout['header'] = self.layouts[inbox]['header']
# Firmware before the top bar only knows show_clock; it follows the clock item.
if 'header' in layout and 'settings' in layout:
layout['settings']['show_clock'] = any(item['type'] == 'clock' for item in layout['header']['items'])
if 'settings' in layout and 'swipe_pages' not in data.get('settings',{}):
layout['settings']['swipe_pages']=self.layouts.get(inbox,{}).get('settings',{}).get('swipe_pages',False)
if 'settings' in layout and 'rotation' not in data.get('settings',{}):
@@ -278,6 +302,8 @@ class Manager:
known = {e['id'] for e in entities} | set(BUILTIN)
if any(t['entity'] not in known for t in layout['tiles']):
raise ValueError('Een gekozen entiteit bestaat niet meer. Zoek de nieuwe entiteit op.')
if any(item['type'] == 'entity' and item['entity'] not in known and item['entity'] not in self.ha.states for item in header_items(layout)):
raise ValueError('Een entiteit in de bovenbalk bestaat niet meer. Kies een andere.')
updated = {**self.layouts, inbox: layout}
self.path.parent.mkdir(parents=True, exist_ok=True)
temp = self.path.with_suffix('.tmp')
@@ -313,6 +339,7 @@ class Manager:
def watched_entities(self):
"""Entities whose state changes matter: tiles on any layout plus the screens' own diagnostics."""
watched = {tile['entity'] for layout in self.layouts.values() for tile in layout['tiles']}
watched |= {item['entity'] for layout in self.layouts.values() for item in header_items(layout) if item['type'] == 'entity'}
for item in getattr(self.ha, 'registry', []):
if item.get('platform') == 'esphome' and item.get('original_name') in SCREEN_ENTITY_NAMES:
watched.add(item['entity_id'])
@@ -344,6 +371,9 @@ class Manager:
messages[0]['swipe_pages'] = layout['settings'].get('swipe_pages',False)
if screen.get('board')=='guition':
messages[0]['rotation'] = layout['settings'].get('rotation',0)
# The top bar right after the layout (firmware 0.2.32+; older firmware draws the clock of show_clock).
if self.supports_header(inbox, screen):
messages.append(self.header_message(layout))
for i,tile in enumerate(layout['tiles']):
forecast=hourly=None
if tile['entity'].startswith('weather.') and hasattr(self.ha,'forecast'):
@@ -468,7 +498,15 @@ def create_app(manager, development=False):
payload['icons'] = tile_icons.editor()
payload['alerts'] = alert_reference()
payload['builtin'] = [{'id': key, 'name': name, 'device': 'Ingebouwd op het scherm', 'area': '', 'state': 'ok'} for key, name in BUILTIN.items()]
payload['header'] = {**header_bar.catalogue(), 'suggestions': {
screen['id']: header_bar.suggestions(screen, entities, manager.ha.states, manager.registry_index()) for screen in payload['screens']}}
return web.json_response(payload)
async def header_preview(request):
"""The top bar as a screen would draw it right now, so the editor shows unsaved changes live."""
data = await request.json()
header = validate_header(data.get('header') if isinstance(data, dict) else None)
return web.json_response({'items': header_bar.preview(header, manager.ha.states, manager.registry_index(),
getattr(manager.ha, 'units', {}), getattr(manager.ha, 'time_zone', None))})
async def events(request):
"""Server-sent events: pushes the light inventory whenever it changes, so the page need not poll."""
response = web.StreamResponse(headers={'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store',
@@ -534,6 +572,7 @@ def create_app(manager, development=False):
app.router.add_post('/api/firmware/profiles', firmware_create)
app.router.add_get('/', index)
app.router.add_get('/api/inventory', inventory)
app.router.add_post('/api/header-preview', header_preview)
app.router.add_get('/api/events', events)
app.router.add_put('/api/screens/{inbox}', save)
app.router.add_static('/static/', static)
+573 -20
View File
@@ -74,9 +74,11 @@ function select(id) {
$("#dirty").textContent = "Alles opgeslagen";
$("#save-detail").textContent = "Aanpassen kan zonder opnieuw flashen.";
renderScreens();
renderTopbar();
renderTiles();
renderResults();
renderSettings();
loadTopbarPreview(0);
}
const settingDefinitions = [
["standby_enabled", "Automatisch standby", "check", true],
@@ -87,7 +89,7 @@ const settingDefinitions = [
["night_brightness", "Helderheid in nachtstand", "range", 10, 0, 100],
["night_start", "Nachtstand vanaf", "time", 1320],
["night_end", "Nachtstand tot", "time", 420],
["show_clock", "Klok tonen", "check", true],
// Whether the clock shows is up to the top bar now; the add-on keeps show_clock in step for older firmware.
["clock_24h", "24-uursklok (uit = 12 uur)", "check", true],
["home_on_standby", "Na standby terug naar pagina 1", "check", false],
["rotation", "Scherm draaien (met de klok mee)", "rotation", 0],
@@ -623,13 +625,13 @@ function renderPreview(preview) {
const moving = preview?.moving || null;
const bySlot = new Map(entries.map((e) => [e.slot, e]));
const covered = new Set(entries.filter((e) => isWide(e.tile)).map((e) => e.slot + 1));
const pages = pageCount(entries), title = $("#title").value || "Thuis";
const pages = pageCount(entries);
// While dragging, one more page waits below the last one.
const shown = drag.active && pages < MAX_PAGES ? pages + 1 : pages;
for (let page = 0; page < shown; page++) {
const frame = node("section", undefined, "screen-preview");
const heading = node("div", undefined, "preview-heading");
heading.append(node("small", `Pagina ${page + 1} · ${title}`));
heading.append(node("small", `Pagina ${page + 1}`));
if (page >= pages) {
frame.classList.add("new-page");
heading.replaceChildren(node("small", `Pagina ${page + 1} · sleep hierheen voor een nieuwe pagina`));
@@ -642,6 +644,7 @@ function renderPreview(preview) {
heading.append(drop);
}
frame.append(heading);
if (page < pages) frame.append(topbarBar());
const grid = node("div", undefined, "preview-grid");
for (let cell = 0; cell < SLOTS_PER_PAGE; cell++) {
const slot = page * SLOTS_PER_PAGE + cell;
@@ -652,6 +655,7 @@ function renderPreview(preview) {
frame.append(grid);
root.append(frame);
}
fitTopbars();
}
// A card on the mockup. A placeholder is the tile being dragged, drawn where it will land.
function tileCard(tile, slot, placeholder) {
@@ -775,19 +779,29 @@ function segmented(choices, value, onChange) {
// A choice applies live like the palette: only pressed states, the summary and the
// badges update, so search text and scroll position survive.
function iconField(tile, onChange) {
const fromHA = Boolean(inventory.entities.find((e) => e.id === tile.entity)?.icon);
return iconPicker({
selected: tile.options?.icon || "auto",
automatic: automaticIcon(tile.entity),
autoLabel: `Automatisch (${fromHA ? "uit Home Assistant" : "standaard"})`,
onPick: (name) => { tile.options = { ...tile.options, icon: name }; markDirty(); renderPreview(); onChange(); },
note: supportsFirmware(0, 2, 18) ? "" : "Het scherm toont een gekozen icoon vanaf firmware 0.2.18.",
});
}
// The icon choice for tiles and top bar items: automatic, optionally none, or one from the set.
function iconPicker({ selected, automatic, autoLabel, allowNone = false, onPick, note = "" }) {
const wrap = node("div", undefined, "sheet-field");
wrap.append(node("span", "Icoon"));
const fromHA = Boolean(inventory.entities.find((e) => e.id === tile.entity)?.icon);
const autoLabel = `Automatisch (${fromHA ? "uit Home Assistant" : "standaard"})`;
let picked = selected;
const summary = node("button", undefined, "icon-current");
summary.type = "button";
summary.setAttribute("aria-expanded", String(iconPickerOpen));
const current = node("span", undefined, "mdi"), text = node("span"), action = node("small", iconPickerOpen ? "Sluiten" : "Wijzigen");
summary.append(current, text, action);
const describe = () => {
const chosen = iconNamed(tile.options?.icon);
current.textContent = glyph(chosen?.cp || automaticIcon(tile.entity));
text.textContent = chosen?.label || autoLabel;
const chosen = iconNamed(picked);
current.textContent = picked === "none" ? "" : glyph(chosen?.cp || automatic);
text.textContent = picked === "none" ? "Geen icoon" : chosen?.label || autoLabel;
};
describe();
const panel = node("div", undefined, "icon-picker");
@@ -805,15 +819,13 @@ function iconField(tile, onChange) {
b.dataset.search = label.toLocaleLowerCase();
b.title = label;
b.setAttribute("aria-label", `Icoon: ${label}`);
b.setAttribute("aria-pressed", String((tile.options?.icon || "auto") === name));
b.append(node("span", glyph(cp), "mdi"));
b.setAttribute("aria-pressed", String(picked === name));
b.append(node("span", cp ? glyph(cp) : "", "mdi"));
b.onclick = () => {
tile.options = { ...tile.options, icon: name };
picked = name;
for (const other of panel.querySelectorAll(".icon-choice")) other.setAttribute("aria-pressed", String(other === b));
describe();
markDirty();
renderPreview();
onChange();
onPick(name);
};
return b;
};
@@ -821,8 +833,10 @@ function iconField(tile, onChange) {
search.type = "search";
search.placeholder = "Zoek, bijvoorbeeld lamp, muziek of deur";
search.setAttribute("aria-label", "Zoek een icoon");
const auto = choice("auto", automaticIcon(tile.entity), autoLabel, "icon-auto");
const auto = choice("auto", automatic, autoLabel, "icon-auto");
auto.append(node("span", autoLabel));
const none = allowNone ? choice("none", "", "Geen icoon", "icon-auto icon-none") : null;
none?.append(node("span", "Geen icoon, alleen tekst"));
const list = node("div", undefined, "icon-list"), empty = node("p", "Geen icoon gevonden.", "hint");
empty.hidden = true;
const sections = inventory.icons.groups.map((group) => {
@@ -850,9 +864,9 @@ function iconField(tile, onChange) {
}
empty.hidden = found > 0;
};
panel.append(search, auto, list, empty);
panel.append(search, auto, ...(none ? [none] : []), list, empty);
wrap.append(summary, panel);
if (!supportsFirmware(0, 2, 18)) wrap.append(node("small", "Het scherm toont een gekozen icoon vanaf firmware 0.2.18.", "icon-hint"));
if (note) wrap.append(node("small", note, "icon-hint"));
return wrap;
}
function renderTileSheet() {
@@ -961,6 +975,541 @@ function renderTileSheet() {
foot.append(done);
sheet.append(head, body, foot);
}
// ---- Top bar ----
// The name on the left; on the right up to six items: the time, an analog clock, the date, or an
// entity's state or last change. The add-on formats entity text (POST header-preview) exactly as the
// screen gets it; the screen and this mockup tick clocks and "5 min geleden" themselves.
const MONTHS = ["jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"];
const WEEKDAYS = ["zo", "ma", "di", "wo", "do", "vr", "za"];
const BUILTIN_ICONS = { clock: "clock-outline", analog: "clock-outline", date: "calendar" };
let topbarPreviews = new Map(), topbarTimer = 0, topbarSheetIndex = null, topbarOverflow = new Set(), topbarAdded = null;
const itemKey = (item) => JSON.stringify(item);
// Without a stored top bar the screen shows what it always did: the clock of show_clock.
const topbarItems = () => layout.header?.items ?? ((layout.settings?.show_clock ?? true) ? [{ type: "clock" }] : []);
const topbarMax = () => inventory.header?.max_items || 6;
function setTopbarItems(items) {
layout.header = { items };
markDirty();
renderTopbar();
renderBars();
loadTopbarPreview();
}
// A caption over a group of buttons; unlike a label it never forwards a click to the first one.
function group(title, content) {
const wrap = node("div", undefined, "sheet-field");
wrap.append(node("span", title), content);
return wrap;
}
// Only the bars of the mockup pages, so tiles, focus and a running drag stay untouched.
function renderBars() {
const bars = document.querySelectorAll("#layout-preview .preview-bar-wrap");
if (!bars.length) return renderPreview();
for (const bar of bars) bar.replaceWith(topbarBar());
fitTopbars();
}
// Entity text as the screen will show it, for the items not previewed yet.
function loadTopbarPreview(delay = 150) {
clearTimeout(topbarTimer);
topbarTimer = setTimeout(async () => {
const items = topbarItems();
if (!items.some((item) => item.type === "entity")) return;
try {
const data = await (await api("header-preview", { method: "POST", body: JSON.stringify({ header: { items } }) })).json();
items.forEach((item, i) => topbarPreviews.set(itemKey(item), data.items[i]));
if (!layout) return;
renderTopbar();
renderBars();
if (topbarSheetIndex !== null && $("#topbar-sheet").open) renderTopbarLive();
} catch {
// Keep the last preview; the next edit or refresh tries again.
}
}, delay);
}
function clockText(now = new Date()) {
let hours = now.getHours();
// The screen formats with %I:%M when the 24-hour clock is off.
if (!(layout.settings?.clock_24h ?? true)) hours = hours % 12 || 12;
return `${String(hours).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
}
const dateText = (now = new Date()) => `${WEEKDAYS[now.getDay()]} ${now.getDate()} ${MONTHS[now.getMonth()]}`;
// Same wording and thresholds as header_bar::ago_text() in the firmware.
function agoText(then, now = Math.floor(Date.now() / 1000)) {
const seconds = now - then, span = Math.abs(seconds), per = (unit) => Math.floor(span / unit);
if (seconds < 0) {
if (span < 3600) return `Over ${Math.max(1, per(60))} min`;
if (span < 86400) return `Over ${per(3600)} uur`;
if (span < 172800) return "Morgen";
return `Over ${per(86400)} dagen`;
}
if (span < 60) return "Zojuist";
if (span < 3600) return `${per(60)} min geleden`;
if (span < 86400) return `${per(3600)} uur geleden`;
if (span < 172800) return "Gisteren";
if (span < 604800) return `${per(86400)} dagen geleden`;
if (span < 2592000) return per(604800) === 1 ? "1 week geleden" : `${per(604800)} weken geleden`;
if (span < 31536000) return per(2592000) === 1 ? "1 maand geleden" : `${per(2592000)} maanden geleden`;
return `${per(31536000)} jaar geleden`;
}
function topbarLabel(item) {
if (item.type === "entity") return entityName(item.entity);
return inventory.header?.builtin.find((b) => b.type === item.type)?.label || item.type;
}
// What the item shows right now: { icon, text, color, shown }. Entities wait for the add-on's preview.
function topbarView(item) {
if (item.type === "clock") return { text: clockText(), shown: true };
if (item.type === "date") return { text: dateText(), shown: true };
if (item.type === "analog") return { analog: true, shown: true };
const p = topbarPreviews.get(itemKey(item));
if (!p) return { icon: item.icon === "none" ? null : iconNamed(item.icon)?.cp || automaticIcon(item.entity), text: "…", shown: true, loading: true };
return { icon: p.i || null, text: p.k === "ago" ? agoText(p.e) : p.t, color: p.c ? `#${p.c}` : null, shown: p.shown };
}
// ---- The bar as the screen draws it ----
// One rule set with header_bar.h in the firmware, in screen pixels of the board: every value (the
// time too) in the same 400 Roboto on the name's baseline; icons and the dial centred on the
// height of the digits; the gaps measured between what you see (glyph ink), not between boxes, so
// an icon with side bearings sits exactly as close to its value as one without.
const BAR_METRICS = {
guition: { width: 448, top: 36, name: 27, text: 21, icon: 26 },
cyd: { width: 298, top: 24, name: 18, text: 14, icon: 18 },
};
// Screens without the Guition type sensor are CYDs, as the rotation setting assumes too.
const barMetrics = () => BAR_METRICS[inventory.screens.find((s) => s.id === selected)?.board === "guition" ? "guition" : "cyd"];
const measure = document.createElement("canvas").getContext("2d");
const inkCache = new Map();
// Ink box of a string relative to its origin on the baseline: left/right, and top (negative, up)/bottom.
function inkOf(text, font) {
const key = `${font}|${text}`;
if (!inkCache.has(key)) {
measure.font = font;
const m = measure.measureText(text);
inkCache.set(key, { left: -m.actualBoundingBoxLeft, right: m.actualBoundingBoxRight, top: -m.actualBoundingBoxAscent, bottom: m.actualBoundingBoxDescent, advance: m.width });
}
return inkCache.get(key);
}
const barFonts = (m) => ({ name: `500 ${m.name}px "Bar Roboto"`, text: `400 ${m.text}px "Bar Roboto"`, icon: `${m.icon}px "Tile Icons"` });
// The fonts load on first use; measurements before that are wrong, so draw again once they are in.
Promise.all([document.fonts.load('500 27px "Bar Roboto"', "Studio 0"), document.fonts.load('400 21px "Bar Roboto"', "Weg 0"), document.fonts.load('26px "Tile Icons"', String.fromCodePoint(0xf0150))])
.then(() => { inkCache.clear(); if (layout) { renderTopbar(); renderBars(); } })
.catch(() => {});
// Same integer arithmetic as header_bar::gaps() in the firmware, from the digit height in pixels.
function barGaps(cap) {
return { icon: Math.max(2, Math.floor((cap * 4 + 5) / 10)), item: Math.max(6, Math.floor((cap * 125 + 50) / 100)), name: Math.max(8, Math.floor((cap * 16 + 5) / 10)) };
}
// The parts per item with their ink widths, the placement, and which items fall off.
function barLayout(items = topbarItems(), metrics = barMetrics(), nameText = $("#title").value || "Thuis") {
const fonts = barFonts(metrics);
// The firmware reads the digit height as a whole number of pixels (the glyph box of "0").
const zero = inkOf("0", fonts.text), cap = Math.round(zero.bottom - zero.top), gaps = barGaps(cap);
const dialInk = inkOf(String.fromCodePoint(0xf0150), fonts.icon), dial = Math.round(dialInk.bottom - dialInk.top);
const parts = items.map((item, index) => {
const view = topbarView(item);
const part = { index, item, view, shown: view.shown, width: 0 };
if (view.analog) { part.dial = dial; part.width = dial; return part; }
if (view.icon) { part.icon = { glyph: glyph(view.icon), ink: inkOf(glyph(view.icon), fonts.icon) }; part.width += part.icon.ink.right - part.icon.ink.left; }
if (view.text) {
part.text = { value: view.text, ink: inkOf(view.text, fonts.text) };
part.width += (part.icon ? gaps.icon : 0) + part.text.ink.right - part.text.ink.left;
}
return part;
});
const shown = parts.filter((p) => p.shown);
const natural = inkOf(nameText, fonts.name).advance;
const minName = Math.min(natural, Math.floor((metrics.width * 35) / 100));
const total = (list) => list.reduce((sum, p) => sum + p.width, 0) + Math.max(0, list.length - 1) * gaps.item;
let first = 0;
while (first < shown.length && total(shown.slice(first)) + gaps.name + minName > metrics.width) first++;
const placed = shown.slice(first), dropped = new Set(shown.slice(0, first).map((p) => p.index));
let x = metrics.width - total(placed);
for (const p of placed) { p.x = x; x += p.width + gaps.item; }
const nameRoom = placed.length ? placed[0].x - gaps.name : metrics.width;
return { metrics, fonts, cap, zero, gaps, parts, placed, dropped, nameText, natural, nameRoom };
}
// LVGL's LV_LABEL_LONG_DOT: the longest start that fits with "..." after it.
function dotted(text, font, room) {
if (inkOf(text, font).advance <= room) return text;
const chars = [...text];
while (chars.length && inkOf(chars.join("") + "...", font).advance > room) chars.pop();
return chars.join("") + "...";
}
// `font` goes through CSSOM: the add-on's CSP blocks style attributes.
const svgNode = (tag, attrs = {}) => {
const el = document.createElementNS("http://www.w3.org/2000/svg", tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === "font") el.style.font = v;
else el.setAttribute(k, v);
}
return el;
};
// Draws placed parts into an SVG group; `baseline` is the text baseline in screen pixels.
function drawParts(group, lay, parts, baseline) {
const capMiddle = baseline + (lay.zero.top + lay.zero.bottom) / 2;
for (const p of parts) {
const color = p.view.color || "#46525e";
if (p.dial) {
const d = p.dial, stroke = Math.max(1, Math.round(d / 10)), hand = Math.max(1, Math.round(d * 0.075));
const cx = p.x + d / 2, now = new Date();
group.append(svgNode("circle", { cx, cy: capMiddle, r: d / 2 - stroke / 2, fill: "none", stroke: color, "stroke-width": stroke }));
for (const [angle, length] of [[(now.getHours() % 12 + now.getMinutes() / 60) * 30, d * 0.24], [now.getMinutes() * 6, d * 0.34]]) {
const rad = (angle * Math.PI) / 180;
group.append(svgNode("line", { x1: cx, y1: capMiddle, x2: cx + length * Math.sin(rad), y2: capMiddle - length * Math.cos(rad), stroke: color, "stroke-width": hand, "stroke-linecap": "round" }));
}
continue;
}
let x = p.x;
if (p.icon) {
const ink = p.icon.ink, icon = svgNode("text", { x: x - ink.left, y: capMiddle - (ink.top + ink.bottom) / 2, fill: color, font: lay.fonts.icon });
icon.textContent = p.icon.glyph;
group.append(icon);
x += ink.right - ink.left + (p.text ? lay.gaps.icon : 0);
}
if (p.text) {
const text = svgNode("text", { x: x - p.text.ink.left, y: baseline, fill: "#46525e", font: lay.fonts.text });
text.textContent = p.text.value;
group.append(text);
}
}
}
// The bar at the top of a mockup page, scaled with the page: name left, items right.
function topbarBar() {
const lay = barLayout(), m = lay.metrics;
const height = m.top + Math.round(m.name * 0.45);
const svg = svgNode("svg", { viewBox: `0 0 ${m.width} ${height}`, class: "preview-bar", role: "img" });
const name = svgNode("text", { x: 0, y: m.top, fill: "#1b1b1b", font: lay.fonts.name });
name.textContent = dotted(lay.nameText, lay.fonts.name, Math.min(lay.natural, lay.nameRoom));
svg.append(name);
const group = svgNode("g");
drawParts(group, lay, lay.placed, m.top);
svg.append(group);
svg.setAttribute("aria-label", `Bovenbalk: ${lay.nameText}`);
const wrap = node("div", undefined, "preview-bar-wrap");
wrap.title = "Bovenbalk aanpassen";
wrap.append(svg);
wrap.onclick = () => { $("#topbar").scrollIntoView({ behavior: "smooth", block: "center" }); $("#topbar").classList.add("flash"); setTimeout(() => $("#topbar").classList.remove("flash"), 900); };
return wrap;
}
// Which items the screen leaves out for lack of room; the chips mark them.
function fitTopbars() {
const dropped = barLayout().dropped;
const before = [...topbarOverflow].join();
topbarOverflow = dropped;
if ([...dropped].join() !== before) renderTopbar();
}
// One item on its own, drawn exactly as in the bar (the sheet's "zo staat het op het scherm").
function itemSample(item) {
const lay = barLayout([item]), m = lay.metrics, part = lay.parts[0];
part.x = 0;
const top = Math.round(m.text * 1.05), height = Math.round(m.text * 1.4);
const svg = svgNode("svg", { viewBox: `-2 0 ${Math.max(1, part.width) + 4} ${height}`, class: "topbar-sample", role: "img" });
svg.style.width = `${(Math.max(1, part.width) + 4) * (26 / m.icon)}px`;
const group = svgNode("g");
drawParts(group, lay, [part], top);
svg.append(group);
return svg;
}
function renderTopbar() {
if (!layout) return;
const items = topbarItems(), chips = $("#topbar-chips");
chips.replaceChildren();
items.forEach((item, index) => chips.append(topbarChip(item, index)));
const add = node("button", "+ Toevoegen", "topbar-add");
add.type = "button";
add.disabled = items.length >= topbarMax();
add.title = add.disabled ? `Maximaal ${topbarMax()} onderdelen` : "Tijd, datum, analoge klok of een entiteit toevoegen";
add.onclick = () => openTopbarSheet(-1);
chips.append(add);
$("#topbar-count").textContent = `${items.length} / ${topbarMax()}`;
const needed = inventory.header?.min_firmware || "0.2.32";
const [major, minor, patch] = needed.split(".").map(Number);
const hint = $("#topbar-hint");
hint.textContent = supportsFirmware(major, minor, patch)
? topbarOverflow.size ? "Niet alles past naast de naam: het scherm laat de gestreepte onderdelen weg. Haal er een weg of kies een kortere naam." : "Sleep om de volgorde te wijzigen; tik op een onderdeel om het in te stellen."
: `Sensoren, datum en de analoge klok verschijnen vanaf firmware ${needed}; tot die update toont dit scherm de naam en, als de tijd erin staat, de klok.`;
hint.classList.toggle("warn", topbarOverflow.size > 0 && supportsFirmware(major, minor, patch));
}
function topbarChip(item, index) {
const view = topbarView(item);
const chip = node("div", undefined, "topbar-chip");
chip.setAttribute("role", "listitem");
chip.tabIndex = 0;
chip.dataset.index = index;
chip.classList.toggle("is-hidden", !view.shown);
chip.classList.toggle("is-overflow", topbarOverflow.has(index));
chip.classList.toggle("just-added", topbarAdded?.key === itemKey(item) && Date.now() - topbarAdded.time < 1200);
chip.classList.toggle("dragging-chip", chipDrag.active && chipDrag.index === index);
const icon = node("span", "", "mdi chip-icon");
const cp = view.analog || item.type !== "entity" ? iconNamed(BUILTIN_ICONS[item.type])?.cp : view.icon;
if (cp) icon.textContent = glyph(cp);
if (view.color) icon.style.color = view.color;
const texts = node("span", undefined, "chip-text");
const detail = !view.shown ? "Verborgen: nu niet actief" : topbarOverflow.has(index) ? "Past niet naast de naam" : view.analog ? "Wijzerplaat" : view.text;
texts.append(node("strong", topbarLabel(item)), node("small", detail));
const remove = node("button", "✕", "chip-remove");
remove.type = "button";
remove.setAttribute("aria-label", `${topbarLabel(item)} uit de bovenbalk halen`);
remove.onclick = (e) => { e.stopPropagation(); removeTopbarItem(index); };
chip.append(icon, texts, remove);
chip.setAttribute("aria-label", `${topbarLabel(item)}, plek ${index + 1}. Enter: instellen, pijltjes: verplaatsen`);
chip.onclick = () => openTopbarSheet(index);
chip.onkeydown = (e) => {
if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openTopbarSheet(index); return; }
const step = { ArrowLeft: -1, ArrowRight: 1 }[e.key];
if (step && moveTopbarItem(index, index + step)) $(`#topbar-chips [data-index="${index + step}"]`)?.focus();
};
enableChipDrag(chip, index);
return chip;
}
function moveTopbarItem(from, to) {
const items = [...topbarItems()];
if (to < 0 || to >= items.length || from === to) return false;
items.splice(to, 0, ...items.splice(from, 1));
setTopbarItems(items);
return true;
}
function removeTopbarItem(index) {
const items = [...topbarItems()];
const [item] = items.splice(index, 1);
if (!item) return;
if ($("#topbar-sheet").open) $("#topbar-sheet").close();
setTopbarItems(items);
toast(`${topbarLabel(item)} uit de bovenbalk gehaald`, {
label: "Ongedaan maken",
run: () => { const back = [...topbarItems()]; back.splice(Math.min(index, back.length), 0, item); setTopbarItems(back); },
});
}
function addTopbarItem(item) {
const items = topbarItems();
if (items.length >= topbarMax()) return toast(`De bovenbalk heeft plaats voor ${topbarMax()} onderdelen.`);
if (items.some((other) => itemKey(other) === itemKey(item))) return toast("Dit staat al in de bovenbalk.");
// The new chip lights up briefly so the eye finds it.
topbarAdded = { key: itemKey(item), time: Date.now() };
setTopbarItems([...items, item]);
$("#topbar-sheet").close();
}
// Pointer drag between chips, mouse and touch (touch after a short hold, so the page still scrolls).
// The order updates while dragging, the screen mockup follows, and a finished drag is not a click.
const chipDrag = { index: -1, start: null, timer: 0, active: false, pointerId: null, moved: false };
function enableChipDrag(chip, index) {
chip.addEventListener("pointerdown", (e) => {
if (e.button !== 0 || e.target.closest(".chip-remove")) return;
if (e.pointerType !== "touch") e.preventDefault();
Object.assign(chipDrag, { index, start: { x: e.clientX, y: e.clientY }, pointerId: e.pointerId, active: false, moved: false });
clearTimeout(chipDrag.timer);
if (e.pointerType === "touch") chipDrag.timer = setTimeout(() => beginChipDrag(), 260);
document.addEventListener("pointermove", moveChipDrag);
document.addEventListener("pointerup", endChipDrag);
document.addEventListener("pointercancel", endChipDrag);
});
}
function beginChipDrag() {
chipDrag.active = true;
document.body.classList.add("dragging");
document.addEventListener("touchmove", blockChipScroll, { passive: false });
$(`#topbar-chips [data-index="${chipDrag.index}"]`)?.classList.add("dragging-chip");
}
function blockChipScroll(e) { if (chipDrag.active) e.preventDefault(); }
function moveChipDrag(e) {
if (e.pointerId !== chipDrag.pointerId || !chipDrag.start) return;
if (!chipDrag.active) {
const distance = Math.hypot(e.clientX - chipDrag.start.x, e.clientY - chipDrag.start.y);
if (e.pointerType === "touch") { if (distance > 10) { clearTimeout(chipDrag.timer); chipDrag.start = null; } return; }
if (distance < 6) return;
beginChipDrag();
}
// The target is the chip under the pointer's row whose middle the pointer passed.
const chips = [...document.querySelectorAll("#topbar-chips .topbar-chip")];
let target = chipDrag.index;
chips.forEach((chip, i) => {
const r = chip.getBoundingClientRect();
if (e.clientY >= r.top - 6 && e.clientY <= r.bottom + 6) {
if (i < chipDrag.index && e.clientX < r.left + r.width / 2) target = Math.min(target, i);
if (i > chipDrag.index && e.clientX > r.left + r.width / 2) target = Math.max(target, i);
}
});
if (target !== chipDrag.index) {
const items = [...topbarItems()];
items.splice(target, 0, ...items.splice(chipDrag.index, 1));
layout.header = { items };
chipDrag.index = target;
chipDrag.moved = true;
renderTopbar();
renderBars();
}
}
function endChipDrag(e) {
if (e.pointerId !== chipDrag.pointerId) return;
clearTimeout(chipDrag.timer);
document.removeEventListener("pointermove", moveChipDrag);
document.removeEventListener("pointerup", endChipDrag);
document.removeEventListener("pointercancel", endChipDrag);
document.removeEventListener("touchmove", blockChipScroll);
document.body.classList.remove("dragging");
if (chipDrag.active) {
drag.suppressUntil = Date.now() + 400;
if (chipDrag.moved) markDirty();
renderTopbar();
}
Object.assign(chipDrag, { index: -1, start: null, active: false, pointerId: null, moved: false });
}
// One sheet for adding (index -1) and for one item's settings.
function openTopbarSheet(index) {
if (index !== topbarSheetIndex) iconPickerOpen = false;
topbarSheetIndex = index;
renderTopbarSheet();
if (!$("#topbar-sheet").open) $("#topbar-sheet").showModal();
}
$("#topbar-sheet").addEventListener("close", () => { topbarSheetIndex = null; });
function sheetHead(badge, title, subtitle) {
const head = node("div", undefined, "sheet-head"), titles = node("div");
titles.append(node("strong", title), node("small", subtitle));
const close = node("button", "✕", "quiet sheet-close");
close.type = "button";
close.setAttribute("aria-label", "Sluiten");
close.onclick = () => $("#topbar-sheet").close();
head.append(badge, titles, close);
return head;
}
function optionButton(cp, title, detail, onClick, disabled = false) {
const b = node("button", undefined, "topbar-option");
b.type = "button";
b.disabled = disabled;
const texts = node("span");
texts.append(node("strong", title), node("small", detail));
b.append(node("span", cp ? glyph(cp) : "", "mdi"), texts);
b.onclick = onClick;
return b;
}
function renderTopbarSheet() {
const sheet = $("#topbar-sheet");
sheet.replaceChildren();
if (topbarSheetIndex === -1) return renderTopbarAdd(sheet);
const item = topbarItems()[topbarSheetIndex];
if (!item) return sheet.close();
const badge = node("span", "", "domain-icon mdi");
const body = node("div", undefined, "sheet-body");
if (item.type === "entity") {
const view = topbarView(item);
badge.textContent = view.icon ? glyph(view.icon) : "";
sheet.append(sheetHead(badge, entityName(item.entity), item.entity));
const live = node("div", undefined, "topbar-live");
live.id = "topbar-live";
body.append(live);
// Choices apply live; an icon pick keeps the open picker (search, scroll) and only refreshes the samples.
const update = (patch) => {
const items = [...topbarItems()];
items[topbarSheetIndex] = { ...items[topbarSheetIndex], ...patch };
setTopbarItems(items);
renderTopbarLive();
const next = topbarView(items[topbarSheetIndex]);
badge.textContent = next.icon ? glyph(next.icon) : "";
};
const content = segmented(inventory.header.contents.map((c) => [c.key, c.label]), item.content, (v) => update({ content: v }));
const contentField = group("Wat laten zien", content);
contentField.append(node("small", "Laatst gewijzigd telt op het scherm zelf door: “Zojuist”, “5 min geleden”, “Gisteren”.", "field-hint"));
body.append(contentField);
body.append(iconPicker({
selected: item.icon,
automatic: topbarPreviews.get(itemKey(item))?.auto_icon || automaticIcon(item.entity),
autoLabel: "Automatisch (zoals Home Assistant)",
allowNone: true,
onPick: (name) => update({ icon: name }),
}));
const shows = segmented(inventory.header.shows.map((s) => [s.key, s.label]), item.show, (v) => update({ show: v }));
const showField = group("Tonen", shows);
showField.append(node("small", "Alleen als actief verbergt het onderdeel zolang het uit, dicht, weg of 0 is. Handig voor een open deur, een draaiende wasmachine of wie er thuis is.", "field-hint"));
body.append(showField);
} else {
badge.textContent = glyph(iconNamed(BUILTIN_ICONS[item.type])?.cp || "");
sheet.append(sheetHead(badge, topbarLabel(item), "Van het scherm zelf, werkt ook zonder Home Assistant"));
const live = node("div", undefined, "topbar-live");
live.id = "topbar-live";
body.append(live);
if (item.type !== "date") {
const format = segmented([["24", "24 uur"], ["12", "12 uur"]], (layout.settings?.clock_24h ?? true) ? "24" : "12", (v) => {
layout.settings = { ...Object.fromEntries(settingDefinitions.map(([key, , , value]) => [key, value])), ...layout.settings, clock_24h: v === "24" };
markDirty();
renderSettings();
renderTopbar();
renderBars();
renderTopbarLive();
});
const formatField = group("Notatie", format);
formatField.append(node("small", "Geldt voor elke klok op dit scherm, ook de kloktegels.", "field-hint"));
body.append(formatField);
}
}
const foot = node("div", undefined, "sheet-foot");
const remove = node("button", "Weghalen", "quiet danger");
remove.type = "button";
remove.onclick = () => removeTopbarItem(topbarSheetIndex);
const left = node("button", "← Naar links", "quiet"), right = node("button", "Naar rechts →", "quiet");
left.type = right.type = "button";
left.disabled = topbarSheetIndex === 0;
right.disabled = topbarSheetIndex >= topbarItems().length - 1;
left.onclick = () => { if (moveTopbarItem(topbarSheetIndex, topbarSheetIndex - 1)) { topbarSheetIndex--; renderTopbarSheet(); } };
right.onclick = () => { if (moveTopbarItem(topbarSheetIndex, topbarSheetIndex + 1)) { topbarSheetIndex++; renderTopbarSheet(); } };
const done = node("button", "Klaar");
done.type = "button";
done.onclick = () => sheet.close();
foot.append(remove, left, right, done);
sheet.append(body, foot);
renderTopbarLive();
}
// "Op het scherm": the item as the bar draws it, updated while choosing.
function renderTopbarLive() {
const live = $("#topbar-live"), item = topbarItems()[topbarSheetIndex];
if (!live || !item) return;
const view = topbarView(item);
const note = !view.shown ? "Nu verborgen: niet actief" : topbarOverflow.has(topbarSheetIndex) ? "Past nu niet naast de naam" : "Zo staat het op het scherm";
live.replaceChildren(node("small", note), itemSample(item));
}
function renderTopbarAdd(sheet) {
const badge = node("span", "+", "domain-icon");
sheet.append(sheetHead(badge, "Toevoegen aan de bovenbalk", `${topbarItems().length} van ${topbarMax()} plekken gebruikt`));
const body = node("div", undefined, "sheet-body");
const taken = new Set(topbarItems().map(itemKey));
const own = node("div", undefined, "topbar-options");
const samples = { clock: clockText(), analog: "Kleine wijzerplaat met de tijd", date: dateText() };
for (const builtin of inventory.header?.builtin || []) {
const item = { type: builtin.type };
own.append(optionButton(iconNamed(BUILTIN_ICONS[builtin.type])?.cp, builtin.label, taken.has(itemKey(item)) ? "Staat er al in" : samples[builtin.type], () => addTopbarItem(item), taken.has(itemKey(item))));
}
body.append(group("Van het scherm zelf", own));
const suggested = inventory.header?.suggestions?.[selected] || [];
if (suggested.length) {
const list = node("div", undefined, "topbar-options");
for (const s of suggested) {
const exists = taken.has(itemKey(s.item));
list.append(optionButton(s.icon || automaticIcon(s.item.entity), s.label, exists ? "Staat er al in" : [s.name, s.area].filter(Boolean).join(" · "), () => addTopbarItem(s.item), exists));
}
body.append(group("Suggesties uit Home Assistant", list));
}
const search = node("input");
search.type = "search";
search.placeholder = "Zoek op naam, ruimte of entiteit, bijv. temperatuur of deur";
const results = node("div", undefined, "topbar-results");
const renderMatches = () => {
const query = search.value.trim().toLocaleLowerCase();
const matches = inventory.entities.filter((e) => `${e.name} ${e.id} ${e.area} ${e.device}`.toLocaleLowerCase().includes(query));
results.replaceChildren(...matches.slice(0, 40).map((e) => {
const item = { type: "entity", entity: e.id, content: "state", icon: "auto", show: "always" };
return optionButton(automaticIcon(e.id), e.name, [e.area, e.id].filter(Boolean).join(" · "), () => addTopbarItem(item), taken.has(itemKey(item)));
}));
if (!matches.length) results.append(node("p", "Geen entiteiten gevonden.", "hint"));
else if (matches.length > 40) results.append(node("p", `${matches.length} resultaten. Typ verder om te verfijnen.`, "hint"));
};
search.oninput = renderMatches;
search.setAttribute("aria-label", "Zoek een entiteit voor de bovenbalk");
const searchField = group("Een entiteit", search);
searchField.append(results);
body.append(searchField);
renderMatches();
const foot = node("div", undefined, "sheet-foot");
const cancel = node("button", "Annuleren", "quiet");
cancel.type = "button";
cancel.onclick = () => sheet.close();
foot.append(cancel);
sheet.append(body, foot);
}
// A click in the picker: the marked empty cell, else the first free cell.
function addTile(id) {
if (layout.tiles.some((t) => t.entity === id) || layout.tiles.length >= tileLimit()) return;
@@ -1481,6 +2030,13 @@ function poll() {
}
listen();
poll();
// The mockup's clocks tick and entity values in the top bar follow Home Assistant while the page is open.
setInterval(() => {
if (!layout || document.hidden || drag.active || chipDrag.active) return;
loadTopbarPreview(0);
renderTopbar();
renderBars();
}, 30000);
document.addEventListener("visibilitychange", async () => {
if (document.hidden) return;
lastFull = Date.now();
@@ -1575,9 +2131,6 @@ function openSection(id) {
if (section.tagName === "DETAILS") section.open = true;
section.scrollIntoView({ behavior: "smooth", block: "start" });
}
$("#nav-tiles").onclick = () => openSection("#tile-section");
$("#nav-settings").onclick = () => openSection("#general-settings");
$("#nav-inspector").onclick = () => inspect();
async function inspect(entity) {
if (!selected) return;
openSection("#inspector-section");
Binary file not shown.
Binary file not shown.
+25 -13
View File
@@ -85,19 +85,30 @@
</div>
<span id="delivery" class="badge"></span>
</div>
<label
>Naam bovenaan het scherm<input
id="title"
maxlength="60"
placeholder="Bijvoorbeeld: Woonkamer"
/></label>
<nav class="editor-nav" aria-label="Scherm beheren">
<button id="nav-tiles" class="quiet">Tegels instellen</button>
<button id="nav-settings" class="quiet">
Algemene instellingen
</button>
<button id="nav-inspector" class="quiet">Inspector</button>
</nav>
<section class="topbar-editor" id="topbar" aria-labelledby="topbar-title">
<div class="section-title">
<h3 id="topbar-title">Bovenbalk</h3>
<span id="topbar-count"></span>
</div>
<div class="topbar-fields">
<label class="topbar-name"
>Links: naam<input
id="title"
maxlength="60"
placeholder="Bijvoorbeeld: Woonkamer"
/></label>
<div class="topbar-right">
<span class="topbar-caption" id="topbar-caption">Rechts: tijd, sensoren of een klok</span>
<div
id="topbar-chips"
class="topbar-chips"
role="list"
aria-labelledby="topbar-caption"
></div>
</div>
</div>
<p class="hint" id="topbar-hint"></p>
</section>
<div class="columns" id="tile-section">
<div class="tile-editor">
<div class="section-title">
@@ -311,6 +322,7 @@
<pre id="firmware-log"></pre>
</dialog>
<dialog id="tile-sheet" class="tile-sheet" aria-label="Tegel instellen"></dialog>
<dialog id="topbar-sheet" class="tile-sheet" aria-label="Bovenbalk"></dialog>
<dialog id="alerts-dialog" class="alerts" aria-label="Alerts">
<div class="dialog-head">
<div>
+58 -13
View File
@@ -792,19 +792,6 @@ pre {
cursor: auto;
}
.editor-nav {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 20px 0;
padding: 12px;
background: #eaf3fc;
border-radius: 14px;
}
.editor-nav button {
background: white;
border: 1px solid #c7d9ea;
}
.tile.selected-tile {
border-color: #009fe3;
background: #f0f9ff;
@@ -1157,3 +1144,61 @@ pre {
.alerts td:first-child code { font-size: 14px; }
.copy-line > pre { flex-basis: 100%; }
}
/* Top bar: the name on the left, up to six items on the right. */
.topbar-editor { margin-top: 4px; padding: 16px 18px 12px; border: 1px solid var(--line); border-radius: 16px; background: #f7f9fc; scroll-margin-top: 16px; transition: box-shadow 0.3s; }
.topbar-editor.flash { box-shadow: 0 0 0 3px #9dbcf5; }
.topbar-editor h3 { margin: 0; }
.topbar-fields { display: grid; grid-template-columns: minmax(180px, 2fr) 5fr; gap: 16px; margin-top: 10px; align-items: start; }
.topbar-name { font-size: 13px; }
.topbar-name input { margin-top: 6px; }
.topbar-caption { display: block; font-size: 13px; font-weight: 600; margin-bottom: 6px; }
.topbar-chips { display: flex; flex-wrap: wrap; gap: 8px; min-height: 46px; }
.topbar-chip { position: relative; display: flex; align-items: center; gap: 8px; max-width: 260px; min-height: 46px; padding: 6px 30px 6px 8px; background: white; border: 1px solid #d5dce5; border-radius: 12px; cursor: grab; user-select: none; touch-action: pan-y; }
.topbar-chip:hover { border-color: #9eb6cf; box-shadow: 0 2px 7px #253f5010; }
.topbar-chip:focus-visible { outline: 3px solid #83b5ff; outline-offset: 2px; }
.topbar-chip .chip-icon { display: grid; place-items: center; width: 30px; height: 30px; flex: none; border-radius: 9px; background: #f0f2f5; color: #46525e; font-size: 19px; }
.chip-text { display: grid; min-width: 0; line-height: 1.25; }
.chip-text strong { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chip-text small { font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chip-remove { position: absolute; top: 50%; right: 5px; transform: translateY(-50%); width: 22px; height: 22px; padding: 0; border-radius: 50%; background: transparent; color: var(--muted); font-size: 11px; line-height: 1; display: grid; place-items: center; opacity: 0; transition: opacity 0.15s; }
.topbar-chip:hover .chip-remove, .topbar-chip:focus-within .chip-remove { opacity: 1; }
.chip-remove:hover { color: #b3261e; background: #fdecea; }
@media (hover: none) { .chip-remove { opacity: 1; } }
.topbar-chip.is-hidden { background: #fbfcfd; border-style: dashed; }
.topbar-chip.is-hidden .chip-icon, .topbar-chip.is-hidden strong { opacity: 0.55; }
.topbar-chip.is-overflow { border-style: dashed; border-color: #e0b36a; background: repeating-linear-gradient(135deg, #fff 0 8px, #fff6e6 8px 16px); }
.topbar-chip.is-overflow small { color: #9a6200; }
.topbar-chip.dragging-chip { border: 2px dashed var(--accent); background: var(--soft); cursor: grabbing; }
.topbar-chip.just-added { animation: chip-added 1.2s ease-out; }
@keyframes chip-added { from { box-shadow: 0 0 0 4px #9dbcf5; } to { box-shadow: 0 0 0 0 #9dbcf500; } }
.topbar-add { min-height: 46px; padding: 8px 14px; border: 1px dashed #b9c4d0; border-radius: 12px; background: transparent; color: var(--accent); font-size: 13px; }
.topbar-add:hover:not(:disabled) { border-color: var(--accent); background: white; filter: none; }
#topbar-hint { margin: 10px 0 0; }
#topbar-hint.warn { color: #9a6200; }
@media (max-width: 700px) { .topbar-fields { grid-template-columns: 1fr; } .topbar-chip { max-width: 100%; } }
/* The bar on a mockup page: an SVG in the board's own pixels (Roboto and the tile icons, the same
placement rules as the firmware), scaled with the page. */
@font-face { font-family: "Bar Roboto"; src: url("bar-roboto-400.woff") format("woff"); font-weight: 400; font-display: block; }
@font-face { font-family: "Bar Roboto"; src: url("bar-roboto-500.woff") format("woff"); font-weight: 500; font-display: block; }
.preview-bar-wrap { margin: -4px 0 6px; border-radius: 8px; cursor: pointer; }
.preview-bar-wrap:hover { background: #dfe3e8; box-shadow: 0 0 0 5px #dfe3e8; }
.preview-bar { display: block; width: 100%; height: auto; overflow: visible; }
/* Top bar sheet. */
.topbar-options { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 8px; }
.topbar-option { display: flex; align-items: center; gap: 10px; padding: 8px 10px; background: white; color: var(--ink); border: 1px solid var(--line); border-radius: 12px; text-align: left; font-weight: 500; }
.topbar-option:hover:not(:disabled) { border-color: #9eb6cf; filter: none; box-shadow: 0 2px 7px #253f5010; }
.topbar-option .mdi { display: grid; place-items: center; width: 34px; height: 34px; flex: none; border-radius: 9px; background: #f0f2f5; color: #46525e; font-size: 21px; }
.topbar-option > span:last-child { display: grid; min-width: 0; }
.topbar-option strong { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.topbar-option small { font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.topbar-results { display: grid; gap: 6px; max-height: 260px; overflow: auto; margin-top: 8px; }
.topbar-results .topbar-option { width: 100%; }
.topbar-results .hint { margin: 4px 0; }
.topbar-live { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px 14px; border-radius: 12px; background: #e7e7e7; }
.topbar-live small { color: #52606d; font-weight: 500; }
.topbar-sample { display: block; height: auto; max-width: 60%; overflow: visible; }
#topbar-sheet .sheet-head .domain-icon { background: #f0f2f5; color: #46525e; }
.icon-choice.icon-none .mdi { width: 22px; height: 22px; border: 1.5px dashed #b9c4d0; border-radius: 6px; }