diff --git a/CHANGELOG.md b/CHANGELOG.md index d819683c..9cfd98fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable changes to this project will be documented in this file. +## [2.3.4] - 11/2026 + +### Fixed + +- **The SPAN Panel card and the sidebar dashboard now show a panel and each of its battery, charger and solar devices by the name you gave it in Home + Assistant**, where a renamed device kept the name the integration gave it. + +- **A SPAN Panel card opened while Home Assistant is starting or restarting, or while the integration retries a panel it cannot reach, says it is waiting for + the panel to load and draws the panel once it has loaded**, where it showed "Unable to connect to SPAN Panel" until Retry was pressed or the dashboard was + opened again. + ## [2.3.3] - 11/2026 **Install 2.3.3 before your panel updates to firmware r202645**, which gives the panel's circuits new device IDs: 2.3.3 carries every circuit entity, device, diff --git a/custom_components/span_panel/additions.py b/custom_components/span_panel/additions.py index 5f269113..5f36c1eb 100644 --- a/custom_components/span_panel/additions.py +++ b/custom_components/span_panel/additions.py @@ -37,7 +37,7 @@ from .const import DOMAIN from .extension import is_extension_unique_id from .notices import async_raise, read_translations -from .util import ADOPTED_IDENTIFIER_TOKEN +from .util import ADOPTED_IDENTIFIER_TOKEN, device_display_name if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry @@ -368,7 +368,7 @@ def _adopted_device_name( token = f"_{ADOPTED_IDENTIFIER_TOKEN}_" if not any(token in identifier for _domain, identifier in device.identifiers): return None - return device.name_by_user or device.name or registry_entry.entity_id + return device_display_name(device) or registry_entry.entity_id def _extension_device_name( @@ -392,7 +392,7 @@ def _extension_device_name( device = devices.async_get(registry_entry.device_id) if device is None: return None - return device.name_by_user or device.name or registry_entry.entity_id + return device_display_name(device) or registry_entry.entity_id def _label(devices: dr.DeviceRegistry, registry_entry: er.RegistryEntry) -> str: @@ -443,7 +443,7 @@ def _own_device_name(devices: dr.DeviceRegistry, registry_entry: er.RegistryEntr return None if isinstance(device, dr.DeviceEntry) and device.via_device_id is None: return None - return device.name_by_user or device.name + return device_display_name(device) async def async_forget_announcements(hass: HomeAssistant, entry: ConfigEntry) -> None: diff --git a/custom_components/span_panel/circuit_object_ids.py b/custom_components/span_panel/circuit_object_ids.py index 8cca902f..1b2aa8c0 100644 --- a/custom_components/span_panel/circuit_object_ids.py +++ b/custom_components/span_panel/circuit_object_ids.py @@ -132,7 +132,7 @@ class here that defines an add or remove hook defines from .id_builder import build_circuit_device_identifier from .naming import circuit_object_id_suffix, suffix_wordings, without_core_number from .runtime import SpanPanelConfigEntry, SpanPanelRuntimeData, loaded_runtime_data -from .util import circuit_id_of_device, effective_circuit_device_name +from .util import circuit_id_of_device, device_display_name, effective_circuit_device_name _LOGGER = logging.getLogger(__name__) @@ -277,7 +277,7 @@ def compose_circuit_object_id( composed_device_name = device_name area_id = device_area_id if device_area_id is None and panel is not None: - panel_name = panel.name_by_user or panel.name + panel_name = device_display_name(panel) area_id = panel.area_id area_name: str | None = None diff --git a/custom_components/span_panel/conversion_repairs.py b/custom_components/span_panel/conversion_repairs.py index 508c1504..9d097e2a 100644 --- a/custom_components/span_panel/conversion_repairs.py +++ b/custom_components/span_panel/conversion_repairs.py @@ -104,6 +104,7 @@ from .entry_issues import EntryIssue, EntryIssueFamily, async_create_entry_issue from .id_builder import build_switch_unique_id from .runtime import SpanPanelConfigEntry, loaded_runtime_data +from .util import device_display_name _TRANSLATION_KEY: Final = "circuit_devices_converted" @@ -243,7 +244,7 @@ def _panel_name(hass: HomeAssistant, entry: SpanPanelConfigEntry) -> str: runtime_data = loaded_runtime_data(entry) if runtime_data is not None: device = dr.async_get(hass).async_get(runtime_data.panel_device_id) - if device is not None and (name := device.name_by_user or device.name): + if device is not None and (name := device_display_name(device)): return name return entry.title diff --git a/custom_components/span_panel/frontend/dist/span-panel-card.js b/custom_components/span_panel/frontend/dist/span-panel-card.js index 4cb6f4c0..46454b6f 100644 --- a/custom_components/span_panel/frontend/dist/span-panel-card.js +++ b/custom_components/span_panel/frontend/dist/span-panel-card.js @@ -1,10 +1,10 @@ -let t="en";const e={en:{"tab.panel":"Panel","tab.by_panel":"By Panel","tab.by_activity":"By Activity","tab.by_area":"By Area","tab.monitoring":"Monitoring","tab.settings":"Settings","tab.adopted":"Adopted","list.search_placeholder":"Search circuits...","list.unassigned_area":"Unassigned","list.no_results":"No circuits found","monitoring.heading":"Monitoring","monitoring.global_settings":"Global Settings","monitoring.enabled":"Enabled","monitoring.continuous":"Continuous (%)","monitoring.spike":"Spike (%)","monitoring.window":"Window (min)","monitoring.cooldown":"Cooldown (min)","monitoring.monitored_points":"Monitored Points","monitoring.col.name":"Name","monitoring.col.continuous":"Continuous","monitoring.col.spike":"Spike","monitoring.col.window":"Window","monitoring.col.cooldown":"Cooldown","monitoring.rating":"Rating","monitoring.all_none":"All / None","monitoring.reset":"Reset","monitoring.limit_invalid":"Enter a whole number from {min} to {max}.","monitoring.enable_invalid":"Monitoring was not turned on: correct the fields marked.","monitoring.point_field":"{field} for {name}","monitoring.reset_point":"Reset {name}","monitoring.admin_only":"Only an administrator can change monitoring.","notification.heading":"Notification Settings","notification.targets":"Notify Targets","notification.none_selected":"None selected","notification.targets_button":"Notify Targets: {targets}","notification.no_targets":"No notify targets found","notification.all_targets":"All","notification.event_bus_target":"Event Bus (HA event bus)","notification.priority":"Priority","notification.priority.default":"Default","notification.priority.passive":"Passive","notification.priority.active":"Active","notification.priority.time_sensitive":"Time-sensitive","notification.priority.critical":"Critical","notification.hint.critical":"Overrides silent/DND","notification.hint.time_sensitive":"Breaks through Focus","notification.hint.passive":"Delivers silently","notification.hint.active":"Standard delivery","notification.title_template":"Title Template","notification.message_template":"Message Template","notification.placeholders":"Placeholders:","notification.event_bus_help":"Event Bus fires event type","notification.event_bus_payload":"with payload:","notification.test_label":"Test Notification","notification.test_button":"Send Test","notification.test_sending":"Sending...","notification.test_sent":"Test notification sent","error.prefix":"Error:","error.failed_save":"Failed to save","error.failed":"Failed","error.panel_offline":"SPAN Panel unreachable","error.panel_reconnected":"SPAN Panel reconnected","error.panel_offline_named":"{name} unreachable","error.panel_reconnected_named":"{name} reconnected","error.discovery_failed":"Unable to connect to SPAN Panel","error.relay_failed":"Unable to toggle relay","error.shedding_failed":"Unable to update shedding priority","error.threshold_failed":"Unable to save threshold","error.graph_horizon_failed":"Unable to update graph time horizon","error.favorites_fetch_failed":"Unable to load favorites","error.favorites_toggle_failed":"Unable to update favorite","error.history_failed":"Unable to load historical data","error.monitoring_failed":"Unable to load monitoring status","error.graph_settings_failed":"Unable to load graph settings","error.areas_failed":"Area assignments may be out of sync","error.retry":"Retry","card.connecting":"Connecting to SPAN Panel...","monitoringRating.none":"no rating","monitoringRating.copied":"{package} from your SPAN app (the panel publishes {panel} A)","monitoringRating.copied_unnamed":"Copied from your SPAN app","monitoringRating.judged_copied":"Judged against {rating} A: {copied}","settings.heading":"Settings","settings.description":"General integration settings (entity naming, device prefix, circuit numbers) are managed through the integration's options flow.","settings.open_link":"Open SPAN Panel Integration Settings","adopted.heading":"Adopted entities","adopted.description":"Vendor readings and adopted devices arrive with minimal metadata. Curate one to set its device class, statistics class, and prominence — saved changes reload the integration and apply from the next startup on.","adopted.filter_placeholder":"Filter by entity or device name","adopted.no_results":"No adopted entities match this filter","adopted.none":"This panel publishes nothing to curate.","adopted.load_failed":"Unable to load adopted entities","adopted.count":"{count} adopted","adopted.vendor_readings":"VENDOR READINGS","adopted.adopted_device":"ADOPTED DEVICE","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURATED","adopted.stale":"STALE","adopted.stale_note":"The panel no longer supports what was saved for: {fields}","adopted.enable_entity":"Enable entity","adopted.enabled":"ENABLED","adopted.disabled":"DISABLED","adopted.enable_note":"Enabled when saved — curating never enables on its own","adopted.registry_unavailable":"Enable and name become available once this entity exists in the registry.","adopted.name":"Name","adopted.device_class":"Device class","adopted.device_class_note":"choices limited by the panel's unit ({unit})","adopted.device_class_note_unitless":"choices limited by what the panel publishes","adopted.no_device_class":"No device class","adopted.statistics_class":"Statistics class","adopted.statistics_note":"long-term statistics begin after the next reload","adopted.no_statistics":"No statistics","adopted.prominence":"Prominence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Display unit","adopted.unit_as_published":"As published","adopted.precision":"Precision","adopted.precision_default":"Default","adopted.read_only":"read-only","adopted.settable":"settable","adopted.save":"Save","adopted.clear":"Clear curation","adopted.reload_note":"Saving reloads the SPAN Panel integration","adopted.saved":"Saved — the integration is reloading","adopted.confirm_heading":"Confirm statistics class","adopted.confirm_setting":"You are setting {name} to {value}.","adopted.confirm_clearing_subject":"You are clearing the statistics class on {name}.","adopted.confirm_total_increasing":"Total increasing treats every drop in the value as a meter reset. If this reading can decrease for any other reason, long-term statistics will be permanently corrupted — fixing the class later does not repair history already written.","adopted.confirm_clearing":"Long-term statistics stop being compiled for this entity, and Home Assistant raises a repair against the statistics already collected under the class you are removing.","adopted.save_anyway":"Save anyway","adopted.cancel":"Cancel","adopted.warn_total_increasing":"Saved as total increasing — every drop in the reading now counts as a meter reset.","adopted.warn_statistics_removed":"This entity has no statistics class any more; Home Assistant will raise a repair against the statistics already collected.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Panel monitoring settings","header.graph_settings":"Graph time horizon settings","header.site":"Site","header.grid":"Grid","header.upstream":"Upstream","header.downstream":"Downstream","header.solar":"Solar","header.battery":"Battery","header.toggle_units":"Toggle Watts / Amps","header.enable_switches":"Enable Switches","header.switches_enabled":"Switches Enabled","controls.admin_only":"Only an administrator can operate this panel's controls.","controls.disabled":"Control of this panel is switched off in its options.","controls.read_only":"Your Home Assistant account can't operate this panel's controls.","controls.entity_unauthorized":"Your Home Assistant account can't operate this control.","controls.not_operable":"You can't operate this panel's controls.","grid.unknown":"Unknown","grid.configure":"Configure circuit","grid.configure_subdevice":"Configure device","grid.on":"On","grid.off":"Off","grid.shared_switch":"Switches every circuit in this space","meters.title":"Meters","meters.importing":"importing","meters.exporting":"exporting","meters.imported":"imported","meters.exported":"exported","subdevice.ev_charger":"EV Charger","subdevice.battery":"Battery","subdevice.fallback":"Sub-device","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Power","subdevice.solar":"Solar","subdevice.solar_inverter":"Solar inverter","subdevice.site_total":"Site total","subdevice.in_site_total":"Included in the site total","sidepanel.graph_settings":"Graph Settings","sidepanel.global_defaults":"Global defaults for all circuits","sidepanel.favorites_subtitle":"Favorites","sidepanel.global_default":"Global Default","sidepanel.list_view_columns":"List View Columns","sidepanel.columns":"Columns","sidepanel.circuit_scales":"Circuit Graph Scales","sidepanel.subdevice_scales":"Sub-Device Graph Scales","sidepanel.reset_to_global":"Reset to global default","sidepanel.relay":"Relay","sidepanel.breaker":"Breaker","sidepanel.capacity":"{amps} A capacity","monitoringRating.title":"Breaker ratings from the SPAN app","monitoringRating.panel_rating":"Panel publishes {panel} A","monitoringRating.other_breaker":"Other breaker (A)","monitoringRating.other_breaker_label":"Other breaker in the space of {circuit}","monitoringRating.reset":"Remove copied ratings","monitoringRating.invalid_other":"Enter the other breaker's rating as a whole number of amps, 1 or more.","monitoringRating.guidance":"If your SPAN app shows two ratings for this circuit, such as 20-20A, enter the second one here. SPAN Panel MAIN 32 panels report only the first, and monitoring then judges this space against both breakers together.","monitoringRating.guidance_two_spaces":"If your SPAN app shows two ratings for this circuit, such as 20-30A, enter the second one here.","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 panels report only the average of this circuit's two legs, which can hide an overloaded leg. We recommend turning monitoring off for this circuit.","monitoringRating.turn_off_monitoring":"Turn off monitoring","monitoringRating.threshold_warning":"This circuit's custom thresholds are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass.","monitoringRating.threshold_warning_global":"The global thresholds this circuit uses are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass; change them under {settings} on the {tab} tab.","monitoringRating.use_global_thresholds":"Use global thresholds","monitoringRating.note_title":"Tandem breakers on SPAN Panel MAIN 32","monitoringRating.note_problem":"SPAN Panel MAIN 32 panels do not report which breakers are tandems, or the rating of a tandem's second breaker. A tandem puts two breakers in one space, but the panel reports it as one circuit with only the first breaker's rating, while one sensor reads both breakers together. A 20-20 tandem shows 20 A here and can carry 40 A, so monitoring raises false alerts on it.","monitoringRating.note_steps":"To fix this, copy the ratings from your SPAN app:","monitoringRating.note_step_find":"In the SPAN app, find each circuit whose breaker shows two ratings, such as 20-20A.","monitoringRating.note_step_enter":"In the table below, type the second rating in that circuit's {column} field. Then press Enter or move to the next field.","monitoringRating.note_step_single":"Leave the field empty for a circuit with a single breaker.","monitoringRating.note_judged":"Monitoring then judges that space against both breakers together: 40 A for a 20-20. Only monitoring uses the copy, and the circuit's Breaker Rating sensor still shows what the panel reports. To remove a copied rating, select ✕ beside its field.","monitoringRating.note_thresholds":"If you raised a tandem's thresholds above 100% to stop its alerts, select {reset} on its row. Those thresholds now apply to both breakers together.","monitoringRating.note_two_spaces":"For a circuit that spans two spaces, enter the second rating the same way if your SPAN app shows two, such as 20-30A. SPAN Panel MAIN 32 panels report only the average of such a circuit's two legs, which can hide an overloaded leg, so the copy can't be applied and we recommend turning monitoring off for that circuit.","monitoringRating.note_guide":"Read more in the guide to tandem and multi-load breakers.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remove copied ratings for {circuit}","monitoringRating.table_threshold_warning":"This circuit's thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Select {reset} to use the global thresholds.","monitoringRating.table_threshold_warning_global":"The global thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Change them under {settings} above.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Unable to update the ratings copied from the SPAN app","sidepanel.judged_against":"Judged against: {rating}","sidepanel.shedding_priority":"Shedding Priority","sidepanel.priority_label":"Priority","sidepanel.monitoring":"Monitoring","sidepanel.global":"Global","sidepanel.custom":"Custom","sidepanel.continuous_pct":"Continuous %","sidepanel.spike_pct":"Spike %","sidepanel.window_duration":"Window duration","sidepanel.cooldown":"Cooldown","sidepanel.favorite":"Favorite","sidepanel.save_to_favorites":"Save to favorites","panel.favorites":"Favorites","status.monitoring":"Monitoring","status.circuits":"circuits","status.mains":"mains","status.warning":"warning","status.warnings":"warnings","status.alert":"alert","status.alerts":"alerts","status.override":"override","status.overrides":"overrides","card.no_device":"Open the card editor and select your SPAN Panel device.","card.device_not_found":"Panel device not found. Check device_id in card config.","card.topology_error":"Topology response missing panel_size and no circuits found. Update the SPAN Panel integration.","card.panel_size_error":"Could not determine panel_size. No circuits found and no panel_size attribute. Update the SPAN Panel integration.","editor.panel_label":"SPAN Panel","editor.select_panel":"Select a panel...","editor.chart_window":"Chart time window","editor.days":"days","editor.hours":"hours","editor.minutes":"minutes","editor.chart_metric":"Chart metric","editor.visible_sections":"Visible sections","editor.panel_circuits":"Panel circuits","editor.battery_bess":"Battery (BESS)","editor.ev_charger_evse":"EV Charger (EVSE)","editor.solar_pv":"Solar (PV)","editor.no_entities":"No entities to show","editor.tab_style":"Tab Style","editor.tab_style_text":"Text","editor.tab_style_icon":"Icon","metric.power":"Power","metric.current":"Current","metric.soc":"State of Charge","metric.soe":"State of Energy","shedding.always_on":"Critical","shedding.never":"Non-sheddable","shedding.soc_threshold":"SoC Threshold","shedding.off_grid":"Sheddable","shedding.unknown":"Unknown","shedding.select.never":"Stays on in an outage","shedding.select.soc_threshold":"Stays on until battery threshold","shedding.select.off_grid":"Turns off in an outage"},es:{"tab.panel":"Panel","tab.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","tab.settings":"Configuración","tab.adopted":"Adoptadas","list.search_placeholder":"Buscar circuitos...","list.unassigned_area":"Sin asignar","list.no_results":"No se encontraron circuitos","monitoring.heading":"Monitoreo","monitoring.global_settings":"Configuración Global","monitoring.enabled":"Activado","monitoring.continuous":"Continuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Ventana (min)","monitoring.cooldown":"Enfriamiento (min)","monitoring.monitored_points":"Puntos Monitoreados","monitoring.col.name":"Nombre","monitoring.col.continuous":"Continuo","monitoring.col.spike":"Pico","monitoring.col.window":"Ventana","monitoring.col.cooldown":"Enfriamiento","monitoring.rating":"Calibre","monitoring.all_none":"Todos / Ninguno","monitoring.reset":"Restablecer","monitoring.limit_invalid":"Introduzca un número entero de {min} a {max}.","monitoring.enable_invalid":"No se activó el monitoreo: corrija los campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Restablecer {name}","monitoring.admin_only":"Solo un administrador puede cambiar el monitoreo.","notification.heading":"Configuración de Notificaciones","notification.targets":"Destinos de Notificación","notification.none_selected":"Ninguno seleccionado","notification.targets_button":"Destinos de Notificación: {targets}","notification.no_targets":"No se encontraron destinos de notificación","notification.all_targets":"Todos","notification.event_bus_target":"Bus de Eventos (bus de eventos de HA)","notification.priority":"Prioridad","notification.priority.default":"Predeterminado","notification.priority.passive":"Pasivo","notification.priority.active":"Activo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Anula silencio/No molestar","notification.hint.time_sensitive":"Atraviesa el modo Concentración","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega estándar","notification.title_template":"Plantilla de Título","notification.message_template":"Plantilla de Mensaje","notification.placeholders":"Variables:","notification.event_bus_help":"El Bus de Eventos dispara el tipo de evento","notification.event_bus_payload":"con datos:","notification.test_label":"Notificación de prueba","notification.test_button":"Enviar prueba","notification.test_sending":"Enviando...","notification.test_sent":"Notificación de prueba enviada","error.prefix":"Error:","error.failed_save":"Error al guardar","error.failed":"Falló","error.panel_offline":"SPAN Panel inaccesible","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inaccesible","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"No se puede conectar al SPAN Panel","error.relay_failed":"No se pudo cambiar el relé","error.shedding_failed":"No se pudo actualizar la prioridad de desconexión","error.threshold_failed":"No se pudo guardar el umbral","error.graph_horizon_failed":"No se pudo actualizar el horizonte temporal del gráfico","error.favorites_fetch_failed":"No se pudieron cargar los favoritos","error.favorites_toggle_failed":"No se pudo actualizar el favorito","error.history_failed":"No se pudieron cargar los datos históricos","error.monitoring_failed":"No se pudo cargar el estado de monitoreo","error.graph_settings_failed":"No se pudo cargar la configuración del gráfico","error.areas_failed":"Las asignaciones de áreas pueden estar desincronizadas","error.retry":"Reintentar","card.connecting":"Conectando al SPAN Panel...","monitoringRating.none":"sin calibre","monitoringRating.copied":"{package} de su app de SPAN (el panel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado de su app de SPAN","monitoringRating.judged_copied":"Evaluado según {rating} A: {copied}","settings.heading":"Configuración","settings.description":"La configuración general de la integración (nombres de entidades, prefijo de dispositivo, números de circuito) se administra a través del flujo de opciones de la integración.","settings.open_link":"Abrir Configuración de Integración SPAN Panel","adopted.heading":"Entidades adoptadas","adopted.description":"Las lecturas del proveedor y los dispositivos adoptados llegan con metadatos mínimos. Cura una para definir su clase de dispositivo, clase de estadísticas y prominencia — los cambios guardados recargan la integración y se aplican desde el siguiente arranque.","adopted.filter_placeholder":"Filtrar por nombre de entidad o dispositivo","adopted.no_results":"Ninguna entidad adoptada coincide con este filtro","adopted.none":"Este panel no publica nada que curar.","adopted.load_failed":"No se pudieron cargar las entidades adoptadas","adopted.count":"{count} adoptadas","adopted.vendor_readings":"LECTURAS DEL PROVEEDOR","adopted.adopted_device":"DISPOSITIVO ADOPTADO","adopted.via_panel":"vía SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"El panel ya no admite lo guardado para: {fields}","adopted.enable_entity":"Activar entidad","adopted.enabled":"ACTIVADA","adopted.disabled":"DESACTIVADA","adopted.enable_note":"Se activa al guardar — curar nunca activa por sí solo","adopted.registry_unavailable":"La activación y el nombre estarán disponibles cuando esta entidad exista en el registro.","adopted.name":"Nombre","adopted.device_class":"Clase de dispositivo","adopted.device_class_note":"opciones limitadas por la unidad del panel ({unit})","adopted.device_class_note_unitless":"opciones limitadas por lo que publica el panel","adopted.no_device_class":"Sin clase de dispositivo","adopted.statistics_class":"Clase de estadísticas","adopted.statistics_note":"las estadísticas a largo plazo comienzan tras la próxima recarga","adopted.no_statistics":"Sin estadísticas","adopted.prominence":"Prominencia","adopted.diagnostic":"Diagnóstico","adopted.standard":"Estándar","adopted.display_unit":"Unidad mostrada","adopted.unit_as_published":"Tal como se publica","adopted.precision":"Precisión","adopted.precision_default":"Predeterminada","adopted.read_only":"solo lectura","adopted.settable":"editable","adopted.save":"Guardar","adopted.clear":"Borrar curación","adopted.reload_note":"Guardar recarga la integración SPAN Panel","adopted.saved":"Guardado — la integración se está recargando","adopted.confirm_heading":"Confirmar clase de estadísticas","adopted.confirm_setting":"Vas a definir {name} como {value}.","adopted.confirm_clearing_subject":"Vas a borrar la clase de estadísticas de {name}.","adopted.confirm_total_increasing":"Total creciente interpreta cada caída del valor como un reinicio del contador. Si esta lectura puede disminuir por cualquier otro motivo, las estadísticas a largo plazo quedarán corrompidas de forma permanente — corregir la clase más tarde no repara el historial ya escrito.","adopted.confirm_clearing":"Dejarán de compilarse estadísticas a largo plazo para esta entidad, y Home Assistant abrirá una reparación sobre las estadísticas ya recogidas bajo la clase que estás quitando.","adopted.save_anyway":"Guardar de todos modos","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Guardado como total creciente — cada caída de la lectura cuenta ahora como un reinicio del contador.","adopted.warn_statistics_removed":"Esta entidad ya no tiene clase de estadísticas; Home Assistant abrirá una reparación sobre las estadísticas ya recogidas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configuración de monitoreo del panel","header.graph_settings":"Configuración del horizonte temporal del gráfico","header.site":"Sitio","header.grid":"Red","header.upstream":"Aguas arriba","header.downstream":"Aguas abajo","header.solar":"Solar","header.battery":"Batería","header.toggle_units":"Alternar Watts / Amperios","header.enable_switches":"Habilitar Interruptores","header.switches_enabled":"Interruptores Habilitados","controls.admin_only":"Solo un administrador puede operar los controles de este panel.","controls.disabled":"El control de este panel está desactivado en sus opciones.","controls.read_only":"Su cuenta de Home Assistant no puede operar los controles de este panel.","controls.entity_unauthorized":"Su cuenta de Home Assistant no puede operar este control.","controls.not_operable":"No puede operar los controles de este panel.","grid.unknown":"Desconocido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Enc","grid.off":"Apag","grid.shared_switch":"Conmuta todos los circuitos de este espacio","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Cargador EV","subdevice.battery":"Batería","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potencia","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total del sitio","subdevice.in_site_total":"Incluido en el total del sitio","sidepanel.graph_settings":"Configuración de Gráficos","sidepanel.global_defaults":"Valores predeterminados globales para todos los circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Predeterminado Global","sidepanel.list_view_columns":"Columnas de la lista","sidepanel.columns":"Columnas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Restablecer al valor global","sidepanel.relay":"Relé","sidepanel.breaker":"Interruptor","sidepanel.capacity":"capacidad de {amps} A","monitoringRating.title":"Calibres de interruptor de la app de SPAN","monitoringRating.panel_rating":"El panel publica {panel} A","monitoringRating.other_breaker":"Otro interruptor (A)","monitoringRating.other_breaker_label":"Otro interruptor en el espacio de {circuit}","monitoringRating.reset":"Quitar los calibres copiados","monitoringRating.invalid_other":"Introduzca el calibre del otro interruptor como un número entero de amperios, 1 o más.","monitoringRating.guidance":"Si su app de SPAN muestra dos calibres para este circuito, como 20-20A, introduzca aquí el segundo. Los paneles SPAN Panel MAIN 32 informan solo el primero, y el monitoreo juzga entonces este espacio según ambos interruptores juntos.","monitoringRating.guidance_two_spaces":"Si su app de SPAN muestra dos calibres para este circuito, como 20-30A, introduzca aquí el segundo.","monitoringRating.averaged_legs":"Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de este circuito, lo que puede ocultar una fase sobrecargada. Recomendamos desactivar el monitoreo de este circuito.","monitoringRating.turn_off_monitoring":"Desactivar el monitoreo","monitoringRating.threshold_warning":"Los umbrales personalizados de este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real.","monitoringRating.threshold_warning_global":"Los umbrales globales que usa este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real; cámbielos en {settings}, en la pestaña {tab}.","monitoringRating.use_global_thresholds":"Usar los umbrales globales","monitoringRating.note_title":"Interruptores tándem en SPAN Panel MAIN 32","monitoringRating.note_problem":"Los paneles SPAN Panel MAIN 32 no informan qué interruptores son tándem ni el calibre del segundo interruptor de un tándem. Un tándem pone dos interruptores en un espacio, pero el panel lo informa como un solo circuito con solo el calibre del primer interruptor, mientras un solo sensor lee ambos interruptores juntos. Un tándem 20-20 muestra 20 A aquí y puede llevar 40 A, por lo que el monitoreo genera falsas alertas en él.","monitoringRating.note_steps":"Para corregirlo, copie los calibres de su app de SPAN:","monitoringRating.note_step_find":"En la app de SPAN, busque cada circuito cuyo interruptor muestre dos calibres, como 20-20A.","monitoringRating.note_step_enter":"En la tabla de abajo, escriba el segundo calibre en el campo {column} de ese circuito. Luego pulse Intro o pase al siguiente campo.","monitoringRating.note_step_single":"Deje el campo vacío para un circuito con un solo interruptor.","monitoringRating.note_judged":"El monitoreo juzga entonces ese espacio según ambos interruptores juntos: 40 A para un 20-20. Solo el monitoreo usa la copia, y el sensor Breaker Rating del circuito sigue mostrando lo que informa el panel. Para quitar un calibre copiado, seleccione ✕ junto a su campo.","monitoringRating.note_thresholds":"Si subió los umbrales de un tándem por encima del 100 % para detener sus alertas, seleccione {reset} en su fila. Esos umbrales se aplican ahora a ambos interruptores juntos.","monitoringRating.note_two_spaces":"Para un circuito que ocupa dos espacios, introduzca el segundo calibre del mismo modo si su app de SPAN muestra dos, como 20-30A. Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de un circuito así, lo que puede ocultar una fase sobrecargada, por lo que la copia no se puede aplicar y recomendamos desactivar el monitoreo de ese circuito.","monitoringRating.note_guide":"Lea más en la guía de interruptores tándem y de cargas múltiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Quitar los calibres copiados de {circuit}","monitoringRating.table_threshold_warning":"Los umbrales de este circuito superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Seleccione {reset} para usar los umbrales globales.","monitoringRating.table_threshold_warning_global":"Los umbrales globales superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Cámbielos en {settings}, arriba.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"No se pudieron actualizar los calibres copiados de la app de SPAN","sidepanel.judged_against":"Evaluado según: {rating}","sidepanel.shedding_priority":"Prioridad de Desconexción","sidepanel.priority_label":"Prioridad","sidepanel.monitoring":"Monitoreo","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Continuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duración de ventana","sidepanel.cooldown":"Enfriamiento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Guardar en favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoreo","status.circuits":"circuitos","status.mains":"alimentación","status.warning":"advertencia","status.warnings":"advertencias","status.alert":"alerta","status.alerts":"alertas","status.override":"anulación","status.overrides":"anulaciones","card.no_device":"Abra el editor de tarjeta y seleccione su dispositivo SPAN Panel.","card.device_not_found":"Dispositivo de panel no encontrado. Verifique device_id en la configuración de la tarjeta.","card.topology_error":"La respuesta de topología no contiene panel_size y no se encontraron circuitos. Actualice la integración SPAN Panel.","card.panel_size_error":"No se pudo determinar panel_size. No se encontraron circuitos ni atributo panel_size. Actualice la integración SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Seleccione un panel...","editor.chart_window":"Ventana de tiempo del gráfico","editor.days":"días","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica del gráfico","editor.visible_sections":"Secciones visibles","editor.panel_circuits":"Circuitos del panel","editor.battery_bess":"Batería (BESS)","editor.ev_charger_evse":"Cargador EV (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"No hay entidades para mostrar","editor.tab_style":"Estilo de pestañas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícono","metric.power":"Potencia","metric.current":"Corriente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energía","shedding.always_on":"Crítico","shedding.never":"No desconectable","shedding.soc_threshold":"Umbral SoC","shedding.off_grid":"Desconectable","shedding.unknown":"Desconocido","shedding.select.never":"Permanece encendido en un corte","shedding.select.soc_threshold":"Encendido hasta umbral de batería","shedding.select.off_grid":"Se apaga en un corte"},fr:{"tab.panel":"Panneau","tab.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","tab.settings":"Paramètres","tab.adopted":"Adoptées","list.search_placeholder":"Rechercher des circuits...","list.unassigned_area":"Non attribué","list.no_results":"Aucun circuit trouvé","monitoring.heading":"Surveillance","monitoring.global_settings":"Paramètres Globaux","monitoring.enabled":"Activé","monitoring.continuous":"Continu (%)","monitoring.spike":"Pic (%)","monitoring.window":"Fenêtre (min)","monitoring.cooldown":"Refroidissement (min)","monitoring.monitored_points":"Points Surveillés","monitoring.col.name":"Nom","monitoring.col.continuous":"Continu","monitoring.col.spike":"Pic","monitoring.col.window":"Fenêtre","monitoring.col.cooldown":"Refroidissement","monitoring.rating":"Calibre","monitoring.all_none":"Tous / Aucun","monitoring.reset":"Réinitialiser","monitoring.limit_invalid":"Saisissez un nombre entier de {min} à {max}.","monitoring.enable_invalid":"La surveillance n'a pas été activée : corrigez les champs signalés.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Réinitialiser {name}","monitoring.admin_only":"Seul un administrateur peut modifier la surveillance.","notification.heading":"Paramètres de Notification","notification.targets":"Cibles de Notification","notification.none_selected":"Aucune sélection","notification.targets_button":"Cibles de Notification : {targets}","notification.no_targets":"Aucune cible de notification trouvée","notification.all_targets":"Tous","notification.event_bus_target":"Bus d'événements (bus d'événements HA)","notification.priority":"Priorité","notification.priority.default":"Par défaut","notification.priority.passive":"Passif","notification.priority.active":"Actif","notification.priority.time_sensitive":"Urgent","notification.priority.critical":"Critique","notification.hint.critical":"Outrepasse silencieux/NPD","notification.hint.time_sensitive":"Traverse le mode Concentration","notification.hint.passive":"Livraison silencieuse","notification.hint.active":"Livraison standard","notification.title_template":"Modèle de Titre","notification.message_template":"Modèle de Message","notification.placeholders":"Variables :","notification.event_bus_help":"Le Bus d'événements déclenche le type d'événement","notification.event_bus_payload":"avec les données :","notification.test_label":"Notification de test","notification.test_button":"Envoyer un test","notification.test_sending":"Envoi...","notification.test_sent":"Notification de test envoyée","error.prefix":"Erreur :","error.failed_save":"Échec de la sauvegarde","error.failed":"Échoué","error.panel_offline":"SPAN Panel inaccessible","error.panel_reconnected":"SPAN Panel reconnecté","error.panel_offline_named":"{name} inaccessible","error.panel_reconnected_named":"{name} reconnecté","error.discovery_failed":"Impossible de se connecter au SPAN Panel","error.relay_failed":"Impossible de basculer le relais","error.shedding_failed":"Impossible de mettre à jour la priorité de délestage","error.threshold_failed":"Impossible d'enregistrer le seuil","error.graph_horizon_failed":"Impossible de mettre à jour l'horizon temporel du graphique","error.favorites_fetch_failed":"Impossible de charger les favoris","error.favorites_toggle_failed":"Impossible de mettre à jour le favori","error.history_failed":"Impossible de charger les données historiques","error.monitoring_failed":"Impossible de charger l'état de surveillance","error.graph_settings_failed":"Impossible de charger les paramètres du graphique","error.areas_failed":"Les affectations de zones peuvent être désynchronisées","error.retry":"Réessayer","card.connecting":"Connexion au SPAN Panel...","monitoringRating.none":"aucun calibre","monitoringRating.copied":"{package} depuis votre application SPAN (le panneau publie {panel} A)","monitoringRating.copied_unnamed":"Copié depuis votre application SPAN","monitoringRating.judged_copied":"Évalué selon {rating} A : {copied}","settings.heading":"Paramètres","settings.description":"Les paramètres généraux de l'intégration (noms d'entités, préfixe de l'appareil, numéros de circuit) sont gérés via le flux d'options de l'intégration.","settings.open_link":"Ouvrir les Paramètres d'Intégration SPAN Panel","adopted.heading":"Entités adoptées","adopted.description":"Les relevés du fournisseur et les appareils adoptés arrivent avec des métadonnées minimales. Curez-en un pour définir sa classe d'appareil, sa classe de statistiques et sa proéminence — les modifications enregistrées rechargent l'intégration et s'appliquent dès le prochain démarrage.","adopted.filter_placeholder":"Filtrer par nom d'entité ou d'appareil","adopted.no_results":"Aucune entité adoptée ne correspond à ce filtre","adopted.none":"Ce panneau ne publie rien à curer.","adopted.load_failed":"Impossible de charger les entités adoptées","adopted.count":"{count} adoptées","adopted.vendor_readings":"RELEVÉS DU FOURNISSEUR","adopted.adopted_device":"APPAREIL ADOPTÉ","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURÉE","adopted.stale":"OBSOLÈTE","adopted.stale_note":"Le panneau ne prend plus en charge ce qui a été enregistré pour : {fields}","adopted.enable_entity":"Activer l'entité","adopted.enabled":"ACTIVÉE","adopted.disabled":"DÉSACTIVÉE","adopted.enable_note":"Activée à l'enregistrement — la curation n'active jamais d'elle-même","adopted.registry_unavailable":"L'activation et le nom seront disponibles dès que cette entité existera dans le registre.","adopted.name":"Nom","adopted.device_class":"Classe d'appareil","adopted.device_class_note":"choix limités par l'unité du panneau ({unit})","adopted.device_class_note_unitless":"choix limités par ce que le panneau publie","adopted.no_device_class":"Aucune classe d'appareil","adopted.statistics_class":"Classe de statistiques","adopted.statistics_note":"les statistiques à long terme commencent après le prochain rechargement","adopted.no_statistics":"Aucune statistique","adopted.prominence":"Proéminence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Unité affichée","adopted.unit_as_published":"Telle que publiée","adopted.precision":"Précision","adopted.precision_default":"Par défaut","adopted.read_only":"lecture seule","adopted.settable":"modifiable","adopted.save":"Enregistrer","adopted.clear":"Effacer la curation","adopted.reload_note":"L'enregistrement recharge l'intégration SPAN Panel","adopted.saved":"Enregistré — l'intégration se recharge","adopted.confirm_heading":"Confirmer la classe de statistiques","adopted.confirm_setting":"Vous définissez {name} sur {value}.","adopted.confirm_clearing_subject":"Vous effacez la classe de statistiques de {name}.","adopted.confirm_total_increasing":"Total croissant interprète chaque baisse de la valeur comme une remise à zéro du compteur. Si ce relevé peut diminuer pour une autre raison, les statistiques à long terme seront corrompues de façon permanente — corriger la classe plus tard ne répare pas l'historique déjà écrit.","adopted.confirm_clearing":"Les statistiques à long terme cesseront d'être compilées pour cette entité, et Home Assistant ouvrira une réparation sur les statistiques déjà collectées sous la classe que vous retirez.","adopted.save_anyway":"Enregistrer quand même","adopted.cancel":"Annuler","adopted.warn_total_increasing":"Enregistré en total croissant — chaque baisse du relevé compte désormais comme une remise à zéro du compteur.","adopted.warn_statistics_removed":"Cette entité n'a plus de classe de statistiques ; Home Assistant ouvrira une réparation sur les statistiques déjà collectées.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Paramètres de surveillance du panneau","header.graph_settings":"Paramètres d'horizon temporel du graphique","header.site":"Site","header.grid":"Réseau","header.upstream":"Amont","header.downstream":"Aval","header.solar":"Solaire","header.battery":"Batterie","header.toggle_units":"Basculer Watts / Ampères","header.enable_switches":"Activer les interrupteurs","header.switches_enabled":"Interrupteurs activés","controls.admin_only":"Seul un administrateur peut utiliser les commandes de ce panneau.","controls.disabled":"La commande de ce panneau est désactivée dans ses options.","controls.read_only":"Votre compte Home Assistant ne peut pas utiliser les commandes de ce panneau.","controls.entity_unauthorized":"Votre compte Home Assistant ne peut pas utiliser cette commande.","controls.not_operable":"Vous ne pouvez pas utiliser les commandes de ce panneau.","grid.unknown":"Inconnu","grid.configure":"Configurer le circuit","grid.configure_subdevice":"Configurer l'appareil","grid.on":"On","grid.off":"Off","grid.shared_switch":"Commute tous les circuits de cet emplacement","meters.title":"Compteurs","meters.importing":"en import","meters.exporting":"en export","meters.imported":"importés","meters.exported":"exportés","subdevice.ev_charger":"Chargeur VE","subdevice.battery":"Batterie","subdevice.fallback":"Sous-appareil","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Puissance","subdevice.solar":"Solaire","subdevice.solar_inverter":"Onduleur solaire","subdevice.site_total":"Total du site","subdevice.in_site_total":"Inclus dans le total du site","sidepanel.graph_settings":"Paramètres des Graphiques","sidepanel.global_defaults":"Valeurs par défaut globales pour tous les circuits","sidepanel.favorites_subtitle":"Favoris","sidepanel.global_default":"Défaut Global","sidepanel.list_view_columns":"Colonnes de la liste","sidepanel.columns":"Colonnes","sidepanel.circuit_scales":"Échelles des Graphiques de Circuits","sidepanel.subdevice_scales":"Échelles des Graphiques de Sous-Appareils","sidepanel.reset_to_global":"Réinitialiser à la valeur globale","sidepanel.relay":"Relais","sidepanel.breaker":"Disjoncteur","sidepanel.capacity":"capacité de {amps} A","monitoringRating.title":"Calibres des disjoncteurs dans l'application SPAN","monitoringRating.panel_rating":"Le panneau publie {panel} A","monitoringRating.other_breaker":"Autre disjoncteur (A)","monitoringRating.other_breaker_label":"Autre disjoncteur dans l'emplacement de {circuit}","monitoringRating.reset":"Supprimer les calibres copiés","monitoringRating.invalid_other":"Saisissez le calibre de l'autre disjoncteur en nombre entier d'ampères, 1 ou plus.","monitoringRating.guidance":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-20A, saisissez ici le second. Les panneaux SPAN Panel MAIN 32 n'indiquent que le premier, et la surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble.","monitoringRating.guidance_two_spaces":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-30A, saisissez ici le second.","monitoringRating.averaged_legs":"Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases de ce circuit, ce qui peut masquer une phase en surcharge. Nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.turn_off_monitoring":"Désactiver la surveillance","monitoringRating.threshold_warning":"Les seuils personnalisés de ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge.","monitoringRating.threshold_warning_global":"Les seuils globaux qu'utilise ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge ; modifiez-les dans {settings}, onglet {tab}.","monitoringRating.use_global_thresholds":"Utiliser les seuils globaux","monitoringRating.note_title":"Disjoncteurs tandem sur SPAN Panel MAIN 32","monitoringRating.note_problem":"Les panneaux SPAN Panel MAIN 32 n'indiquent pas quels disjoncteurs sont des tandems, ni le calibre du second disjoncteur d'un tandem. Un tandem place deux disjoncteurs dans un emplacement, mais le panneau l'indique comme un seul circuit avec le calibre du premier disjoncteur seulement, tandis qu'un seul capteur lit les deux disjoncteurs ensemble. Un tandem 20-20 affiche 20 A ici et peut supporter 40 A, si bien que la surveillance déclenche de fausses alertes sur lui.","monitoringRating.note_steps":"Pour corriger cela, copiez les calibres depuis votre application SPAN :","monitoringRating.note_step_find":"Dans l'application SPAN, trouvez chaque circuit dont le disjoncteur affiche deux calibres, par exemple 20-20A.","monitoringRating.note_step_enter":"Dans le tableau ci-dessous, saisissez le second calibre dans le champ {column} de ce circuit. Appuyez ensuite sur Entrée ou passez au champ suivant.","monitoringRating.note_step_single":"Laissez le champ vide pour un circuit à disjoncteur unique.","monitoringRating.note_judged":"La surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble : 40 A pour un 20-20. Seule la surveillance utilise la copie, et le capteur Breaker Rating du circuit affiche toujours ce que le panneau indique. Pour supprimer un calibre copié, sélectionnez ✕ à côté de son champ.","monitoringRating.note_thresholds":"Si vous avez relevé les seuils d'un tandem au-dessus de 100 % pour faire cesser ses alertes, sélectionnez {reset} sur sa ligne. Ces seuils s'appliquent désormais aux deux disjoncteurs ensemble.","monitoringRating.note_two_spaces":"Pour un circuit qui occupe deux emplacements, saisissez le second calibre de la même façon si votre application SPAN en affiche deux, par exemple 20-30A. Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases d'un tel circuit, ce qui peut masquer une phase en surcharge : la copie ne peut donc pas être appliquée, et nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.note_guide":"Pour en savoir plus, consultez le guide des disjoncteurs tandem et à charges multiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Supprimer les calibres copiés de {circuit}","monitoringRating.table_threshold_warning":"Les seuils de ce circuit dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Sélectionnez {reset} pour utiliser les seuils globaux.","monitoringRating.table_threshold_warning_global":"Les seuils globaux dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Modifiez-les dans {settings} ci-dessus.","monitoringRating.warning_announcement":"{circuit} : {warning}","error.package_ratings_failed":"Impossible de mettre à jour les calibres copiés depuis l'application SPAN","sidepanel.judged_against":"Évalué selon : {rating}","sidepanel.shedding_priority":"Priorité de Délestage","sidepanel.priority_label":"Priorité","sidepanel.monitoring":"Surveillance","sidepanel.global":"Global","sidepanel.custom":"Personnalisé","sidepanel.continuous_pct":"Continu %","sidepanel.spike_pct":"Pic %","sidepanel.window_duration":"Durée de fenêtre","sidepanel.cooldown":"Refroidissement","sidepanel.favorite":"Favori","sidepanel.save_to_favorites":"Enregistrer dans les favoris","panel.favorites":"Favoris","status.monitoring":"Surveillance","status.circuits":"circuits","status.mains":"alimentation","status.warning":"avertissement","status.warnings":"avertissements","status.alert":"alerte","status.alerts":"alertes","status.override":"remplacement","status.overrides":"remplacements","card.no_device":"Ouvrez l'éditeur de carte et sélectionnez votre appareil SPAN Panel.","card.device_not_found":"Appareil de panneau introuvable. Vérifiez device_id dans la configuration de la carte.","card.topology_error":"La réponse de topologie ne contient pas panel_size et aucun circuit trouvé. Mettez à jour l'intégration SPAN Panel.","card.panel_size_error":"Impossible de déterminer panel_size. Aucun circuit trouvé et aucun attribut panel_size. Mettez à jour l'intégration SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Sélectionnez un panneau...","editor.chart_window":"Fenêtre de temps du graphique","editor.days":"jours","editor.hours":"heures","editor.minutes":"minutes","editor.chart_metric":"Métrique du graphique","editor.visible_sections":"Sections visibles","editor.panel_circuits":"Circuits du panneau","editor.battery_bess":"Batterie (BESS)","editor.ev_charger_evse":"Chargeur VE (EVSE)","editor.solar_pv":"Solaire (PV)","editor.no_entities":"Aucune entité à afficher","editor.tab_style":"Style des onglets","editor.tab_style_text":"Texte","editor.tab_style_icon":"Icône","metric.power":"Puissance","metric.current":"Courant","metric.soc":"État de Charge","metric.soe":"État d'Énergie","shedding.always_on":"Critique","shedding.never":"Non délestable","shedding.soc_threshold":"Seuil SoC","shedding.off_grid":"Délestable","shedding.unknown":"Inconnu","shedding.select.never":"Reste allumé en cas de coupure","shedding.select.soc_threshold":"Allumé jusqu'au seuil batterie","shedding.select.off_grid":"S'éteint en cas de coupure"},ja:{"tab.panel":"パネル","tab.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","tab.settings":"設定","tab.adopted":"採用済み","list.search_placeholder":"回路を検索...","list.unassigned_area":"未割り当て","list.no_results":"回路が見つかりません","monitoring.heading":"モニタリング","monitoring.global_settings":"グローバル設定","monitoring.enabled":"有効","monitoring.continuous":"継続 (%)","monitoring.spike":"スパイク (%)","monitoring.window":"ウィンドウ (分)","monitoring.cooldown":"クールダウン (分)","monitoring.monitored_points":"監視ポイント","monitoring.col.name":"名前","monitoring.col.continuous":"継続","monitoring.col.spike":"スパイク","monitoring.col.window":"ウィンドウ","monitoring.col.cooldown":"クールダウン","monitoring.rating":"定格","monitoring.all_none":"全選択 / 全解除","monitoring.reset":"リセット","monitoring.limit_invalid":"{min} から {max} までの整数を入力してください。","monitoring.enable_invalid":"モニタリングは有効になっていません。マークされた項目を修正してください。","monitoring.point_field":"{name}の{field}","monitoring.reset_point":"{name}をリセット","monitoring.admin_only":"モニタリングを変更できるのは管理者のみです。","notification.heading":"通知設定","notification.targets":"通知先","notification.none_selected":"未選択","notification.targets_button":"通知先: {targets}","notification.no_targets":"通知先が見つかりません","notification.all_targets":"すべて","notification.event_bus_target":"イベントバス (HAイベントバス)","notification.priority":"優先度","notification.priority.default":"デフォルト","notification.priority.passive":"パッシブ","notification.priority.active":"アクティブ","notification.priority.time_sensitive":"緊急","notification.priority.critical":"重大","notification.hint.critical":"サイレント/おやすみモードを無視","notification.hint.time_sensitive":"集中モードを突破","notification.hint.passive":"サイレント配信","notification.hint.active":"標準配信","notification.title_template":"タイトルテンプレート","notification.message_template":"メッセージテンプレート","notification.placeholders":"プレースホルダー:","notification.event_bus_help":"イベントバスが発行するイベントタイプ","notification.event_bus_payload":"ペイロード:","notification.test_label":"テスト通知","notification.test_button":"テスト送信","notification.test_sending":"送信中...","notification.test_sent":"テスト通知を送信しました","error.prefix":"エラー:","error.failed_save":"保存に失敗","error.failed":"失敗","error.panel_offline":"SPANパネルに接続できません","error.panel_reconnected":"SPANパネルが再接続されました","error.panel_offline_named":"{name}に接続できません","error.panel_reconnected_named":"{name}が再接続されました","error.discovery_failed":"SPANパネルへの接続に失敗しました","error.relay_failed":"リレーの切り替えに失敗しました","error.shedding_failed":"シェディング優先度の更新に失敗しました","error.threshold_failed":"しきい値の保存に失敗しました","error.graph_horizon_failed":"グラフの時間範囲の更新に失敗しました","error.favorites_fetch_failed":"お気に入りの読み込みに失敗しました","error.favorites_toggle_failed":"お気に入りの更新に失敗しました","error.history_failed":"履歴データの読み込みに失敗しました","error.monitoring_failed":"監視ステータスの読み込みに失敗しました","error.graph_settings_failed":"グラフ設定の読み込みに失敗しました","error.areas_failed":"エリア割り当てが同期されていない可能性があります","error.retry":"再試行","card.connecting":"SPANパネルに接続中...","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","settings.heading":"設定","settings.description":"統合の一般設定(エンティティ名、デバイスプレフィックス、回路番号)は統合のオプションフローで管理されます。","settings.open_link":"SPAN Panel統合設定を開く","adopted.heading":"採用済みエンティティ","adopted.description":"ベンダーの測定値と採用済みデバイスは最小限のメタデータで登録されます。キュレーションでデバイスクラス、統計クラス、表示区分を設定できます。保存すると統合が再読み込みされ、次回の起動から適用されます。","adopted.filter_placeholder":"エンティティ名またはデバイス名で絞り込み","adopted.no_results":"この条件に一致する採用済みエンティティはありません","adopted.none":"このパネルにキュレーション対象はありません。","adopted.load_failed":"採用済みエンティティを読み込めません","adopted.count":"{count} 件","adopted.vendor_readings":"ベンダー測定値","adopted.adopted_device":"採用済みデバイス","adopted.via_panel":"SPAN Panel 経由","adopted.curated":"キュレーション済み","adopted.stale":"無効","adopted.stale_note":"パネルは保存された次の項目をサポートしなくなりました: {fields}","adopted.enable_entity":"エンティティを有効化","adopted.enabled":"有効","adopted.disabled":"無効","adopted.enable_note":"保存時に有効化されます — キュレーション自体が有効化することはありません","adopted.registry_unavailable":"有効化・名前は、このエンティティがレジストリに登録された後に利用できます。","adopted.name":"名前","adopted.device_class":"デバイスクラス","adopted.device_class_note":"パネルの単位({unit})により選択肢が制限されます","adopted.device_class_note_unitless":"パネルが公開する内容により選択肢が制限されます","adopted.no_device_class":"デバイスクラスなし","adopted.statistics_class":"統計クラス","adopted.statistics_note":"長期統計は次回の再読み込み後に開始されます","adopted.no_statistics":"統計なし","adopted.prominence":"表示区分","adopted.diagnostic":"診断","adopted.standard":"標準","adopted.display_unit":"表示単位","adopted.unit_as_published":"公開されたまま","adopted.precision":"小数点以下桁数","adopted.precision_default":"既定","adopted.read_only":"読み取り専用","adopted.settable":"書き込み可","adopted.save":"保存","adopted.clear":"キュレーションを消去","adopted.reload_note":"保存すると SPAN Panel 統合が再読み込みされます","adopted.saved":"保存しました — 統合を再読み込みしています","adopted.confirm_heading":"統計クラスの確認","adopted.confirm_setting":"{name} を {value} に設定しようとしています。","adopted.confirm_clearing_subject":"{name} の統計クラスを消去しようとしています。","adopted.confirm_total_increasing":"積算増加は値の低下をすべてメーターのリセットとして扱います。この測定値が他の理由でも下がる場合、長期統計は恒久的に破損します。後からクラスを直しても、既に書き込まれた履歴は修復されません。","adopted.confirm_clearing":"このエンティティの長期統計は収集されなくなり、削除するクラスの下で既に収集された統計について Home Assistant が修復項目を作成します。","adopted.save_anyway":"それでも保存","adopted.cancel":"キャンセル","adopted.warn_total_increasing":"積算増加として保存しました — 測定値の低下はすべてメーターのリセットとして数えられます。","adopted.warn_statistics_removed":"このエンティティに統計クラスはなくなりました。既に収集された統計について Home Assistant が修復項目を作成します。","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"パネルモニタリング設定","header.graph_settings":"グラフ時間範囲設定","header.site":"サイト","header.grid":"グリッド","header.upstream":"上流","header.downstream":"下流","header.solar":"ソーラー","header.battery":"バッテリー","header.toggle_units":"ワット/アンペア切り替え","header.enable_switches":"スイッチを有効化","header.switches_enabled":"スイッチ有効","controls.admin_only":"このパネルのコントロールを操作できるのは管理者のみです。","controls.disabled":"このパネルのコントロールはオプションで無効になっています。","controls.read_only":"お使いのHome Assistantアカウントでは、このパネルのコントロールを操作できません。","controls.entity_unauthorized":"お使いのHome Assistantアカウントでは、このコントロールを操作できません。","controls.not_operable":"このパネルのコントロールは操作できません。","grid.unknown":"不明","grid.configure":"回路を設定","grid.configure_subdevice":"デバイスを設定","grid.on":"オン","grid.off":"オフ","grid.shared_switch":"このスペースのすべての回路を切り替えます","meters.title":"メーター","meters.importing":"受電中","meters.exporting":"送電中","meters.imported":"受電","meters.exported":"送電","subdevice.ev_charger":"EV充電器","subdevice.battery":"バッテリー","subdevice.fallback":"サブデバイス","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"電力","subdevice.solar":"ソーラー","subdevice.solar_inverter":"ソーラーインバーター","subdevice.site_total":"サイト合計","subdevice.in_site_total":"サイト合計に含まれます","sidepanel.graph_settings":"グラフ設定","sidepanel.global_defaults":"全回路のグローバルデフォルト","sidepanel.favorites_subtitle":"お気に入り","sidepanel.global_default":"グローバルデフォルト","sidepanel.list_view_columns":"リスト表示の列数","sidepanel.columns":"列","sidepanel.circuit_scales":"回路グラフスケール","sidepanel.subdevice_scales":"サブデバイスグラフスケール","sidepanel.reset_to_global":"グローバルにリセット","sidepanel.relay":"リレー","sidepanel.breaker":"ブレーカー","sidepanel.capacity":"容量 {amps} A","monitoringRating.title":"SPAN アプリのブレーカー定格","monitoringRating.panel_rating":"パネルの公開値 {panel} A","monitoringRating.other_breaker":"もう一方のブレーカー (A)","monitoringRating.other_breaker_label":"{circuit} のスペースにあるもう一方のブレーカー","monitoringRating.reset":"コピーした定格を削除","monitoringRating.invalid_other":"もう一方のブレーカーの定格を 1 以上の整数のアンペアで入力してください。","monitoringRating.guidance":"SPAN アプリでこの回路に 20-20A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。SPAN Panel MAIN 32 パネルが報告するのは 1 つ目だけで、モニタリングはこのスペースを両方のブレーカーの合計で判定します。","monitoringRating.guidance_two_spaces":"SPAN アプリでこの回路に 20-30A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 パネルはこの回路の 2 本の線の平均値しか報告しないため、過負荷の線が見えなくなることがあります。この回路のモニタリングをオフにすることをおすすめします。","monitoringRating.turn_off_monitoring":"モニタリングをオフにする","monitoringRating.threshold_warning":"この回路のカスタムしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。","monitoringRating.threshold_warning_global":"この回路が使用するグローバルしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。{tab}タブの{settings}で変更してください。","monitoringRating.use_global_thresholds":"グローバルしきい値を使用","monitoringRating.note_title":"SPAN Panel MAIN 32 のタンデムブレーカー","monitoringRating.note_problem":"SPAN Panel MAIN 32 パネルは、どのブレーカーがタンデムかも、タンデムの 2 つ目のブレーカーの定格も報告しません。タンデムは 1 つのスペースに 2 つのブレーカーを収めますが、パネルはそれを 1 つ目のブレーカーの定格だけを持つ 1 つの回路として報告し、1 つのセンサーが両方のブレーカーの合計を読み取ります。20-20 のタンデムはここでは 20 A と表示されますが 40 A まで流せるため、モニタリングが誤ったアラートを出します。","monitoringRating.note_steps":"これを直すには、次の手順で SPAN アプリから定格をコピーします。","monitoringRating.note_step_find":"SPAN アプリで、ブレーカーに 20-20A のように 2 つの定格が表示されている回路をすべて探します。","monitoringRating.note_step_enter":"下の表で、その回路の{column}フィールドに 2 つ目の定格を入力します。続けて Enter キーを押すか、次のフィールドに移動します。","monitoringRating.note_step_single":"ブレーカーが 1 つだけの回路では、フィールドを空のままにします。","monitoringRating.note_judged":"するとモニタリングは、そのスペースを両方のブレーカーの合計で判定します。20-20 なら 40 A です。コピーを使うのはモニタリングだけで、回路の Breaker Rating センサーは引き続きパネルが報告する値を表示します。コピーした定格を削除するには、フィールドの横の ✕ を選択します。","monitoringRating.note_thresholds":"アラートを止めるためにタンデムのしきい値を 100% より上に上げていた場合は、その行の{reset}を選択してください。それらのしきい値は今後、両方のブレーカーの合計に適用されます。","monitoringRating.note_two_spaces":"2 つのスペースにまたがる回路でも、SPAN アプリに 20-30A のように 2 つの定格が表示されていれば、同じ方法で 2 つ目の定格を入力します。SPAN Panel MAIN 32 パネルはそのような回路の 2 本の線の平均値しか報告せず、過負荷の線が見えなくなることがあるため、コピーは適用できません。その回路のモニタリングをオフにすることをおすすめします。","monitoringRating.note_guide":"詳しくは、タンデムブレーカーと複数負荷ブレーカーのガイドをご覧ください。","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"{circuit} のコピーした定格を削除","monitoringRating.table_threshold_warning":"この回路のしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。{reset}を選択するとグローバルしきい値を使用します。","monitoringRating.table_threshold_warning_global":"グローバルしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。上の{settings}で変更してください。","monitoringRating.warning_announcement":"{circuit}:{warning}","error.package_ratings_failed":"SPAN アプリからコピーした定格の更新に失敗しました","sidepanel.judged_against":"判定基準: {rating}","sidepanel.shedding_priority":"シェディング優先度","sidepanel.priority_label":"優先度","sidepanel.monitoring":"モニタリング","sidepanel.global":"グローバル","sidepanel.custom":"カスタム","sidepanel.continuous_pct":"継続 %","sidepanel.spike_pct":"スパイク %","sidepanel.window_duration":"ウィンドウ時間","sidepanel.cooldown":"クールダウン","sidepanel.favorite":"お気に入り","sidepanel.save_to_favorites":"お気に入りに保存","panel.favorites":"お気に入り","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","card.device_not_found":"パネルデバイスが見つかりません。カード設定のdevice_idを確認してください。","card.topology_error":"トポロジー応答にpanel_sizeがなく、回路が見つかりません。SPAN Panel統合を更新してください。","card.panel_size_error":"panel_sizeを判定できません。回路がpanel_size属性が見つかりません。SPAN Panel統合を更新してください。","editor.panel_label":"SPAN Panel","editor.select_panel":"パネルを選択...","editor.chart_window":"グラフ時間ウィンドウ","editor.days":"日","editor.hours":"時間","editor.minutes":"分","editor.chart_metric":"グラフ指標","editor.visible_sections":"表示セクション","editor.panel_circuits":"パネル回路","editor.battery_bess":"バッテリー (BESS)","editor.ev_charger_evse":"EV充電器 (EVSE)","editor.solar_pv":"ソーラー (PV)","editor.no_entities":"表示するエンティティがありません","editor.tab_style":"タブスタイル","editor.tab_style_text":"テキスト","editor.tab_style_icon":"アイコン","metric.power":"電力","metric.current":"電流","metric.soc":"充電状態","metric.soe":"エネルギー状態","shedding.always_on":"重要","shedding.never":"切断不可","shedding.soc_threshold":"SoCしきい値","shedding.off_grid":"切断可能","shedding.unknown":"不明","shedding.select.never":"停電時もオンを維持","shedding.select.soc_threshold":"バッテリーしきい値までオン","shedding.select.off_grid":"停電時にオフ"},pt:{"tab.panel":"Painel","tab.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","tab.settings":"Configurações","tab.adopted":"Adotadas","list.search_placeholder":"Pesquisar circuitos...","list.unassigned_area":"Não atribuído","list.no_results":"Nenhum circuito encontrado","monitoring.heading":"Monitoramento","monitoring.global_settings":"Configurações Globais","monitoring.enabled":"Ativado","monitoring.continuous":"Contínuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Janela (min)","monitoring.cooldown":"Resfriamento (min)","monitoring.monitored_points":"Pontos Monitorados","monitoring.col.name":"Nome","monitoring.col.continuous":"Contínuo","monitoring.col.spike":"Pico","monitoring.col.window":"Janela","monitoring.col.cooldown":"Resfriamento","monitoring.rating":"Corrente nominal","monitoring.all_none":"Todos / Nenhum","monitoring.reset":"Redefinir","monitoring.limit_invalid":"Digite um número inteiro de {min} a {max}.","monitoring.enable_invalid":"O monitoramento não foi ativado: corrija os campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Redefinir {name}","monitoring.admin_only":"Somente um administrador pode alterar o monitoramento.","notification.heading":"Configurações de Notificação","notification.targets":"Destinos de Notificação","notification.none_selected":"Nenhum selecionado","notification.targets_button":"Destinos de Notificação: {targets}","notification.no_targets":"Nenhum destino de notificação encontrado","notification.all_targets":"Todos","notification.event_bus_target":"Barramento de Eventos (barramento de eventos do HA)","notification.priority":"Prioridade","notification.priority.default":"Padrão","notification.priority.passive":"Passivo","notification.priority.active":"Ativo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Substitui silencioso/Não perturbar","notification.hint.time_sensitive":"Atravessa o modo Foco","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega padrão","notification.title_template":"Modelo de Título","notification.message_template":"Modelo de Mensagem","notification.placeholders":"Variáveis:","notification.event_bus_help":"O Barramento de Eventos dispara o tipo de evento","notification.event_bus_payload":"com dados:","notification.test_label":"Notificação de teste","notification.test_button":"Enviar teste","notification.test_sending":"Enviando...","notification.test_sent":"Notificação de teste enviada","error.prefix":"Erro:","error.failed_save":"Falha ao salvar","error.failed":"Falhou","error.panel_offline":"SPAN Panel inacessível","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inacessível","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"Não foi possível conectar ao SPAN Panel","error.relay_failed":"Não foi possível alternar o relé","error.shedding_failed":"Não foi possível atualizar a prioridade de desligamento","error.threshold_failed":"Não foi possível salvar o limite","error.graph_horizon_failed":"Não foi possível atualizar o horizonte temporal do gráfico","error.favorites_fetch_failed":"Não foi possível carregar os favoritos","error.favorites_toggle_failed":"Não foi possível atualizar o favorito","error.history_failed":"Não foi possível carregar os dados históricos","error.monitoring_failed":"Não foi possível carregar o status de monitoramento","error.graph_settings_failed":"Não foi possível carregar as configurações do gráfico","error.areas_failed":"As atribuições de áreas podem estar fora de sincronização","error.retry":"Tentar novamente","card.connecting":"Conectando ao SPAN Panel...","monitoringRating.none":"sem corrente nominal","monitoringRating.copied":"{package} do seu app SPAN (o painel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado do seu app SPAN","monitoringRating.judged_copied":"Avaliado com base em {rating} A: {copied}","settings.heading":"Configurações","settings.description":"As configurações gerais da integração (nomes de entidades, prefixo do dispositivo, números de circuito) são gerenciadas através do fluxo de opções da integração.","settings.open_link":"Abrir Configurações de Integração SPAN Panel","adopted.heading":"Entidades adotadas","adopted.description":"As leituras do fornecedor e os dispositivos adotados chegam com metadados mínimos. Faça a curadoria de uma para definir sua classe de dispositivo, classe de estatísticas e proeminência — alterações salvas recarregam a integração e valem a partir da próxima inicialização.","adopted.filter_placeholder":"Filtrar por nome de entidade ou dispositivo","adopted.no_results":"Nenhuma entidade adotada corresponde a este filtro","adopted.none":"Este painel não publica nada para curadoria.","adopted.load_failed":"Não foi possível carregar as entidades adotadas","adopted.count":"{count} adotadas","adopted.vendor_readings":"LEITURAS DO FORNECEDOR","adopted.adopted_device":"DISPOSITIVO ADOTADO","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"O painel não suporta mais o que foi salvo para: {fields}","adopted.enable_entity":"Ativar entidade","adopted.enabled":"ATIVADA","adopted.disabled":"DESATIVADA","adopted.enable_note":"Ativada ao salvar — a curadoria nunca ativa por conta própria","adopted.registry_unavailable":"Ativação e nome ficam disponíveis assim que esta entidade existir no registro.","adopted.name":"Nome","adopted.device_class":"Classe de dispositivo","adopted.device_class_note":"opções limitadas pela unidade do painel ({unit})","adopted.device_class_note_unitless":"opções limitadas pelo que o painel publica","adopted.no_device_class":"Sem classe de dispositivo","adopted.statistics_class":"Classe de estatísticas","adopted.statistics_note":"as estatísticas de longo prazo começam após a próxima recarga","adopted.no_statistics":"Sem estatísticas","adopted.prominence":"Proeminência","adopted.diagnostic":"Diagnóstico","adopted.standard":"Padrão","adopted.display_unit":"Unidade exibida","adopted.unit_as_published":"Como publicada","adopted.precision":"Precisão","adopted.precision_default":"Padrão","adopted.read_only":"somente leitura","adopted.settable":"editável","adopted.save":"Salvar","adopted.clear":"Limpar curadoria","adopted.reload_note":"Salvar recarrega a integração SPAN Panel","adopted.saved":"Salvo — a integração está recarregando","adopted.confirm_heading":"Confirmar classe de estatísticas","adopted.confirm_setting":"Você está definindo {name} como {value}.","adopted.confirm_clearing_subject":"Você está limpando a classe de estatísticas de {name}.","adopted.confirm_total_increasing":"Total crescente trata toda queda do valor como uma reinicialização do medidor. Se esta leitura puder diminuir por qualquer outro motivo, as estatísticas de longo prazo ficarão permanentemente corrompidas — corrigir a classe depois não repara o histórico já gravado.","adopted.confirm_clearing":"As estatísticas de longo prazo deixarão de ser compiladas para esta entidade, e o Home Assistant abrirá um reparo sobre as estatísticas já coletadas na classe que você está removendo.","adopted.save_anyway":"Salvar mesmo assim","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Salvo como total crescente — cada queda da leitura agora conta como uma reinicialização do medidor.","adopted.warn_statistics_removed":"Esta entidade não tem mais classe de estatísticas; o Home Assistant abrirá um reparo sobre as estatísticas já coletadas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configurações de monitoramento do painel","header.graph_settings":"Configurações do horizonte temporal do gráfico","header.site":"Local","header.grid":"Rede","header.upstream":"Montante","header.downstream":"Jusante","header.solar":"Solar","header.battery":"Bateria","header.toggle_units":"Alternar Watts / Amperes","header.enable_switches":"Ativar Interruptores","header.switches_enabled":"Interruptores Ativados","controls.admin_only":"Somente um administrador pode operar os controles deste painel.","controls.disabled":"O controle deste painel está desativado nas suas opções.","controls.read_only":"Sua conta do Home Assistant não pode operar os controles deste painel.","controls.entity_unauthorized":"Sua conta do Home Assistant não pode operar este controle.","controls.not_operable":"Você não pode operar os controles deste painel.","grid.unknown":"Desconhecido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Lig","grid.off":"Des","grid.shared_switch":"Liga e desliga todos os circuitos deste espaço","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Carregador VE","subdevice.battery":"Bateria","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potência","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total do local","subdevice.in_site_total":"Incluído no total do local","sidepanel.graph_settings":"Configurações de Gráficos","sidepanel.global_defaults":"Padrões globais para todos os circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Padrão Global","sidepanel.list_view_columns":"Colunas da Lista","sidepanel.columns":"Colunas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Redefinir para o padrão global","sidepanel.relay":"Relé","sidepanel.breaker":"Disjuntor","sidepanel.capacity":"capacidade de {amps} A","monitoringRating.title":"Correntes nominais dos disjuntores no app SPAN","monitoringRating.panel_rating":"O painel publica {panel} A","monitoringRating.other_breaker":"Outro disjuntor (A)","monitoringRating.other_breaker_label":"Outro disjuntor no espaço de {circuit}","monitoringRating.reset":"Remover as correntes nominais copiadas","monitoringRating.invalid_other":"Digite a corrente nominal do outro disjuntor como um número inteiro de amperes, 1 ou mais.","monitoringRating.guidance":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-20A, digite a segunda aqui. Os painéis SPAN Panel MAIN 32 informam apenas a primeira, e o monitoramento então avalia este espaço pelos dois disjuntores juntos.","monitoringRating.guidance_two_spaces":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-30A, digite a segunda aqui.","monitoringRating.averaged_legs":"Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases deste circuito, o que pode esconder uma fase sobrecarregada. Recomendamos desativar o monitoramento deste circuito.","monitoringRating.turn_off_monitoring":"Desativar o monitoramento","monitoringRating.threshold_warning":"Os limites personalizados deste circuito passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real.","monitoringRating.threshold_warning_global":"Os limites globais que este circuito usa passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real; altere-os em {settings}, na aba {tab}.","monitoringRating.use_global_thresholds":"Usar os limites globais","monitoringRating.note_title":"Disjuntores tandem no SPAN Panel MAIN 32","monitoringRating.note_problem":"Os painéis SPAN Panel MAIN 32 não informam quais disjuntores são tandem, nem a corrente nominal do segundo disjuntor de um tandem. Um tandem coloca dois disjuntores em um espaço, mas o painel o informa como um único circuito com apenas a corrente nominal do primeiro disjuntor, enquanto um único sensor lê os dois disjuntores juntos. Um tandem 20-20 mostra 20 A aqui e pode conduzir 40 A, então o monitoramento gera alertas falsos nele.","monitoringRating.note_steps":"Para corrigir isso, copie as correntes nominais do seu app SPAN:","monitoringRating.note_step_find":"No app SPAN, encontre cada circuito cujo disjuntor mostra duas correntes nominais, como 20-20A.","monitoringRating.note_step_enter":"Na tabela abaixo, digite a segunda corrente nominal no campo {column} desse circuito. Depois pressione Enter ou vá para o próximo campo.","monitoringRating.note_step_single":"Deixe o campo vazio para um circuito com um único disjuntor.","monitoringRating.note_judged":"O monitoramento então avalia esse espaço pelos dois disjuntores juntos: 40 A para um 20-20. Só o monitoramento usa a cópia, e o sensor Breaker Rating do circuito continua mostrando o que o painel informa. Para remover uma corrente nominal copiada, selecione ✕ ao lado do seu campo.","monitoringRating.note_thresholds":"Se você aumentou os limites de um tandem acima de 100% para interromper os alertas dele, selecione {reset} na linha dele. Esses limites agora se aplicam aos dois disjuntores juntos.","monitoringRating.note_two_spaces":"Para um circuito que ocupa dois espaços, digite a segunda corrente nominal da mesma forma se o seu app SPAN mostrar duas, como 20-30A. Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases de um circuito assim, o que pode esconder uma fase sobrecarregada, então a cópia não pode ser aplicada e recomendamos desativar o monitoramento desse circuito.","monitoringRating.note_guide":"Leia mais no guia de disjuntores tandem e de cargas múltiplas.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remover as correntes nominais copiadas de {circuit}","monitoringRating.table_threshold_warning":"Os limites deste circuito passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Selecione {reset} para usar os limites globais.","monitoringRating.table_threshold_warning_global":"Os limites globais passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Altere-os em {settings}, acima.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Não foi possível atualizar as correntes nominais copiadas do app SPAN","sidepanel.judged_against":"Avaliado com base em: {rating}","sidepanel.shedding_priority":"Prioridade de Desligamento","sidepanel.priority_label":"Prioridade","sidepanel.monitoring":"Monitoramento","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Contínuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duração da janela","sidepanel.cooldown":"Resfriamento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Salvar nos favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoramento","status.circuits":"circuitos","status.mains":"alimentação","status.warning":"aviso","status.warnings":"avisos","status.alert":"alerta","status.alerts":"alertas","status.override":"substituição","status.overrides":"substituições","card.no_device":"Abra o editor do cartão e selecione seu dispositivo SPAN Panel.","card.device_not_found":"Dispositivo do painel não encontrado. Verifique device_id na configuração do cartão.","card.topology_error":"A resposta de topologia não contém panel_size e nenhum circuito encontrado. Atualize a integração SPAN Panel.","card.panel_size_error":"Não foi possível determinar panel_size. Nenhum circuito encontrado e nenhum atributo panel_size. Atualize a integração SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Selecione um painel...","editor.chart_window":"Janela de tempo do gráfico","editor.days":"dias","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica do gráfico","editor.visible_sections":"Seções visíveis","editor.panel_circuits":"Circuitos do painel","editor.battery_bess":"Bateria (BESS)","editor.ev_charger_evse":"Carregador VE (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"Nenhuma entidade para mostrar","editor.tab_style":"Estilo das abas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícone","metric.power":"Potência","metric.current":"Corrente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energia","shedding.always_on":"Crítico","shedding.never":"Não desligável","shedding.soc_threshold":"Limite SoC","shedding.off_grid":"Desligável","shedding.unknown":"Desconhecido","shedding.select.never":"Permanece ligado em uma queda","shedding.select.soc_threshold":"Ligado até limite da bateria","shedding.select.off_grid":"Desliga em uma queda"}};function n(n){t=n&&e[n]?n:"en"}function i(n){return e[t]?.[n]??e.en?.[n]??n}function r(n,i){return(e[t]?.[n]??e.en?.[n]??n).replace(/\{(\w+)\}/g,(t,e)=>Object.prototype.hasOwnProperty.call(i,e)?i[e]:`{${e}}`)}const o="power",a="5m",s={"5m":{ms:3e5,refreshMs:1e3,useRealtime:!0},"1h":{ms:36e5,refreshMs:3e4,useRealtime:!1},"1d":{ms:864e5,refreshMs:6e4,useRealtime:!1},"1w":{ms:6048e5,refreshMs:6e4,useRealtime:!1},"1M":{ms:2592e6,refreshMs:6e4,useRealtime:!1}},l="span_panel",c="span-panel-card",u=`custom:${c}`,d="span-panel",h=`custom:${d}`,p=`ll-strategy-section-${d}`,f="bess",g="evse",m="pv",v="sub_",y={power:{entityRole:"power",label:()=>i("metric.power"),unit:t=>Math.abs(t)>=1e3?"kW":"W",format:t=>{const e=Math.abs(t);return e>=1e3?(e/1e3).toFixed(1):e<10&&e>0?e.toFixed(1):String(Math.round(e))}},current:{entityRole:"current",label:()=>i("metric.current"),unit:()=>"A",format:t=>Math.abs(t).toFixed(1)}},_={soc:{entityRole:"soc",label:()=>i("metric.soc"),unit:()=>"%",format:t=>String(Math.round(t)),fixedMin:0,fixedMax:100},soe:{entityRole:"soe",label:()=>i("metric.soe"),unit:()=>"kWh",format:t=>t.toFixed(1)},power:y.power},b={always_on:{icon:"mdi:battery",icon2:"mdi:router-wireless",color:"#4caf50",label:()=>i("shedding.always_on")},never:{icon:"mdi:battery",color:"#4caf50",label:()=>i("shedding.never")},soc_threshold:{icon:"mdi:battery-alert-variant-outline",color:"#9c27b0",label:()=>i("shedding.soc_threshold"),textLabel:"SoC"},off_grid:{icon:"mdi:transmission-tower",color:"#ff9800",label:()=>i("shedding.off_grid")},unknown:{icon:"mdi:help-circle-outline",color:"#888",label:()=>i("shedding.unknown")}},x=Object.keys(b).filter(t=>"unknown"!==t&&"always_on"!==t);var w=function(t,e){return w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},w(t,e)};function S(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}w(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function C(t,e,n,i){var r,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(r=t[s])&&(a=(o<3?r(a):o>3?r(e,n,a):r(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}"function"==typeof SuppressedError&&SuppressedError; +let t="en";const e={en:{"tab.panel":"Panel","tab.by_panel":"By Panel","tab.by_activity":"By Activity","tab.by_area":"By Area","tab.monitoring":"Monitoring","tab.settings":"Settings","tab.adopted":"Adopted","list.search_placeholder":"Search circuits...","list.unassigned_area":"Unassigned","list.no_results":"No circuits found","monitoring.heading":"Monitoring","monitoring.global_settings":"Global Settings","monitoring.enabled":"Enabled","monitoring.continuous":"Continuous (%)","monitoring.spike":"Spike (%)","monitoring.window":"Window (min)","monitoring.cooldown":"Cooldown (min)","monitoring.monitored_points":"Monitored Points","monitoring.col.name":"Name","monitoring.col.continuous":"Continuous","monitoring.col.spike":"Spike","monitoring.col.window":"Window","monitoring.col.cooldown":"Cooldown","monitoring.rating":"Rating","monitoring.all_none":"All / None","monitoring.reset":"Reset","monitoring.limit_invalid":"Enter a whole number from {min} to {max}.","monitoring.enable_invalid":"Monitoring was not turned on: correct the fields marked.","monitoring.point_field":"{field} for {name}","monitoring.reset_point":"Reset {name}","monitoring.admin_only":"Only an administrator can change monitoring.","notification.heading":"Notification Settings","notification.targets":"Notify Targets","notification.none_selected":"None selected","notification.targets_button":"Notify Targets: {targets}","notification.no_targets":"No notify targets found","notification.all_targets":"All","notification.event_bus_target":"Event Bus (HA event bus)","notification.priority":"Priority","notification.priority.default":"Default","notification.priority.passive":"Passive","notification.priority.active":"Active","notification.priority.time_sensitive":"Time-sensitive","notification.priority.critical":"Critical","notification.hint.critical":"Overrides silent/DND","notification.hint.time_sensitive":"Breaks through Focus","notification.hint.passive":"Delivers silently","notification.hint.active":"Standard delivery","notification.title_template":"Title Template","notification.message_template":"Message Template","notification.placeholders":"Placeholders:","notification.event_bus_help":"Event Bus fires event type","notification.event_bus_payload":"with payload:","notification.test_label":"Test Notification","notification.test_button":"Send Test","notification.test_sending":"Sending...","notification.test_sent":"Test notification sent","error.prefix":"Error:","error.failed_save":"Failed to save","error.failed":"Failed","error.panel_offline":"SPAN Panel unreachable","error.panel_reconnected":"SPAN Panel reconnected","error.panel_offline_named":"{name} unreachable","error.panel_reconnected_named":"{name} reconnected","error.discovery_failed":"Unable to connect to SPAN Panel","error.relay_failed":"Unable to toggle relay","error.shedding_failed":"Unable to update shedding priority","error.threshold_failed":"Unable to save threshold","error.graph_horizon_failed":"Unable to update graph time horizon","error.favorites_fetch_failed":"Unable to load favorites","error.favorites_toggle_failed":"Unable to update favorite","error.history_failed":"Unable to load historical data","error.monitoring_failed":"Unable to load monitoring status","error.graph_settings_failed":"Unable to load graph settings","error.areas_failed":"Area assignments may be out of sync","error.retry":"Retry","card.connecting":"Connecting to SPAN Panel...","card.waiting_for_load":"Waiting for SPAN Panel to load...","monitoringRating.none":"no rating","monitoringRating.copied":"{package} from your SPAN app (the panel publishes {panel} A)","monitoringRating.copied_unnamed":"Copied from your SPAN app","monitoringRating.judged_copied":"Judged against {rating} A: {copied}","settings.heading":"Settings","settings.description":"General integration settings (entity naming, device prefix, circuit numbers) are managed through the integration's options flow.","settings.open_link":"Open SPAN Panel Integration Settings","adopted.heading":"Adopted entities","adopted.description":"Vendor readings and adopted devices arrive with minimal metadata. Curate one to set its device class, statistics class, and prominence — saved changes reload the integration and apply from the next startup on.","adopted.filter_placeholder":"Filter by entity or device name","adopted.no_results":"No adopted entities match this filter","adopted.none":"This panel publishes nothing to curate.","adopted.load_failed":"Unable to load adopted entities","adopted.count":"{count} adopted","adopted.vendor_readings":"VENDOR READINGS","adopted.adopted_device":"ADOPTED DEVICE","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURATED","adopted.stale":"STALE","adopted.stale_note":"The panel no longer supports what was saved for: {fields}","adopted.enable_entity":"Enable entity","adopted.enabled":"ENABLED","adopted.disabled":"DISABLED","adopted.enable_note":"Enabled when saved — curating never enables on its own","adopted.registry_unavailable":"Enable and name become available once this entity exists in the registry.","adopted.name":"Name","adopted.device_class":"Device class","adopted.device_class_note":"choices limited by the panel's unit ({unit})","adopted.device_class_note_unitless":"choices limited by what the panel publishes","adopted.no_device_class":"No device class","adopted.statistics_class":"Statistics class","adopted.statistics_note":"long-term statistics begin after the next reload","adopted.no_statistics":"No statistics","adopted.prominence":"Prominence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Display unit","adopted.unit_as_published":"As published","adopted.precision":"Precision","adopted.precision_default":"Default","adopted.read_only":"read-only","adopted.settable":"settable","adopted.save":"Save","adopted.clear":"Clear curation","adopted.reload_note":"Saving reloads the SPAN Panel integration","adopted.saved":"Saved — the integration is reloading","adopted.confirm_heading":"Confirm statistics class","adopted.confirm_setting":"You are setting {name} to {value}.","adopted.confirm_clearing_subject":"You are clearing the statistics class on {name}.","adopted.confirm_total_increasing":"Total increasing treats every drop in the value as a meter reset. If this reading can decrease for any other reason, long-term statistics will be permanently corrupted — fixing the class later does not repair history already written.","adopted.confirm_clearing":"Long-term statistics stop being compiled for this entity, and Home Assistant raises a repair against the statistics already collected under the class you are removing.","adopted.save_anyway":"Save anyway","adopted.cancel":"Cancel","adopted.warn_total_increasing":"Saved as total increasing — every drop in the reading now counts as a meter reset.","adopted.warn_statistics_removed":"This entity has no statistics class any more; Home Assistant will raise a repair against the statistics already collected.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Panel monitoring settings","header.graph_settings":"Graph time horizon settings","header.site":"Site","header.grid":"Grid","header.upstream":"Upstream","header.downstream":"Downstream","header.solar":"Solar","header.battery":"Battery","header.toggle_units":"Toggle Watts / Amps","header.enable_switches":"Enable Switches","header.switches_enabled":"Switches Enabled","controls.admin_only":"Only an administrator can operate this panel's controls.","controls.disabled":"Control of this panel is switched off in its options.","controls.read_only":"Your Home Assistant account can't operate this panel's controls.","controls.entity_unauthorized":"Your Home Assistant account can't operate this control.","controls.not_operable":"You can't operate this panel's controls.","grid.unknown":"Unknown","grid.configure":"Configure circuit","grid.configure_subdevice":"Configure device","grid.on":"On","grid.off":"Off","grid.shared_switch":"Switches every circuit in this space","meters.title":"Meters","meters.importing":"importing","meters.exporting":"exporting","meters.imported":"imported","meters.exported":"exported","subdevice.ev_charger":"EV Charger","subdevice.battery":"Battery","subdevice.fallback":"Sub-device","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Power","subdevice.solar":"Solar","subdevice.solar_inverter":"Solar inverter","subdevice.site_total":"Site total","subdevice.in_site_total":"Included in the site total","sidepanel.graph_settings":"Graph Settings","sidepanel.global_defaults":"Global defaults for all circuits","sidepanel.favorites_subtitle":"Favorites","sidepanel.global_default":"Global Default","sidepanel.list_view_columns":"List View Columns","sidepanel.columns":"Columns","sidepanel.circuit_scales":"Circuit Graph Scales","sidepanel.subdevice_scales":"Sub-Device Graph Scales","sidepanel.reset_to_global":"Reset to global default","sidepanel.relay":"Relay","sidepanel.breaker":"Breaker","sidepanel.capacity":"{amps} A capacity","monitoringRating.title":"Breaker ratings from the SPAN app","monitoringRating.panel_rating":"Panel publishes {panel} A","monitoringRating.other_breaker":"Other breaker (A)","monitoringRating.other_breaker_label":"Other breaker in the space of {circuit}","monitoringRating.reset":"Remove copied ratings","monitoringRating.invalid_other":"Enter the other breaker's rating as a whole number of amps, 1 or more.","monitoringRating.guidance":"If your SPAN app shows two ratings for this circuit, such as 20-20A, enter the second one here. SPAN Panel MAIN 32 panels report only the first, and monitoring then judges this space against both breakers together.","monitoringRating.guidance_two_spaces":"If your SPAN app shows two ratings for this circuit, such as 20-30A, enter the second one here.","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 panels report only the average of this circuit's two legs, which can hide an overloaded leg. We recommend turning monitoring off for this circuit.","monitoringRating.turn_off_monitoring":"Turn off monitoring","monitoringRating.threshold_warning":"This circuit's custom thresholds are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass.","monitoringRating.threshold_warning_global":"The global thresholds this circuit uses are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass; change them under {settings} on the {tab} tab.","monitoringRating.use_global_thresholds":"Use global thresholds","monitoringRating.note_title":"Tandem breakers on SPAN Panel MAIN 32","monitoringRating.note_problem":"SPAN Panel MAIN 32 panels do not report which breakers are tandems, or the rating of a tandem's second breaker. A tandem puts two breakers in one space, but the panel reports it as one circuit with only the first breaker's rating, while one sensor reads both breakers together. A 20-20 tandem shows 20 A here and can carry 40 A, so monitoring raises false alerts on it.","monitoringRating.note_steps":"To fix this, copy the ratings from your SPAN app:","monitoringRating.note_step_find":"In the SPAN app, find each circuit whose breaker shows two ratings, such as 20-20A.","monitoringRating.note_step_enter":"In the table below, type the second rating in that circuit's {column} field. Then press Enter or move to the next field.","monitoringRating.note_step_single":"Leave the field empty for a circuit with a single breaker.","monitoringRating.note_judged":"Monitoring then judges that space against both breakers together: 40 A for a 20-20. Only monitoring uses the copy, and the circuit's Breaker Rating sensor still shows what the panel reports. To remove a copied rating, select ✕ beside its field.","monitoringRating.note_thresholds":"If you raised a tandem's thresholds above 100% to stop its alerts, select {reset} on its row. Those thresholds now apply to both breakers together.","monitoringRating.note_two_spaces":"For a circuit that spans two spaces, enter the second rating the same way if your SPAN app shows two, such as 20-30A. SPAN Panel MAIN 32 panels report only the average of such a circuit's two legs, which can hide an overloaded leg, so the copy can't be applied and we recommend turning monitoring off for that circuit.","monitoringRating.note_guide":"Read more in the guide to tandem and multi-load breakers.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remove copied ratings for {circuit}","monitoringRating.table_threshold_warning":"This circuit's thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Select {reset} to use the global thresholds.","monitoringRating.table_threshold_warning_global":"The global thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Change them under {settings} above.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Unable to update the ratings copied from the SPAN app","sidepanel.judged_against":"Judged against: {rating}","sidepanel.shedding_priority":"Shedding Priority","sidepanel.priority_label":"Priority","sidepanel.monitoring":"Monitoring","sidepanel.global":"Global","sidepanel.custom":"Custom","sidepanel.continuous_pct":"Continuous %","sidepanel.spike_pct":"Spike %","sidepanel.window_duration":"Window duration","sidepanel.cooldown":"Cooldown","sidepanel.favorite":"Favorite","sidepanel.save_to_favorites":"Save to favorites","panel.favorites":"Favorites","status.monitoring":"Monitoring","status.circuits":"circuits","status.mains":"mains","status.warning":"warning","status.warnings":"warnings","status.alert":"alert","status.alerts":"alerts","status.override":"override","status.overrides":"overrides","card.no_device":"Open the card editor and select your SPAN Panel device.","card.device_not_found":"Panel device not found. Check device_id in card config.","card.topology_error":"Topology response missing panel_size and no circuits found. Update the SPAN Panel integration.","editor.panel_label":"SPAN Panel","editor.select_panel":"Select a panel...","editor.chart_window":"Chart time window","editor.days":"days","editor.hours":"hours","editor.minutes":"minutes","editor.chart_metric":"Chart metric","editor.visible_sections":"Visible sections","editor.panel_circuits":"Panel circuits","editor.battery_bess":"Battery (BESS)","editor.ev_charger_evse":"EV Charger (EVSE)","editor.solar_pv":"Solar (PV)","editor.no_entities":"No entities to show","editor.tab_style":"Tab Style","editor.tab_style_text":"Text","editor.tab_style_icon":"Icon","metric.power":"Power","metric.current":"Current","metric.soc":"State of Charge","metric.soe":"State of Energy","shedding.always_on":"Critical","shedding.never":"Non-sheddable","shedding.soc_threshold":"SoC Threshold","shedding.off_grid":"Sheddable","shedding.unknown":"Unknown","shedding.select.never":"Stays on in an outage","shedding.select.soc_threshold":"Stays on until battery threshold","shedding.select.off_grid":"Turns off in an outage"},es:{"tab.panel":"Panel","tab.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","tab.settings":"Configuración","tab.adopted":"Adoptadas","list.search_placeholder":"Buscar circuitos...","list.unassigned_area":"Sin asignar","list.no_results":"No se encontraron circuitos","monitoring.heading":"Monitoreo","monitoring.global_settings":"Configuración Global","monitoring.enabled":"Activado","monitoring.continuous":"Continuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Ventana (min)","monitoring.cooldown":"Enfriamiento (min)","monitoring.monitored_points":"Puntos Monitoreados","monitoring.col.name":"Nombre","monitoring.col.continuous":"Continuo","monitoring.col.spike":"Pico","monitoring.col.window":"Ventana","monitoring.col.cooldown":"Enfriamiento","monitoring.rating":"Calibre","monitoring.all_none":"Todos / Ninguno","monitoring.reset":"Restablecer","monitoring.limit_invalid":"Introduzca un número entero de {min} a {max}.","monitoring.enable_invalid":"No se activó el monitoreo: corrija los campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Restablecer {name}","monitoring.admin_only":"Solo un administrador puede cambiar el monitoreo.","notification.heading":"Configuración de Notificaciones","notification.targets":"Destinos de Notificación","notification.none_selected":"Ninguno seleccionado","notification.targets_button":"Destinos de Notificación: {targets}","notification.no_targets":"No se encontraron destinos de notificación","notification.all_targets":"Todos","notification.event_bus_target":"Bus de Eventos (bus de eventos de HA)","notification.priority":"Prioridad","notification.priority.default":"Predeterminado","notification.priority.passive":"Pasivo","notification.priority.active":"Activo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Anula silencio/No molestar","notification.hint.time_sensitive":"Atraviesa el modo Concentración","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega estándar","notification.title_template":"Plantilla de Título","notification.message_template":"Plantilla de Mensaje","notification.placeholders":"Variables:","notification.event_bus_help":"El Bus de Eventos dispara el tipo de evento","notification.event_bus_payload":"con datos:","notification.test_label":"Notificación de prueba","notification.test_button":"Enviar prueba","notification.test_sending":"Enviando...","notification.test_sent":"Notificación de prueba enviada","error.prefix":"Error:","error.failed_save":"Error al guardar","error.failed":"Falló","error.panel_offline":"SPAN Panel inaccesible","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inaccesible","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"No se puede conectar al SPAN Panel","error.relay_failed":"No se pudo cambiar el relé","error.shedding_failed":"No se pudo actualizar la prioridad de desconexión","error.threshold_failed":"No se pudo guardar el umbral","error.graph_horizon_failed":"No se pudo actualizar el horizonte temporal del gráfico","error.favorites_fetch_failed":"No se pudieron cargar los favoritos","error.favorites_toggle_failed":"No se pudo actualizar el favorito","error.history_failed":"No se pudieron cargar los datos históricos","error.monitoring_failed":"No se pudo cargar el estado de monitoreo","error.graph_settings_failed":"No se pudo cargar la configuración del gráfico","error.areas_failed":"Las asignaciones de áreas pueden estar desincronizadas","error.retry":"Reintentar","card.connecting":"Conectando al SPAN Panel...","card.waiting_for_load":"Esperando a que cargue el SPAN Panel...","monitoringRating.none":"sin calibre","monitoringRating.copied":"{package} de su app de SPAN (el panel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado de su app de SPAN","monitoringRating.judged_copied":"Evaluado según {rating} A: {copied}","settings.heading":"Configuración","settings.description":"La configuración general de la integración (nombres de entidades, prefijo de dispositivo, números de circuito) se administra a través del flujo de opciones de la integración.","settings.open_link":"Abrir Configuración de Integración SPAN Panel","adopted.heading":"Entidades adoptadas","adopted.description":"Las lecturas del proveedor y los dispositivos adoptados llegan con metadatos mínimos. Cura una para definir su clase de dispositivo, clase de estadísticas y prominencia — los cambios guardados recargan la integración y se aplican desde el siguiente arranque.","adopted.filter_placeholder":"Filtrar por nombre de entidad o dispositivo","adopted.no_results":"Ninguna entidad adoptada coincide con este filtro","adopted.none":"Este panel no publica nada que curar.","adopted.load_failed":"No se pudieron cargar las entidades adoptadas","adopted.count":"{count} adoptadas","adopted.vendor_readings":"LECTURAS DEL PROVEEDOR","adopted.adopted_device":"DISPOSITIVO ADOPTADO","adopted.via_panel":"vía SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"El panel ya no admite lo guardado para: {fields}","adopted.enable_entity":"Activar entidad","adopted.enabled":"ACTIVADA","adopted.disabled":"DESACTIVADA","adopted.enable_note":"Se activa al guardar — curar nunca activa por sí solo","adopted.registry_unavailable":"La activación y el nombre estarán disponibles cuando esta entidad exista en el registro.","adopted.name":"Nombre","adopted.device_class":"Clase de dispositivo","adopted.device_class_note":"opciones limitadas por la unidad del panel ({unit})","adopted.device_class_note_unitless":"opciones limitadas por lo que publica el panel","adopted.no_device_class":"Sin clase de dispositivo","adopted.statistics_class":"Clase de estadísticas","adopted.statistics_note":"las estadísticas a largo plazo comienzan tras la próxima recarga","adopted.no_statistics":"Sin estadísticas","adopted.prominence":"Prominencia","adopted.diagnostic":"Diagnóstico","adopted.standard":"Estándar","adopted.display_unit":"Unidad mostrada","adopted.unit_as_published":"Tal como se publica","adopted.precision":"Precisión","adopted.precision_default":"Predeterminada","adopted.read_only":"solo lectura","adopted.settable":"editable","adopted.save":"Guardar","adopted.clear":"Borrar curación","adopted.reload_note":"Guardar recarga la integración SPAN Panel","adopted.saved":"Guardado — la integración se está recargando","adopted.confirm_heading":"Confirmar clase de estadísticas","adopted.confirm_setting":"Vas a definir {name} como {value}.","adopted.confirm_clearing_subject":"Vas a borrar la clase de estadísticas de {name}.","adopted.confirm_total_increasing":"Total creciente interpreta cada caída del valor como un reinicio del contador. Si esta lectura puede disminuir por cualquier otro motivo, las estadísticas a largo plazo quedarán corrompidas de forma permanente — corregir la clase más tarde no repara el historial ya escrito.","adopted.confirm_clearing":"Dejarán de compilarse estadísticas a largo plazo para esta entidad, y Home Assistant abrirá una reparación sobre las estadísticas ya recogidas bajo la clase que estás quitando.","adopted.save_anyway":"Guardar de todos modos","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Guardado como total creciente — cada caída de la lectura cuenta ahora como un reinicio del contador.","adopted.warn_statistics_removed":"Esta entidad ya no tiene clase de estadísticas; Home Assistant abrirá una reparación sobre las estadísticas ya recogidas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configuración de monitoreo del panel","header.graph_settings":"Configuración del horizonte temporal del gráfico","header.site":"Sitio","header.grid":"Red","header.upstream":"Aguas arriba","header.downstream":"Aguas abajo","header.solar":"Solar","header.battery":"Batería","header.toggle_units":"Alternar Watts / Amperios","header.enable_switches":"Habilitar Interruptores","header.switches_enabled":"Interruptores Habilitados","controls.admin_only":"Solo un administrador puede operar los controles de este panel.","controls.disabled":"El control de este panel está desactivado en sus opciones.","controls.read_only":"Su cuenta de Home Assistant no puede operar los controles de este panel.","controls.entity_unauthorized":"Su cuenta de Home Assistant no puede operar este control.","controls.not_operable":"No puede operar los controles de este panel.","grid.unknown":"Desconocido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Enc","grid.off":"Apag","grid.shared_switch":"Conmuta todos los circuitos de este espacio","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Cargador EV","subdevice.battery":"Batería","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potencia","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total del sitio","subdevice.in_site_total":"Incluido en el total del sitio","sidepanel.graph_settings":"Configuración de Gráficos","sidepanel.global_defaults":"Valores predeterminados globales para todos los circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Predeterminado Global","sidepanel.list_view_columns":"Columnas de la lista","sidepanel.columns":"Columnas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Restablecer al valor global","sidepanel.relay":"Relé","sidepanel.breaker":"Interruptor","sidepanel.capacity":"capacidad de {amps} A","monitoringRating.title":"Calibres de interruptor de la app de SPAN","monitoringRating.panel_rating":"El panel publica {panel} A","monitoringRating.other_breaker":"Otro interruptor (A)","monitoringRating.other_breaker_label":"Otro interruptor en el espacio de {circuit}","monitoringRating.reset":"Quitar los calibres copiados","monitoringRating.invalid_other":"Introduzca el calibre del otro interruptor como un número entero de amperios, 1 o más.","monitoringRating.guidance":"Si su app de SPAN muestra dos calibres para este circuito, como 20-20A, introduzca aquí el segundo. Los paneles SPAN Panel MAIN 32 informan solo el primero, y el monitoreo juzga entonces este espacio según ambos interruptores juntos.","monitoringRating.guidance_two_spaces":"Si su app de SPAN muestra dos calibres para este circuito, como 20-30A, introduzca aquí el segundo.","monitoringRating.averaged_legs":"Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de este circuito, lo que puede ocultar una fase sobrecargada. Recomendamos desactivar el monitoreo de este circuito.","monitoringRating.turn_off_monitoring":"Desactivar el monitoreo","monitoringRating.threshold_warning":"Los umbrales personalizados de este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real.","monitoringRating.threshold_warning_global":"Los umbrales globales que usa este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real; cámbielos en {settings}, en la pestaña {tab}.","monitoringRating.use_global_thresholds":"Usar los umbrales globales","monitoringRating.note_title":"Interruptores tándem en SPAN Panel MAIN 32","monitoringRating.note_problem":"Los paneles SPAN Panel MAIN 32 no informan qué interruptores son tándem ni el calibre del segundo interruptor de un tándem. Un tándem pone dos interruptores en un espacio, pero el panel lo informa como un solo circuito con solo el calibre del primer interruptor, mientras un solo sensor lee ambos interruptores juntos. Un tándem 20-20 muestra 20 A aquí y puede llevar 40 A, por lo que el monitoreo genera falsas alertas en él.","monitoringRating.note_steps":"Para corregirlo, copie los calibres de su app de SPAN:","monitoringRating.note_step_find":"En la app de SPAN, busque cada circuito cuyo interruptor muestre dos calibres, como 20-20A.","monitoringRating.note_step_enter":"En la tabla de abajo, escriba el segundo calibre en el campo {column} de ese circuito. Luego pulse Intro o pase al siguiente campo.","monitoringRating.note_step_single":"Deje el campo vacío para un circuito con un solo interruptor.","monitoringRating.note_judged":"El monitoreo juzga entonces ese espacio según ambos interruptores juntos: 40 A para un 20-20. Solo el monitoreo usa la copia, y el sensor Breaker Rating del circuito sigue mostrando lo que informa el panel. Para quitar un calibre copiado, seleccione ✕ junto a su campo.","monitoringRating.note_thresholds":"Si subió los umbrales de un tándem por encima del 100 % para detener sus alertas, seleccione {reset} en su fila. Esos umbrales se aplican ahora a ambos interruptores juntos.","monitoringRating.note_two_spaces":"Para un circuito que ocupa dos espacios, introduzca el segundo calibre del mismo modo si su app de SPAN muestra dos, como 20-30A. Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de un circuito así, lo que puede ocultar una fase sobrecargada, por lo que la copia no se puede aplicar y recomendamos desactivar el monitoreo de ese circuito.","monitoringRating.note_guide":"Lea más en la guía de interruptores tándem y de cargas múltiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Quitar los calibres copiados de {circuit}","monitoringRating.table_threshold_warning":"Los umbrales de este circuito superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Seleccione {reset} para usar los umbrales globales.","monitoringRating.table_threshold_warning_global":"Los umbrales globales superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Cámbielos en {settings}, arriba.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"No se pudieron actualizar los calibres copiados de la app de SPAN","sidepanel.judged_against":"Evaluado según: {rating}","sidepanel.shedding_priority":"Prioridad de Desconexción","sidepanel.priority_label":"Prioridad","sidepanel.monitoring":"Monitoreo","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Continuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duración de ventana","sidepanel.cooldown":"Enfriamiento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Guardar en favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoreo","status.circuits":"circuitos","status.mains":"alimentación","status.warning":"advertencia","status.warnings":"advertencias","status.alert":"alerta","status.alerts":"alertas","status.override":"anulación","status.overrides":"anulaciones","card.no_device":"Abra el editor de tarjeta y seleccione su dispositivo SPAN Panel.","card.device_not_found":"Dispositivo de panel no encontrado. Verifique device_id en la configuración de la tarjeta.","card.topology_error":"La respuesta de topología no contiene panel_size y no se encontraron circuitos. Actualice la integración SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Seleccione un panel...","editor.chart_window":"Ventana de tiempo del gráfico","editor.days":"días","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica del gráfico","editor.visible_sections":"Secciones visibles","editor.panel_circuits":"Circuitos del panel","editor.battery_bess":"Batería (BESS)","editor.ev_charger_evse":"Cargador EV (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"No hay entidades para mostrar","editor.tab_style":"Estilo de pestañas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícono","metric.power":"Potencia","metric.current":"Corriente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energía","shedding.always_on":"Crítico","shedding.never":"No desconectable","shedding.soc_threshold":"Umbral SoC","shedding.off_grid":"Desconectable","shedding.unknown":"Desconocido","shedding.select.never":"Permanece encendido en un corte","shedding.select.soc_threshold":"Encendido hasta umbral de batería","shedding.select.off_grid":"Se apaga en un corte"},fr:{"tab.panel":"Panneau","tab.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","tab.settings":"Paramètres","tab.adopted":"Adoptées","list.search_placeholder":"Rechercher des circuits...","list.unassigned_area":"Non attribué","list.no_results":"Aucun circuit trouvé","monitoring.heading":"Surveillance","monitoring.global_settings":"Paramètres Globaux","monitoring.enabled":"Activé","monitoring.continuous":"Continu (%)","monitoring.spike":"Pic (%)","monitoring.window":"Fenêtre (min)","monitoring.cooldown":"Refroidissement (min)","monitoring.monitored_points":"Points Surveillés","monitoring.col.name":"Nom","monitoring.col.continuous":"Continu","monitoring.col.spike":"Pic","monitoring.col.window":"Fenêtre","monitoring.col.cooldown":"Refroidissement","monitoring.rating":"Calibre","monitoring.all_none":"Tous / Aucun","monitoring.reset":"Réinitialiser","monitoring.limit_invalid":"Saisissez un nombre entier de {min} à {max}.","monitoring.enable_invalid":"La surveillance n'a pas été activée : corrigez les champs signalés.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Réinitialiser {name}","monitoring.admin_only":"Seul un administrateur peut modifier la surveillance.","notification.heading":"Paramètres de Notification","notification.targets":"Cibles de Notification","notification.none_selected":"Aucune sélection","notification.targets_button":"Cibles de Notification : {targets}","notification.no_targets":"Aucune cible de notification trouvée","notification.all_targets":"Tous","notification.event_bus_target":"Bus d'événements (bus d'événements HA)","notification.priority":"Priorité","notification.priority.default":"Par défaut","notification.priority.passive":"Passif","notification.priority.active":"Actif","notification.priority.time_sensitive":"Urgent","notification.priority.critical":"Critique","notification.hint.critical":"Outrepasse silencieux/NPD","notification.hint.time_sensitive":"Traverse le mode Concentration","notification.hint.passive":"Livraison silencieuse","notification.hint.active":"Livraison standard","notification.title_template":"Modèle de Titre","notification.message_template":"Modèle de Message","notification.placeholders":"Variables :","notification.event_bus_help":"Le Bus d'événements déclenche le type d'événement","notification.event_bus_payload":"avec les données :","notification.test_label":"Notification de test","notification.test_button":"Envoyer un test","notification.test_sending":"Envoi...","notification.test_sent":"Notification de test envoyée","error.prefix":"Erreur :","error.failed_save":"Échec de la sauvegarde","error.failed":"Échoué","error.panel_offline":"SPAN Panel inaccessible","error.panel_reconnected":"SPAN Panel reconnecté","error.panel_offline_named":"{name} inaccessible","error.panel_reconnected_named":"{name} reconnecté","error.discovery_failed":"Impossible de se connecter au SPAN Panel","error.relay_failed":"Impossible de basculer le relais","error.shedding_failed":"Impossible de mettre à jour la priorité de délestage","error.threshold_failed":"Impossible d'enregistrer le seuil","error.graph_horizon_failed":"Impossible de mettre à jour l'horizon temporel du graphique","error.favorites_fetch_failed":"Impossible de charger les favoris","error.favorites_toggle_failed":"Impossible de mettre à jour le favori","error.history_failed":"Impossible de charger les données historiques","error.monitoring_failed":"Impossible de charger l'état de surveillance","error.graph_settings_failed":"Impossible de charger les paramètres du graphique","error.areas_failed":"Les affectations de zones peuvent être désynchronisées","error.retry":"Réessayer","card.connecting":"Connexion au SPAN Panel...","card.waiting_for_load":"En attente du chargement du SPAN Panel...","monitoringRating.none":"aucun calibre","monitoringRating.copied":"{package} depuis votre application SPAN (le panneau publie {panel} A)","monitoringRating.copied_unnamed":"Copié depuis votre application SPAN","monitoringRating.judged_copied":"Évalué selon {rating} A : {copied}","settings.heading":"Paramètres","settings.description":"Les paramètres généraux de l'intégration (noms d'entités, préfixe de l'appareil, numéros de circuit) sont gérés via le flux d'options de l'intégration.","settings.open_link":"Ouvrir les Paramètres d'Intégration SPAN Panel","adopted.heading":"Entités adoptées","adopted.description":"Les relevés du fournisseur et les appareils adoptés arrivent avec des métadonnées minimales. Curez-en un pour définir sa classe d'appareil, sa classe de statistiques et sa proéminence — les modifications enregistrées rechargent l'intégration et s'appliquent dès le prochain démarrage.","adopted.filter_placeholder":"Filtrer par nom d'entité ou d'appareil","adopted.no_results":"Aucune entité adoptée ne correspond à ce filtre","adopted.none":"Ce panneau ne publie rien à curer.","adopted.load_failed":"Impossible de charger les entités adoptées","adopted.count":"{count} adoptées","adopted.vendor_readings":"RELEVÉS DU FOURNISSEUR","adopted.adopted_device":"APPAREIL ADOPTÉ","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURÉE","adopted.stale":"OBSOLÈTE","adopted.stale_note":"Le panneau ne prend plus en charge ce qui a été enregistré pour : {fields}","adopted.enable_entity":"Activer l'entité","adopted.enabled":"ACTIVÉE","adopted.disabled":"DÉSACTIVÉE","adopted.enable_note":"Activée à l'enregistrement — la curation n'active jamais d'elle-même","adopted.registry_unavailable":"L'activation et le nom seront disponibles dès que cette entité existera dans le registre.","adopted.name":"Nom","adopted.device_class":"Classe d'appareil","adopted.device_class_note":"choix limités par l'unité du panneau ({unit})","adopted.device_class_note_unitless":"choix limités par ce que le panneau publie","adopted.no_device_class":"Aucune classe d'appareil","adopted.statistics_class":"Classe de statistiques","adopted.statistics_note":"les statistiques à long terme commencent après le prochain rechargement","adopted.no_statistics":"Aucune statistique","adopted.prominence":"Proéminence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Unité affichée","adopted.unit_as_published":"Telle que publiée","adopted.precision":"Précision","adopted.precision_default":"Par défaut","adopted.read_only":"lecture seule","adopted.settable":"modifiable","adopted.save":"Enregistrer","adopted.clear":"Effacer la curation","adopted.reload_note":"L'enregistrement recharge l'intégration SPAN Panel","adopted.saved":"Enregistré — l'intégration se recharge","adopted.confirm_heading":"Confirmer la classe de statistiques","adopted.confirm_setting":"Vous définissez {name} sur {value}.","adopted.confirm_clearing_subject":"Vous effacez la classe de statistiques de {name}.","adopted.confirm_total_increasing":"Total croissant interprète chaque baisse de la valeur comme une remise à zéro du compteur. Si ce relevé peut diminuer pour une autre raison, les statistiques à long terme seront corrompues de façon permanente — corriger la classe plus tard ne répare pas l'historique déjà écrit.","adopted.confirm_clearing":"Les statistiques à long terme cesseront d'être compilées pour cette entité, et Home Assistant ouvrira une réparation sur les statistiques déjà collectées sous la classe que vous retirez.","adopted.save_anyway":"Enregistrer quand même","adopted.cancel":"Annuler","adopted.warn_total_increasing":"Enregistré en total croissant — chaque baisse du relevé compte désormais comme une remise à zéro du compteur.","adopted.warn_statistics_removed":"Cette entité n'a plus de classe de statistiques ; Home Assistant ouvrira une réparation sur les statistiques déjà collectées.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Paramètres de surveillance du panneau","header.graph_settings":"Paramètres d'horizon temporel du graphique","header.site":"Site","header.grid":"Réseau","header.upstream":"Amont","header.downstream":"Aval","header.solar":"Solaire","header.battery":"Batterie","header.toggle_units":"Basculer Watts / Ampères","header.enable_switches":"Activer les interrupteurs","header.switches_enabled":"Interrupteurs activés","controls.admin_only":"Seul un administrateur peut utiliser les commandes de ce panneau.","controls.disabled":"La commande de ce panneau est désactivée dans ses options.","controls.read_only":"Votre compte Home Assistant ne peut pas utiliser les commandes de ce panneau.","controls.entity_unauthorized":"Votre compte Home Assistant ne peut pas utiliser cette commande.","controls.not_operable":"Vous ne pouvez pas utiliser les commandes de ce panneau.","grid.unknown":"Inconnu","grid.configure":"Configurer le circuit","grid.configure_subdevice":"Configurer l'appareil","grid.on":"On","grid.off":"Off","grid.shared_switch":"Commute tous les circuits de cet emplacement","meters.title":"Compteurs","meters.importing":"en import","meters.exporting":"en export","meters.imported":"importés","meters.exported":"exportés","subdevice.ev_charger":"Chargeur VE","subdevice.battery":"Batterie","subdevice.fallback":"Sous-appareil","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Puissance","subdevice.solar":"Solaire","subdevice.solar_inverter":"Onduleur solaire","subdevice.site_total":"Total du site","subdevice.in_site_total":"Inclus dans le total du site","sidepanel.graph_settings":"Paramètres des Graphiques","sidepanel.global_defaults":"Valeurs par défaut globales pour tous les circuits","sidepanel.favorites_subtitle":"Favoris","sidepanel.global_default":"Défaut Global","sidepanel.list_view_columns":"Colonnes de la liste","sidepanel.columns":"Colonnes","sidepanel.circuit_scales":"Échelles des Graphiques de Circuits","sidepanel.subdevice_scales":"Échelles des Graphiques de Sous-Appareils","sidepanel.reset_to_global":"Réinitialiser à la valeur globale","sidepanel.relay":"Relais","sidepanel.breaker":"Disjoncteur","sidepanel.capacity":"capacité de {amps} A","monitoringRating.title":"Calibres des disjoncteurs dans l'application SPAN","monitoringRating.panel_rating":"Le panneau publie {panel} A","monitoringRating.other_breaker":"Autre disjoncteur (A)","monitoringRating.other_breaker_label":"Autre disjoncteur dans l'emplacement de {circuit}","monitoringRating.reset":"Supprimer les calibres copiés","monitoringRating.invalid_other":"Saisissez le calibre de l'autre disjoncteur en nombre entier d'ampères, 1 ou plus.","monitoringRating.guidance":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-20A, saisissez ici le second. Les panneaux SPAN Panel MAIN 32 n'indiquent que le premier, et la surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble.","monitoringRating.guidance_two_spaces":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-30A, saisissez ici le second.","monitoringRating.averaged_legs":"Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases de ce circuit, ce qui peut masquer une phase en surcharge. Nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.turn_off_monitoring":"Désactiver la surveillance","monitoringRating.threshold_warning":"Les seuils personnalisés de ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge.","monitoringRating.threshold_warning_global":"Les seuils globaux qu'utilise ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge ; modifiez-les dans {settings}, onglet {tab}.","monitoringRating.use_global_thresholds":"Utiliser les seuils globaux","monitoringRating.note_title":"Disjoncteurs tandem sur SPAN Panel MAIN 32","monitoringRating.note_problem":"Les panneaux SPAN Panel MAIN 32 n'indiquent pas quels disjoncteurs sont des tandems, ni le calibre du second disjoncteur d'un tandem. Un tandem place deux disjoncteurs dans un emplacement, mais le panneau l'indique comme un seul circuit avec le calibre du premier disjoncteur seulement, tandis qu'un seul capteur lit les deux disjoncteurs ensemble. Un tandem 20-20 affiche 20 A ici et peut supporter 40 A, si bien que la surveillance déclenche de fausses alertes sur lui.","monitoringRating.note_steps":"Pour corriger cela, copiez les calibres depuis votre application SPAN :","monitoringRating.note_step_find":"Dans l'application SPAN, trouvez chaque circuit dont le disjoncteur affiche deux calibres, par exemple 20-20A.","monitoringRating.note_step_enter":"Dans le tableau ci-dessous, saisissez le second calibre dans le champ {column} de ce circuit. Appuyez ensuite sur Entrée ou passez au champ suivant.","monitoringRating.note_step_single":"Laissez le champ vide pour un circuit à disjoncteur unique.","monitoringRating.note_judged":"La surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble : 40 A pour un 20-20. Seule la surveillance utilise la copie, et le capteur Breaker Rating du circuit affiche toujours ce que le panneau indique. Pour supprimer un calibre copié, sélectionnez ✕ à côté de son champ.","monitoringRating.note_thresholds":"Si vous avez relevé les seuils d'un tandem au-dessus de 100 % pour faire cesser ses alertes, sélectionnez {reset} sur sa ligne. Ces seuils s'appliquent désormais aux deux disjoncteurs ensemble.","monitoringRating.note_two_spaces":"Pour un circuit qui occupe deux emplacements, saisissez le second calibre de la même façon si votre application SPAN en affiche deux, par exemple 20-30A. Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases d'un tel circuit, ce qui peut masquer une phase en surcharge : la copie ne peut donc pas être appliquée, et nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.note_guide":"Pour en savoir plus, consultez le guide des disjoncteurs tandem et à charges multiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Supprimer les calibres copiés de {circuit}","monitoringRating.table_threshold_warning":"Les seuils de ce circuit dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Sélectionnez {reset} pour utiliser les seuils globaux.","monitoringRating.table_threshold_warning_global":"Les seuils globaux dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Modifiez-les dans {settings} ci-dessus.","monitoringRating.warning_announcement":"{circuit} : {warning}","error.package_ratings_failed":"Impossible de mettre à jour les calibres copiés depuis l'application SPAN","sidepanel.judged_against":"Évalué selon : {rating}","sidepanel.shedding_priority":"Priorité de Délestage","sidepanel.priority_label":"Priorité","sidepanel.monitoring":"Surveillance","sidepanel.global":"Global","sidepanel.custom":"Personnalisé","sidepanel.continuous_pct":"Continu %","sidepanel.spike_pct":"Pic %","sidepanel.window_duration":"Durée de fenêtre","sidepanel.cooldown":"Refroidissement","sidepanel.favorite":"Favori","sidepanel.save_to_favorites":"Enregistrer dans les favoris","panel.favorites":"Favoris","status.monitoring":"Surveillance","status.circuits":"circuits","status.mains":"alimentation","status.warning":"avertissement","status.warnings":"avertissements","status.alert":"alerte","status.alerts":"alertes","status.override":"remplacement","status.overrides":"remplacements","card.no_device":"Ouvrez l'éditeur de carte et sélectionnez votre appareil SPAN Panel.","card.device_not_found":"Appareil de panneau introuvable. Vérifiez device_id dans la configuration de la carte.","card.topology_error":"La réponse de topologie ne contient pas panel_size et aucun circuit trouvé. Mettez à jour l'intégration SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Sélectionnez un panneau...","editor.chart_window":"Fenêtre de temps du graphique","editor.days":"jours","editor.hours":"heures","editor.minutes":"minutes","editor.chart_metric":"Métrique du graphique","editor.visible_sections":"Sections visibles","editor.panel_circuits":"Circuits du panneau","editor.battery_bess":"Batterie (BESS)","editor.ev_charger_evse":"Chargeur VE (EVSE)","editor.solar_pv":"Solaire (PV)","editor.no_entities":"Aucune entité à afficher","editor.tab_style":"Style des onglets","editor.tab_style_text":"Texte","editor.tab_style_icon":"Icône","metric.power":"Puissance","metric.current":"Courant","metric.soc":"État de Charge","metric.soe":"État d'Énergie","shedding.always_on":"Critique","shedding.never":"Non délestable","shedding.soc_threshold":"Seuil SoC","shedding.off_grid":"Délestable","shedding.unknown":"Inconnu","shedding.select.never":"Reste allumé en cas de coupure","shedding.select.soc_threshold":"Allumé jusqu'au seuil batterie","shedding.select.off_grid":"S'éteint en cas de coupure"},ja:{"tab.panel":"パネル","tab.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","tab.settings":"設定","tab.adopted":"採用済み","list.search_placeholder":"回路を検索...","list.unassigned_area":"未割り当て","list.no_results":"回路が見つかりません","monitoring.heading":"モニタリング","monitoring.global_settings":"グローバル設定","monitoring.enabled":"有効","monitoring.continuous":"継続 (%)","monitoring.spike":"スパイク (%)","monitoring.window":"ウィンドウ (分)","monitoring.cooldown":"クールダウン (分)","monitoring.monitored_points":"監視ポイント","monitoring.col.name":"名前","monitoring.col.continuous":"継続","monitoring.col.spike":"スパイク","monitoring.col.window":"ウィンドウ","monitoring.col.cooldown":"クールダウン","monitoring.rating":"定格","monitoring.all_none":"全選択 / 全解除","monitoring.reset":"リセット","monitoring.limit_invalid":"{min} から {max} までの整数を入力してください。","monitoring.enable_invalid":"モニタリングは有効になっていません。マークされた項目を修正してください。","monitoring.point_field":"{name}の{field}","monitoring.reset_point":"{name}をリセット","monitoring.admin_only":"モニタリングを変更できるのは管理者のみです。","notification.heading":"通知設定","notification.targets":"通知先","notification.none_selected":"未選択","notification.targets_button":"通知先: {targets}","notification.no_targets":"通知先が見つかりません","notification.all_targets":"すべて","notification.event_bus_target":"イベントバス (HAイベントバス)","notification.priority":"優先度","notification.priority.default":"デフォルト","notification.priority.passive":"パッシブ","notification.priority.active":"アクティブ","notification.priority.time_sensitive":"緊急","notification.priority.critical":"重大","notification.hint.critical":"サイレント/おやすみモードを無視","notification.hint.time_sensitive":"集中モードを突破","notification.hint.passive":"サイレント配信","notification.hint.active":"標準配信","notification.title_template":"タイトルテンプレート","notification.message_template":"メッセージテンプレート","notification.placeholders":"プレースホルダー:","notification.event_bus_help":"イベントバスが発行するイベントタイプ","notification.event_bus_payload":"ペイロード:","notification.test_label":"テスト通知","notification.test_button":"テスト送信","notification.test_sending":"送信中...","notification.test_sent":"テスト通知を送信しました","error.prefix":"エラー:","error.failed_save":"保存に失敗","error.failed":"失敗","error.panel_offline":"SPANパネルに接続できません","error.panel_reconnected":"SPANパネルが再接続されました","error.panel_offline_named":"{name}に接続できません","error.panel_reconnected_named":"{name}が再接続されました","error.discovery_failed":"SPANパネルへの接続に失敗しました","error.relay_failed":"リレーの切り替えに失敗しました","error.shedding_failed":"シェディング優先度の更新に失敗しました","error.threshold_failed":"しきい値の保存に失敗しました","error.graph_horizon_failed":"グラフの時間範囲の更新に失敗しました","error.favorites_fetch_failed":"お気に入りの読み込みに失敗しました","error.favorites_toggle_failed":"お気に入りの更新に失敗しました","error.history_failed":"履歴データの読み込みに失敗しました","error.monitoring_failed":"監視ステータスの読み込みに失敗しました","error.graph_settings_failed":"グラフ設定の読み込みに失敗しました","error.areas_failed":"エリア割り当てが同期されていない可能性があります","error.retry":"再試行","card.connecting":"SPANパネルに接続中...","card.waiting_for_load":"SPANパネルの読み込みを待機中...","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","settings.heading":"設定","settings.description":"統合の一般設定(エンティティ名、デバイスプレフィックス、回路番号)は統合のオプションフローで管理されます。","settings.open_link":"SPAN Panel統合設定を開く","adopted.heading":"採用済みエンティティ","adopted.description":"ベンダーの測定値と採用済みデバイスは最小限のメタデータで登録されます。キュレーションでデバイスクラス、統計クラス、表示区分を設定できます。保存すると統合が再読み込みされ、次回の起動から適用されます。","adopted.filter_placeholder":"エンティティ名またはデバイス名で絞り込み","adopted.no_results":"この条件に一致する採用済みエンティティはありません","adopted.none":"このパネルにキュレーション対象はありません。","adopted.load_failed":"採用済みエンティティを読み込めません","adopted.count":"{count} 件","adopted.vendor_readings":"ベンダー測定値","adopted.adopted_device":"採用済みデバイス","adopted.via_panel":"SPAN Panel 経由","adopted.curated":"キュレーション済み","adopted.stale":"無効","adopted.stale_note":"パネルは保存された次の項目をサポートしなくなりました: {fields}","adopted.enable_entity":"エンティティを有効化","adopted.enabled":"有効","adopted.disabled":"無効","adopted.enable_note":"保存時に有効化されます — キュレーション自体が有効化することはありません","adopted.registry_unavailable":"有効化・名前は、このエンティティがレジストリに登録された後に利用できます。","adopted.name":"名前","adopted.device_class":"デバイスクラス","adopted.device_class_note":"パネルの単位({unit})により選択肢が制限されます","adopted.device_class_note_unitless":"パネルが公開する内容により選択肢が制限されます","adopted.no_device_class":"デバイスクラスなし","adopted.statistics_class":"統計クラス","adopted.statistics_note":"長期統計は次回の再読み込み後に開始されます","adopted.no_statistics":"統計なし","adopted.prominence":"表示区分","adopted.diagnostic":"診断","adopted.standard":"標準","adopted.display_unit":"表示単位","adopted.unit_as_published":"公開されたまま","adopted.precision":"小数点以下桁数","adopted.precision_default":"既定","adopted.read_only":"読み取り専用","adopted.settable":"書き込み可","adopted.save":"保存","adopted.clear":"キュレーションを消去","adopted.reload_note":"保存すると SPAN Panel 統合が再読み込みされます","adopted.saved":"保存しました — 統合を再読み込みしています","adopted.confirm_heading":"統計クラスの確認","adopted.confirm_setting":"{name} を {value} に設定しようとしています。","adopted.confirm_clearing_subject":"{name} の統計クラスを消去しようとしています。","adopted.confirm_total_increasing":"積算増加は値の低下をすべてメーターのリセットとして扱います。この測定値が他の理由でも下がる場合、長期統計は恒久的に破損します。後からクラスを直しても、既に書き込まれた履歴は修復されません。","adopted.confirm_clearing":"このエンティティの長期統計は収集されなくなり、削除するクラスの下で既に収集された統計について Home Assistant が修復項目を作成します。","adopted.save_anyway":"それでも保存","adopted.cancel":"キャンセル","adopted.warn_total_increasing":"積算増加として保存しました — 測定値の低下はすべてメーターのリセットとして数えられます。","adopted.warn_statistics_removed":"このエンティティに統計クラスはなくなりました。既に収集された統計について Home Assistant が修復項目を作成します。","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"パネルモニタリング設定","header.graph_settings":"グラフ時間範囲設定","header.site":"サイト","header.grid":"グリッド","header.upstream":"上流","header.downstream":"下流","header.solar":"ソーラー","header.battery":"バッテリー","header.toggle_units":"ワット/アンペア切り替え","header.enable_switches":"スイッチを有効化","header.switches_enabled":"スイッチ有効","controls.admin_only":"このパネルのコントロールを操作できるのは管理者のみです。","controls.disabled":"このパネルのコントロールはオプションで無効になっています。","controls.read_only":"お使いのHome Assistantアカウントでは、このパネルのコントロールを操作できません。","controls.entity_unauthorized":"お使いのHome Assistantアカウントでは、このコントロールを操作できません。","controls.not_operable":"このパネルのコントロールは操作できません。","grid.unknown":"不明","grid.configure":"回路を設定","grid.configure_subdevice":"デバイスを設定","grid.on":"オン","grid.off":"オフ","grid.shared_switch":"このスペースのすべての回路を切り替えます","meters.title":"メーター","meters.importing":"受電中","meters.exporting":"送電中","meters.imported":"受電","meters.exported":"送電","subdevice.ev_charger":"EV充電器","subdevice.battery":"バッテリー","subdevice.fallback":"サブデバイス","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"電力","subdevice.solar":"ソーラー","subdevice.solar_inverter":"ソーラーインバーター","subdevice.site_total":"サイト合計","subdevice.in_site_total":"サイト合計に含まれます","sidepanel.graph_settings":"グラフ設定","sidepanel.global_defaults":"全回路のグローバルデフォルト","sidepanel.favorites_subtitle":"お気に入り","sidepanel.global_default":"グローバルデフォルト","sidepanel.list_view_columns":"リスト表示の列数","sidepanel.columns":"列","sidepanel.circuit_scales":"回路グラフスケール","sidepanel.subdevice_scales":"サブデバイスグラフスケール","sidepanel.reset_to_global":"グローバルにリセット","sidepanel.relay":"リレー","sidepanel.breaker":"ブレーカー","sidepanel.capacity":"容量 {amps} A","monitoringRating.title":"SPAN アプリのブレーカー定格","monitoringRating.panel_rating":"パネルの公開値 {panel} A","monitoringRating.other_breaker":"もう一方のブレーカー (A)","monitoringRating.other_breaker_label":"{circuit} のスペースにあるもう一方のブレーカー","monitoringRating.reset":"コピーした定格を削除","monitoringRating.invalid_other":"もう一方のブレーカーの定格を 1 以上の整数のアンペアで入力してください。","monitoringRating.guidance":"SPAN アプリでこの回路に 20-20A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。SPAN Panel MAIN 32 パネルが報告するのは 1 つ目だけで、モニタリングはこのスペースを両方のブレーカーの合計で判定します。","monitoringRating.guidance_two_spaces":"SPAN アプリでこの回路に 20-30A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 パネルはこの回路の 2 本の線の平均値しか報告しないため、過負荷の線が見えなくなることがあります。この回路のモニタリングをオフにすることをおすすめします。","monitoringRating.turn_off_monitoring":"モニタリングをオフにする","monitoringRating.threshold_warning":"この回路のカスタムしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。","monitoringRating.threshold_warning_global":"この回路が使用するグローバルしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。{tab}タブの{settings}で変更してください。","monitoringRating.use_global_thresholds":"グローバルしきい値を使用","monitoringRating.note_title":"SPAN Panel MAIN 32 のタンデムブレーカー","monitoringRating.note_problem":"SPAN Panel MAIN 32 パネルは、どのブレーカーがタンデムかも、タンデムの 2 つ目のブレーカーの定格も報告しません。タンデムは 1 つのスペースに 2 つのブレーカーを収めますが、パネルはそれを 1 つ目のブレーカーの定格だけを持つ 1 つの回路として報告し、1 つのセンサーが両方のブレーカーの合計を読み取ります。20-20 のタンデムはここでは 20 A と表示されますが 40 A まで流せるため、モニタリングが誤ったアラートを出します。","monitoringRating.note_steps":"これを直すには、次の手順で SPAN アプリから定格をコピーします。","monitoringRating.note_step_find":"SPAN アプリで、ブレーカーに 20-20A のように 2 つの定格が表示されている回路をすべて探します。","monitoringRating.note_step_enter":"下の表で、その回路の{column}フィールドに 2 つ目の定格を入力します。続けて Enter キーを押すか、次のフィールドに移動します。","monitoringRating.note_step_single":"ブレーカーが 1 つだけの回路では、フィールドを空のままにします。","monitoringRating.note_judged":"するとモニタリングは、そのスペースを両方のブレーカーの合計で判定します。20-20 なら 40 A です。コピーを使うのはモニタリングだけで、回路の Breaker Rating センサーは引き続きパネルが報告する値を表示します。コピーした定格を削除するには、フィールドの横の ✕ を選択します。","monitoringRating.note_thresholds":"アラートを止めるためにタンデムのしきい値を 100% より上に上げていた場合は、その行の{reset}を選択してください。それらのしきい値は今後、両方のブレーカーの合計に適用されます。","monitoringRating.note_two_spaces":"2 つのスペースにまたがる回路でも、SPAN アプリに 20-30A のように 2 つの定格が表示されていれば、同じ方法で 2 つ目の定格を入力します。SPAN Panel MAIN 32 パネルはそのような回路の 2 本の線の平均値しか報告せず、過負荷の線が見えなくなることがあるため、コピーは適用できません。その回路のモニタリングをオフにすることをおすすめします。","monitoringRating.note_guide":"詳しくは、タンデムブレーカーと複数負荷ブレーカーのガイドをご覧ください。","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"{circuit} のコピーした定格を削除","monitoringRating.table_threshold_warning":"この回路のしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。{reset}を選択するとグローバルしきい値を使用します。","monitoringRating.table_threshold_warning_global":"グローバルしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。上の{settings}で変更してください。","monitoringRating.warning_announcement":"{circuit}:{warning}","error.package_ratings_failed":"SPAN アプリからコピーした定格の更新に失敗しました","sidepanel.judged_against":"判定基準: {rating}","sidepanel.shedding_priority":"シェディング優先度","sidepanel.priority_label":"優先度","sidepanel.monitoring":"モニタリング","sidepanel.global":"グローバル","sidepanel.custom":"カスタム","sidepanel.continuous_pct":"継続 %","sidepanel.spike_pct":"スパイク %","sidepanel.window_duration":"ウィンドウ時間","sidepanel.cooldown":"クールダウン","sidepanel.favorite":"お気に入り","sidepanel.save_to_favorites":"お気に入りに保存","panel.favorites":"お気に入り","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","card.device_not_found":"パネルデバイスが見つかりません。カード設定のdevice_idを確認してください。","card.topology_error":"トポロジー応答にpanel_sizeがなく、回路が見つかりません。SPAN Panel統合を更新してください。","editor.panel_label":"SPAN Panel","editor.select_panel":"パネルを選択...","editor.chart_window":"グラフ時間ウィンドウ","editor.days":"日","editor.hours":"時間","editor.minutes":"分","editor.chart_metric":"グラフ指標","editor.visible_sections":"表示セクション","editor.panel_circuits":"パネル回路","editor.battery_bess":"バッテリー (BESS)","editor.ev_charger_evse":"EV充電器 (EVSE)","editor.solar_pv":"ソーラー (PV)","editor.no_entities":"表示するエンティティがありません","editor.tab_style":"タブスタイル","editor.tab_style_text":"テキスト","editor.tab_style_icon":"アイコン","metric.power":"電力","metric.current":"電流","metric.soc":"充電状態","metric.soe":"エネルギー状態","shedding.always_on":"重要","shedding.never":"切断不可","shedding.soc_threshold":"SoCしきい値","shedding.off_grid":"切断可能","shedding.unknown":"不明","shedding.select.never":"停電時もオンを維持","shedding.select.soc_threshold":"バッテリーしきい値までオン","shedding.select.off_grid":"停電時にオフ"},pt:{"tab.panel":"Painel","tab.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","tab.settings":"Configurações","tab.adopted":"Adotadas","list.search_placeholder":"Pesquisar circuitos...","list.unassigned_area":"Não atribuído","list.no_results":"Nenhum circuito encontrado","monitoring.heading":"Monitoramento","monitoring.global_settings":"Configurações Globais","monitoring.enabled":"Ativado","monitoring.continuous":"Contínuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Janela (min)","monitoring.cooldown":"Resfriamento (min)","monitoring.monitored_points":"Pontos Monitorados","monitoring.col.name":"Nome","monitoring.col.continuous":"Contínuo","monitoring.col.spike":"Pico","monitoring.col.window":"Janela","monitoring.col.cooldown":"Resfriamento","monitoring.rating":"Corrente nominal","monitoring.all_none":"Todos / Nenhum","monitoring.reset":"Redefinir","monitoring.limit_invalid":"Digite um número inteiro de {min} a {max}.","monitoring.enable_invalid":"O monitoramento não foi ativado: corrija os campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Redefinir {name}","monitoring.admin_only":"Somente um administrador pode alterar o monitoramento.","notification.heading":"Configurações de Notificação","notification.targets":"Destinos de Notificação","notification.none_selected":"Nenhum selecionado","notification.targets_button":"Destinos de Notificação: {targets}","notification.no_targets":"Nenhum destino de notificação encontrado","notification.all_targets":"Todos","notification.event_bus_target":"Barramento de Eventos (barramento de eventos do HA)","notification.priority":"Prioridade","notification.priority.default":"Padrão","notification.priority.passive":"Passivo","notification.priority.active":"Ativo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Substitui silencioso/Não perturbar","notification.hint.time_sensitive":"Atravessa o modo Foco","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega padrão","notification.title_template":"Modelo de Título","notification.message_template":"Modelo de Mensagem","notification.placeholders":"Variáveis:","notification.event_bus_help":"O Barramento de Eventos dispara o tipo de evento","notification.event_bus_payload":"com dados:","notification.test_label":"Notificação de teste","notification.test_button":"Enviar teste","notification.test_sending":"Enviando...","notification.test_sent":"Notificação de teste enviada","error.prefix":"Erro:","error.failed_save":"Falha ao salvar","error.failed":"Falhou","error.panel_offline":"SPAN Panel inacessível","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inacessível","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"Não foi possível conectar ao SPAN Panel","error.relay_failed":"Não foi possível alternar o relé","error.shedding_failed":"Não foi possível atualizar a prioridade de desligamento","error.threshold_failed":"Não foi possível salvar o limite","error.graph_horizon_failed":"Não foi possível atualizar o horizonte temporal do gráfico","error.favorites_fetch_failed":"Não foi possível carregar os favoritos","error.favorites_toggle_failed":"Não foi possível atualizar o favorito","error.history_failed":"Não foi possível carregar os dados históricos","error.monitoring_failed":"Não foi possível carregar o status de monitoramento","error.graph_settings_failed":"Não foi possível carregar as configurações do gráfico","error.areas_failed":"As atribuições de áreas podem estar fora de sincronização","error.retry":"Tentar novamente","card.connecting":"Conectando ao SPAN Panel...","card.waiting_for_load":"Aguardando o carregamento do SPAN Panel...","monitoringRating.none":"sem corrente nominal","monitoringRating.copied":"{package} do seu app SPAN (o painel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado do seu app SPAN","monitoringRating.judged_copied":"Avaliado com base em {rating} A: {copied}","settings.heading":"Configurações","settings.description":"As configurações gerais da integração (nomes de entidades, prefixo do dispositivo, números de circuito) são gerenciadas através do fluxo de opções da integração.","settings.open_link":"Abrir Configurações de Integração SPAN Panel","adopted.heading":"Entidades adotadas","adopted.description":"As leituras do fornecedor e os dispositivos adotados chegam com metadados mínimos. Faça a curadoria de uma para definir sua classe de dispositivo, classe de estatísticas e proeminência — alterações salvas recarregam a integração e valem a partir da próxima inicialização.","adopted.filter_placeholder":"Filtrar por nome de entidade ou dispositivo","adopted.no_results":"Nenhuma entidade adotada corresponde a este filtro","adopted.none":"Este painel não publica nada para curadoria.","adopted.load_failed":"Não foi possível carregar as entidades adotadas","adopted.count":"{count} adotadas","adopted.vendor_readings":"LEITURAS DO FORNECEDOR","adopted.adopted_device":"DISPOSITIVO ADOTADO","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"O painel não suporta mais o que foi salvo para: {fields}","adopted.enable_entity":"Ativar entidade","adopted.enabled":"ATIVADA","adopted.disabled":"DESATIVADA","adopted.enable_note":"Ativada ao salvar — a curadoria nunca ativa por conta própria","adopted.registry_unavailable":"Ativação e nome ficam disponíveis assim que esta entidade existir no registro.","adopted.name":"Nome","adopted.device_class":"Classe de dispositivo","adopted.device_class_note":"opções limitadas pela unidade do painel ({unit})","adopted.device_class_note_unitless":"opções limitadas pelo que o painel publica","adopted.no_device_class":"Sem classe de dispositivo","adopted.statistics_class":"Classe de estatísticas","adopted.statistics_note":"as estatísticas de longo prazo começam após a próxima recarga","adopted.no_statistics":"Sem estatísticas","adopted.prominence":"Proeminência","adopted.diagnostic":"Diagnóstico","adopted.standard":"Padrão","adopted.display_unit":"Unidade exibida","adopted.unit_as_published":"Como publicada","adopted.precision":"Precisão","adopted.precision_default":"Padrão","adopted.read_only":"somente leitura","adopted.settable":"editável","adopted.save":"Salvar","adopted.clear":"Limpar curadoria","adopted.reload_note":"Salvar recarrega a integração SPAN Panel","adopted.saved":"Salvo — a integração está recarregando","adopted.confirm_heading":"Confirmar classe de estatísticas","adopted.confirm_setting":"Você está definindo {name} como {value}.","adopted.confirm_clearing_subject":"Você está limpando a classe de estatísticas de {name}.","adopted.confirm_total_increasing":"Total crescente trata toda queda do valor como uma reinicialização do medidor. Se esta leitura puder diminuir por qualquer outro motivo, as estatísticas de longo prazo ficarão permanentemente corrompidas — corrigir a classe depois não repara o histórico já gravado.","adopted.confirm_clearing":"As estatísticas de longo prazo deixarão de ser compiladas para esta entidade, e o Home Assistant abrirá um reparo sobre as estatísticas já coletadas na classe que você está removendo.","adopted.save_anyway":"Salvar mesmo assim","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Salvo como total crescente — cada queda da leitura agora conta como uma reinicialização do medidor.","adopted.warn_statistics_removed":"Esta entidade não tem mais classe de estatísticas; o Home Assistant abrirá um reparo sobre as estatísticas já coletadas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configurações de monitoramento do painel","header.graph_settings":"Configurações do horizonte temporal do gráfico","header.site":"Local","header.grid":"Rede","header.upstream":"Montante","header.downstream":"Jusante","header.solar":"Solar","header.battery":"Bateria","header.toggle_units":"Alternar Watts / Amperes","header.enable_switches":"Ativar Interruptores","header.switches_enabled":"Interruptores Ativados","controls.admin_only":"Somente um administrador pode operar os controles deste painel.","controls.disabled":"O controle deste painel está desativado nas suas opções.","controls.read_only":"Sua conta do Home Assistant não pode operar os controles deste painel.","controls.entity_unauthorized":"Sua conta do Home Assistant não pode operar este controle.","controls.not_operable":"Você não pode operar os controles deste painel.","grid.unknown":"Desconhecido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Lig","grid.off":"Des","grid.shared_switch":"Liga e desliga todos os circuitos deste espaço","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Carregador VE","subdevice.battery":"Bateria","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potência","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total do local","subdevice.in_site_total":"Incluído no total do local","sidepanel.graph_settings":"Configurações de Gráficos","sidepanel.global_defaults":"Padrões globais para todos os circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Padrão Global","sidepanel.list_view_columns":"Colunas da Lista","sidepanel.columns":"Colunas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Redefinir para o padrão global","sidepanel.relay":"Relé","sidepanel.breaker":"Disjuntor","sidepanel.capacity":"capacidade de {amps} A","monitoringRating.title":"Correntes nominais dos disjuntores no app SPAN","monitoringRating.panel_rating":"O painel publica {panel} A","monitoringRating.other_breaker":"Outro disjuntor (A)","monitoringRating.other_breaker_label":"Outro disjuntor no espaço de {circuit}","monitoringRating.reset":"Remover as correntes nominais copiadas","monitoringRating.invalid_other":"Digite a corrente nominal do outro disjuntor como um número inteiro de amperes, 1 ou mais.","monitoringRating.guidance":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-20A, digite a segunda aqui. Os painéis SPAN Panel MAIN 32 informam apenas a primeira, e o monitoramento então avalia este espaço pelos dois disjuntores juntos.","monitoringRating.guidance_two_spaces":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-30A, digite a segunda aqui.","monitoringRating.averaged_legs":"Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases deste circuito, o que pode esconder uma fase sobrecarregada. Recomendamos desativar o monitoramento deste circuito.","monitoringRating.turn_off_monitoring":"Desativar o monitoramento","monitoringRating.threshold_warning":"Os limites personalizados deste circuito passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real.","monitoringRating.threshold_warning_global":"Os limites globais que este circuito usa passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real; altere-os em {settings}, na aba {tab}.","monitoringRating.use_global_thresholds":"Usar os limites globais","monitoringRating.note_title":"Disjuntores tandem no SPAN Panel MAIN 32","monitoringRating.note_problem":"Os painéis SPAN Panel MAIN 32 não informam quais disjuntores são tandem, nem a corrente nominal do segundo disjuntor de um tandem. Um tandem coloca dois disjuntores em um espaço, mas o painel o informa como um único circuito com apenas a corrente nominal do primeiro disjuntor, enquanto um único sensor lê os dois disjuntores juntos. Um tandem 20-20 mostra 20 A aqui e pode conduzir 40 A, então o monitoramento gera alertas falsos nele.","monitoringRating.note_steps":"Para corrigir isso, copie as correntes nominais do seu app SPAN:","monitoringRating.note_step_find":"No app SPAN, encontre cada circuito cujo disjuntor mostra duas correntes nominais, como 20-20A.","monitoringRating.note_step_enter":"Na tabela abaixo, digite a segunda corrente nominal no campo {column} desse circuito. Depois pressione Enter ou vá para o próximo campo.","monitoringRating.note_step_single":"Deixe o campo vazio para um circuito com um único disjuntor.","monitoringRating.note_judged":"O monitoramento então avalia esse espaço pelos dois disjuntores juntos: 40 A para um 20-20. Só o monitoramento usa a cópia, e o sensor Breaker Rating do circuito continua mostrando o que o painel informa. Para remover uma corrente nominal copiada, selecione ✕ ao lado do seu campo.","monitoringRating.note_thresholds":"Se você aumentou os limites de um tandem acima de 100% para interromper os alertas dele, selecione {reset} na linha dele. Esses limites agora se aplicam aos dois disjuntores juntos.","monitoringRating.note_two_spaces":"Para um circuito que ocupa dois espaços, digite a segunda corrente nominal da mesma forma se o seu app SPAN mostrar duas, como 20-30A. Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases de um circuito assim, o que pode esconder uma fase sobrecarregada, então a cópia não pode ser aplicada e recomendamos desativar o monitoramento desse circuito.","monitoringRating.note_guide":"Leia mais no guia de disjuntores tandem e de cargas múltiplas.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remover as correntes nominais copiadas de {circuit}","monitoringRating.table_threshold_warning":"Os limites deste circuito passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Selecione {reset} para usar os limites globais.","monitoringRating.table_threshold_warning_global":"Os limites globais passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Altere-os em {settings}, acima.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Não foi possível atualizar as correntes nominais copiadas do app SPAN","sidepanel.judged_against":"Avaliado com base em: {rating}","sidepanel.shedding_priority":"Prioridade de Desligamento","sidepanel.priority_label":"Prioridade","sidepanel.monitoring":"Monitoramento","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Contínuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duração da janela","sidepanel.cooldown":"Resfriamento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Salvar nos favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoramento","status.circuits":"circuitos","status.mains":"alimentação","status.warning":"aviso","status.warnings":"avisos","status.alert":"alerta","status.alerts":"alertas","status.override":"substituição","status.overrides":"substituições","card.no_device":"Abra o editor do cartão e selecione seu dispositivo SPAN Panel.","card.device_not_found":"Dispositivo do painel não encontrado. Verifique device_id na configuração do cartão.","card.topology_error":"A resposta de topologia não contém panel_size e nenhum circuito encontrado. Atualize a integração SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Selecione um painel...","editor.chart_window":"Janela de tempo do gráfico","editor.days":"dias","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica do gráfico","editor.visible_sections":"Seções visíveis","editor.panel_circuits":"Circuitos do painel","editor.battery_bess":"Bateria (BESS)","editor.ev_charger_evse":"Carregador VE (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"Nenhuma entidade para mostrar","editor.tab_style":"Estilo das abas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícone","metric.power":"Potência","metric.current":"Corrente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energia","shedding.always_on":"Crítico","shedding.never":"Não desligável","shedding.soc_threshold":"Limite SoC","shedding.off_grid":"Desligável","shedding.unknown":"Desconhecido","shedding.select.never":"Permanece ligado em uma queda","shedding.select.soc_threshold":"Ligado até limite da bateria","shedding.select.off_grid":"Desliga em uma queda"}};function n(n){t=n&&e[n]?n:"en"}function i(n){return e[t]?.[n]??e.en?.[n]??n}function r(n,i){return(e[t]?.[n]??e.en?.[n]??n).replace(/\{(\w+)\}/g,(t,e)=>Object.prototype.hasOwnProperty.call(i,e)?i[e]:`{${e}}`)}const o="power",a="5m",s={"5m":{ms:3e5,refreshMs:1e3,useRealtime:!0},"1h":{ms:36e5,refreshMs:3e4,useRealtime:!1},"1d":{ms:864e5,refreshMs:6e4,useRealtime:!1},"1w":{ms:6048e5,refreshMs:6e4,useRealtime:!1},"1M":{ms:2592e6,refreshMs:6e4,useRealtime:!1}},l="span_panel",c="span-panel-card",u=`custom:${c}`,d="span-panel",h=`custom:${d}`,p=`ll-strategy-section-${d}`,f="bess",g="evse",m="pv",v="sub_",y={power:{entityRole:"power",label:()=>i("metric.power"),unit:t=>Math.abs(t)>=1e3?"kW":"W",format:t=>{const e=Math.abs(t);return e>=1e3?(e/1e3).toFixed(1):e<10&&e>0?e.toFixed(1):String(Math.round(e))}},current:{entityRole:"current",label:()=>i("metric.current"),unit:()=>"A",format:t=>Math.abs(t).toFixed(1)}},_={soc:{entityRole:"soc",label:()=>i("metric.soc"),unit:()=>"%",format:t=>String(Math.round(t)),fixedMin:0,fixedMax:100},soe:{entityRole:"soe",label:()=>i("metric.soe"),unit:()=>"kWh",format:t=>t.toFixed(1)},power:y.power},b={always_on:{icon:"mdi:battery",icon2:"mdi:router-wireless",color:"#4caf50",label:()=>i("shedding.always_on")},never:{icon:"mdi:battery",color:"#4caf50",label:()=>i("shedding.never")},soc_threshold:{icon:"mdi:battery-alert-variant-outline",color:"#9c27b0",label:()=>i("shedding.soc_threshold"),textLabel:"SoC"},off_grid:{icon:"mdi:transmission-tower",color:"#ff9800",label:()=>i("shedding.off_grid")},unknown:{icon:"mdi:help-circle-outline",color:"#888",label:()=>i("shedding.unknown")}},x=Object.keys(b).filter(t=>"unknown"!==t&&"always_on"!==t);var w=function(t,e){return w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},w(t,e)};function S(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}w(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function C(t,e,n,i){var r,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(r=t[s])&&(a=(o<3?r(a):o>3?r(e,n,a):r(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}"function"==typeof SuppressedError&&SuppressedError; /** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ -const k=globalThis,M=k.ShadowRoot&&(void 0===k.ShadyCSS||k.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,T=Symbol(),A=new WeakMap;let I=class{constructor(t,e,n){if(this._$cssResult$=!0,n!==T)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(M&&void 0===t){const n=void 0!==e&&1===e.length;n&&(t=A.get(e)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&A.set(e,t))}return t}toString(){return this.cssText}};const D=t=>new I("string"==typeof t?t:t+"",void 0,T),P=(t,...e)=>{const n=1===t.length?t[0]:e.reduce((e,n,i)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+t[i+1],t[0]);return new I(n,t,T)},L=M?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const n of t.cssRules)e+=n.cssText;return D(e)})(t):t,{is:E,defineProperty:N,getOwnPropertyDescriptor:R,getOwnPropertyNames:O,getOwnPropertySymbols:z,getPrototypeOf:H}=Object,B=globalThis,$=B.trustedTypes,F=$?$.emptyScript:"",V=B.reactiveElementPolyfillSupport,W=(t,e)=>t,j={toAttribute(t,e){switch(e){case Boolean:t=t?F:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let n=t;switch(e){case Boolean:n=null!==t;break;case Number:n=null===t?null:Number(t);break;case Object:case Array:try{n=JSON.parse(t)}catch(t){n=null}}return n}},q=(t,e)=>!E(t,e),U={attribute:!0,type:String,converter:j,reflect:!1,useDefault:!1,hasChanged:q}; +const k=globalThis,M=k.ShadowRoot&&(void 0===k.ShadyCSS||k.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,T=Symbol(),A=new WeakMap;let I=class{constructor(t,e,n){if(this._$cssResult$=!0,n!==T)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(M&&void 0===t){const n=void 0!==e&&1===e.length;n&&(t=A.get(e)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&A.set(e,t))}return t}toString(){return this.cssText}};const D=t=>new I("string"==typeof t?t:t+"",void 0,T),P=(t,...e)=>{const n=1===t.length?t[0]:e.reduce((e,n,i)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+t[i+1],t[0]);return new I(n,t,T)},L=M?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const n of t.cssRules)e+=n.cssText;return D(e)})(t):t,{is:E,defineProperty:N,getOwnPropertyDescriptor:R,getOwnPropertyNames:O,getOwnPropertySymbols:z,getPrototypeOf:H}=Object,B=globalThis,F=B.trustedTypes,$=F?F.emptyScript:"",V=B.reactiveElementPolyfillSupport,W=(t,e)=>t,j={toAttribute(t,e){switch(e){case Boolean:t=t?$:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let n=t;switch(e){case Boolean:n=null!==t;break;case Number:n=null===t?null:Number(t);break;case Object:case Array:try{n=JSON.parse(t)}catch(t){n=null}}return n}},q=(t,e)=>!E(t,e),U={attribute:!0,type:String,converter:j,reflect:!1,useDefault:!1,hasChanged:q}; /** * @license * Copyright 2017 Google LLC @@ -36,7 +36,7 @@ const Ot={attribute:!0,type:String,converter:j,reflect:!1,hasChanged:q},zt=(t=Ot * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */function Bt(t){return Ht({...t,state:!0,attribute:!1})}const $t={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ft(t){return String(t).replace(/[&<>"']/g,t=>$t[t]??t)}const Vt="span_panel_list_columns";function Wt(){try{const t=localStorage.getItem(Vt);if(!t)return 1;const e=parseInt(t,10);return 1===e||2===e||3===e?e:1}catch{return 1}}function jt(t){try{localStorage.setItem(Vt,String(t))}catch{}}function qt(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}const Ut=y.power,Gt=y.current,Xt="--",Yt=`${Xt}`;function Zt(t){return Ut.unit(t)}function Kt(t){return(t<0?"-":"")+Ut.format(t)}function Qt(t){return null===t?Yt:`${Kt(t)} ${Zt(t)}`}function Jt(t){return null===t?Yt:`${Kt(t)}${Zt(t)}`}function te(t){return null===t?Yt:`${Gt.format(t)}A`}function ee(t){return t instanceof Error||"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message?t.message:String(t)}const ne=new Set(["Unauthorized","UnknownUser"]);function ie(t){if("object"!=typeof t||null===t)return!1;const e="code"in t?t.code:void 0;return"unauthorized"===e||"home_assistant_error"===e&&"message"in t&&ne.has(t.message)}const re="Validation error: ",oe={translation_domain:t=>"translation_domain"in t?t.translation_domain:void 0,translation_key:t=>"translation_key"in t?t.translation_key:void 0,translation_placeholders:t=>"translation_placeholders"in t?t.translation_placeholders:void 0};function ae(t,e){return"object"==typeof t&&null!==t?oe[e](t):void 0}async function se(t,e,n,i){const r=ae(e,"translation_key");if(t&&"string"==typeof r&&ae(e,"translation_domain")===n){const i=`component.${n}.exceptions.${r}.message`;try{const r=t.loadBackendTranslation?await t.loadBackendTranslation("exceptions",n):t.localize,o=r?.(i,function(t){const e=ae(t,"translation_placeholders");if("object"!=typeof e||null===e)return{};const n={};for(const[t,i]of Object.entries(e))"string"!=typeof i&&"number"!=typeof i||(n[t]=i);return n}(e));if(o)return o}catch{}}const o=ee(e),a=o.startsWith(re)?o.slice(18):o;return a&&"[object Object]"!==a?a:i}const le=["relay_state","relay_state_target","priority","priority_target"];function ce(t){return"_favoriteRefs"in t}const ue=Object.freeze({mayOperate:!0,reason:null}),de=Object.freeze({mayOperate:!1,reason:null}),he=["control_disabled","admin_only","read_only"];function pe(t){const e=t?.control_access;return"object"==typeof e&&null!==e&&"may_operate"in e&&"boolean"==typeof e.may_operate?e.may_operate?ue:{mayOperate:!1,reason:"reason"in e&&(n=e.reason,he.some(t=>t===n))?e.reason:null}:ue;var n}function fe(t){return"circuit"===t?.kind}function ge(t,e){if(!t||!ce(t))return pe(t);const n=t._favoriteRefs[e];return fe(n)?n.controlAccess:de}function me(t){return!!t?.entities?.switch&&!1!==t.is_user_controllable}function ve(t,e){const n=new Map;for(const[i,r]of Object.entries(t._favoriteRefs))fe(r)&&e(t.circuits[i])&&n.set(r.panelDeviceId,r.controlAccess);return n}const ye={control_disabled:()=>i("controls.disabled"),admin_only:()=>i("controls.admin_only"),read_only:()=>i("controls.read_only")};function _e(t){return t.mayOperate?"":t.reason?ye[t.reason]():i("controls.not_operable")}class be extends Error{constructor(t){super(t),this.name="ControlChangeRefused"}}function xe(t,e){return{setRelay:(n,i)=>we(t,e,"switch",i?"turn_on":"turn_off",n,{}),setPriority:(n,i)=>we(t,e,"select","select_option",n,{option:i})}}async function we(t,e,n,r,o,a){if(!e.mayOperate)throw new be(_e(e));try{await t.callWS({type:"call_service",domain:n,service:r,service_data:a,target:{entity_id:o}})}catch(t){throw ie(t)?new be(i("controls.entity_unauthorized")):t}}const Se={relay:{key:"service:relay",fallback:()=>i("error.relay_failed")},priority:{key:"service:shedding",fallback:()=>i("error.shedding_failed")}};function Ce(t,e,n,i){console.warn(`SPAN Panel: ${i} change failed`,n);const{key:r,fallback:o}=Se[i];se(t,n,l,o()).then(t=>{e?.add({key:r,level:"error",message:t,persistent:!1})})}function ke(t,e){const n=_e(e);n?t.title=n:t.removeAttribute("title")}function Me(t){const e=_e(t);return e?`

${Ft(e)}

`:""}function Te(t,e,n={}){const r=Ft(t.device_name||i("header.default_name")),o=Ft(t.serial||""),a=Ft(t.firmware||""),s="current"===(e.chart_metric||"power"),l=!1!==n.showSwitches;return`\n
\n
\n
\n

${r}

\n ${o}\n \n ${l?function(t,e={}){const n=!t.mayOperate;return`
\n ${Ft(i("header.enable_switches"))}\n
\n \n
\n
${!1===e.note?"":Me(t)}`}(function(t){if(!t||!ce(t))return pe(t);const e=[...ve(t,me).values()],[n]=e;return!n||e.some(t=>t.mayOperate)?ue:n}(t)):""}\n
\n ${function(t,e){const n="current"===(e.chart_metric||"power"),r=!!t.panel_entities?.site_power,o=!!t.panel_entities?.dsm_state,a=!!t.panel_entities?.current_power,s=!!t.panel_entities?.feedthrough_power,l=!!t.panel_entities?.pv_power,c=!!t.panel_entities?.battery_level;return`\n
\n ${r?`\n
\n ${i("header.site")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${o?`\n
\n ${i("header.grid")}\n
\n ${Xt}\n
\n
`:""}\n ${a?`\n
\n ${i("header.upstream")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${s?`\n
\n ${i("header.downstream")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${l?`\n
\n ${i("header.solar")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${c?`\n
\n ${i("header.battery")}\n
\n ${Xt}\n %\n
\n
`:""}\n
\n `}(t,e)}\n
\n
\n
\n ${a}\n
\n \n \n
\n
\n
\n ${Object.entries(b).filter(([t])=>"unknown"!==t).map(([,t])=>{const e=Ft(t.icon),n=Ft(t.color),i=Ft(t.label());let r;return r=t.icon2?``:t.textLabel?`${Ft(t.textLabel)}`:``,`
${r}${i}
`}).join("")}\n
\n
\n
\n `}function Ae(t){return"number"==typeof t&&Number.isInteger(t)&&t>0}function Ie(t){return!0===t.outside_panel}function De(t,e){if(!t)return null;let n=null,i=null;const{first_position:r,last_position:o}=t;Ae(r)&&Ae(o)&&r<=o?(n=r,i=o):Ae(e)&&(n=1,i=e);for(const e of Object.values(t.circuits))if(e&&!Ie(e))for(const t of e.tabs??[])Ae(t)&&(n=null===n?t:Math.min(n,t),i=null===i?t:Math.max(i,t));return null===n||null===i?null:{first:n,last:i}}function Pe(t){return Le(t.last)-Le(t.first)+1}function Le(t){return Math.ceil(t/2)}function Ee(t){return t%2==0?1:0}function Ne(t){if(2!==t.length)return null;const[e,n]=[Math.min(...t),Math.max(...t)];return Le(e)===Le(n)?"row-span":Ee(e)===Ee(n)?"col-span":"row-span"}function Re(t){const e=t.chart_metric??o;return y[e]??y[o]}function Oe(t,e){const n=function(t){return Re(t).entityRole}(e);return t.entities?.[n]??t.entities?.power??null}function ze(t){return t.members.map((e,n)=>({uuid:t.memberIds[n],circuit:e}))}function He(t){return new Map(t.flatMap(t=>t.memberIds.map(e=>[e,t])))}function Be(t,e){if(!e)return t;const{breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}=e.circuit;return{...t,breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}}function $e(t){const e=t.circuits,n=new Map;for(const[t,i]of Object.entries(e)){const e=i.shared_meter_group;e&&n.set(e,[...n.get(e)??[],[t,i]])}const i=[];for(const[r,o]of Object.entries(e)){const e=o.shared_meter_group,a=e?n.get(e):void 0;if(e&&a){if(a[0][0]===r){const[n,r]=a.find(([t])=>t===e)??a[0],o=a.map(([,t])=>t),s=t.shared_meter_groups?.[e];i.push({uuid:n,circuit:{...r,tabs:Fe(o),breaker_rating_a:s?s.breaker_rating_a:We(o),monitoring_rating_a:s?.monitoring_rating_a,monitoring_rating_user_set:!0===s?.monitoring_rating_user_set},members:o,memberIds:a.map(([t])=>t)})}}else i.push({uuid:r,circuit:o,members:[o],memberIds:[r]})}return i}function Fe(t){return[...new Set(t.flatMap(t=>t.tabs))].sort((t,e)=>t-e)}function Ve(t){const e=function(t){return t.some(t=>!t.breaker_rating_a)?"":t.map(t=>Math.round(t.breaker_rating_a)).join("·")}(t);return e?1===t.length?`${e}A`:`${e} A`:""}function We(t){let e=0;for(const n of t){if(!n.breaker_rating_a)return null;e+=n.breaker_rating_a}return e}function je(t){if(1===t.length){const e=t[0].breaker_rating_a;return e?`${e}A`:""}return Ve(t)}function qe(t){return new Promise(e=>setTimeout(e,t))}class Ue{constructor(t){this._store=t}async callWS(t,e,n){const i=n?.retries??3,r=n?.errorId??`ws:${String(e.type??"unknown")}`;return this._withRetry(()=>t.callWS(e),i,r,n?.errorMessage)}async _withRetry(t,e,n,r){if(this._store.hasAnyPanelOffline())try{const e=await t();return this._store.remove(n),e}catch(t){const e=t instanceof Error?t:new Error(ee(t));throw this._store.add({key:n,level:"error",message:r??i("error.panel_offline"),persistent:!1}),e}let o;for(let i=0;i<=e;i++)try{const e=await t();return this._store.remove(n),e}catch(t){if(o=t instanceof Error?t:new Error(ee(t)),i{try{const n={};e&&(n.config_entry_id=e);const o={type:"call_service",domain:l,service:"get_monitoring_status",service_data:n,return_response:!0},a=this._retry?await this._retry.callWS(t,o,{errorId:"fetch:monitoring",errorMessage:i("error.monitoring_failed")}):await t.callWS(o),s=Ge(a?.response);return r===this._generation&&(this._status=s,this._lastFetch=Date.now()),s}catch(t){return console.warn("SPAN Panel: monitoring status fetch failed",t),r===this._generation&&(this._status=null),this._retry||this._errorStore?.add({key:"fetch:monitoring",level:"warning",message:i("error.monitoring_failed"),persistent:!1}),null}finally{this._inflight?.gen===r&&(this._inflight=null)}})();return this._inflight={gen:r,promise:o},o}invalidate(){this._lastFetch=0,this._generation++}get status(){return this._status}clear(){this._status=null,this._lastFetch=0,this._generation++}}class Ye{constructor(){this._caches=new Map,this._errorStore=null}get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t;for(const e of this._caches.values())e.errorStore=t}async fetchOne(t,e){let n=this._caches.get(e);return n||(n=new Xe,n.errorStore=this._errorStore,this._caches.set(e,n)),n.fetch(t,e)}invalidate(){for(const t of this._caches.values())t.invalidate()}clear(){this._caches.clear()}}function Ze(t,e){return function(t,e){return t?.circuits?t.circuits[e]??null:null}(t,function(t){return t.entities?.current??t.entities?.power??""}(e))}function Ke(t){return{continuousPct:t?.continuous_threshold_pct??80,spikePct:t?.spike_threshold_pct??100}}function Qe(t,e){const{continuousPct:n,spikePct:i}=Ke(e);return t>=i?"alert":t>=n?"warning":"normal"}function Je(t,e){return`utilization-${Qe(t,e)}`}function tn(t){return(void 0===t.monitoring_rating_a?t.breaker_rating_a:t.monitoring_rating_a)??null}function en(t){return null!=t&&!1!==t.monitoring_enabled}function nn(t,e){return en(e)?tn(t):t.breaker_rating_a??null}const rn=["continuous_threshold_pct","spike_threshold_pct"];function on(t,e){return en(e)?function(t,e){return"averaged_legs"===t?.package_ratings_state&&en(e)}(t,e)?"averaged_legs":function(t,e){return t&&e&&function(t){const e=t.package_ratings_state;return"applies"===e||"pending"===e&&"one_space"===t.package_ratings_form}(t)&&rn.some(t=>(e[t]??0)>100)?!0===e.has_override?"own":"global":null}(t,e):null}function an(t){return t.packageRatings?.length&&t.panelAmps?r("monitoringRating.copied",{package:t.packageRatings.join("-"),panel:String(t.panelAmps)}):i("monitoringRating.copied_unnamed")}function sn(t,e,n,i){const r=[];return n||r.push("circuit-off"),i&&r.push("circuit-producer"),function(t){return!!t&&null!=t.over_threshold_since}(e)&&r.push("circuit-alert"),r.join(" ")}function ln(t,e){return Ie(t)||yn(t,e)}function cn(t,e){const n=t.entities?.power;return qt(n?e.states[n]:void 0)}function un(t,e){const n=t.entities?.current;return qt(n?e.states[n]:void 0)}function dn(t){return t.is_generation??"pv"===t.device_type}function hn(t,e){return dn(t)||null!==e&&e<0}function pn(t,e,n){const i=un(t,e);if(t.entities?.current&&null===i)return null;const r=n?.utilization_pct??null,o=nn(t,n);return null===r&&null!==i&&o?Math.round(Math.abs(i)/o*1e3)/10:r}const fn=new Set(x),gn={NEVER:"never",SOC_THRESHOLD:"soc_threshold",OFF_GRID:"off_grid"};function mn(t,e){const n=t.entities?.switch;return n?e.states[n]?.state:void 0}function vn(t,e,n){const i=t.entities?.power,r=i?e.states[i]?.attributes?.[n]:void 0;return"string"==typeof r&&r?r:void 0}function yn(t,e){const n=mn(t,e);return"on"===n||"off"===n?"on"===n:"CLOSED"===(vn(t,e,"relay_state")??t.relay_state)}function _n(t,e){if(!t.entities?.switch||!1===t.is_user_controllable)return"none";const n=mn(t,e);return void 0===n?"none":"on"===n||"off"===n?"operable":"inert"}function bn(t){return void 0===t?void 0:gn[t]}function xn(t,e){const n=t.entities?.select;return n?e.states[n]?.state:void 0}function wn(t,e){if(t.always_on)return"always_on";if(!t.entities?.select)return"unknown";const n=xn(t,e);return void 0!==n&&fn.has(n)?n:bn(vn(t,e,"shed_priority"))??bn(t.priority)??"unknown"}function Sn(t,e){return _e(t)||(e?i("grid.shared_switch"):"")}function Cn(t,e,n,r=!1){if("none"===e)return"";const o=["toggle-pill",t?"toggle-on":"toggle-off"];"inert"===e&&o.push("toggle-unavailable"),r&&o.push("toggle-shared"),n.mayOperate||o.push("toggle-forbidden");const a=Sn(n,r);return`
\n ${i(t?"grid.on":"grid.off")}\n \n
`}function kn(t,e,n,r){const o=t.querySelector(".toggle-pill");if(!o)return;o.classList.toggle("toggle-on",e),o.classList.toggle("toggle-off",!e),o.classList.toggle("toggle-unavailable","operable"!==n),o.classList.toggle("toggle-forbidden",!r.mayOperate);const a=Sn(r,o.classList.contains("toggle-shared"));a?o.title=a:o.removeAttribute("title");const s=o.querySelector(".toggle-label");s&&(s.textContent=i(e?"grid.on":"grid.off"))}function Mn(t){return"unknown"===t?void 0:b[t]}const Tn="display:none;";function An(t){const e=Mn(t),n=e?Ft(e.color):"",i=e?` title="${Ft(e.label())}"`:"",r=e?Ft(e.icon):"",o=e?.icon2?Ft(e.icon2):"",a=e?.textLabel?Ft(e.textLabel):"";return`\n \n \n ${a}\n `}function In(t,e){const n=t.querySelector(".shedding-composite");if(!n)return;const i=Mn(e);n.style.display=i?"":"none",n.title=i?i.label():"";const r=i?.color??"",o=n.querySelector(".shedding-icon");o&&(o.setAttribute("icon",i?.icon??""),o.style.color=r);const a=n.querySelector(".shedding-icon-secondary");a&&(a.setAttribute("icon",i?.icon2??""),a.style.color=r,a.style.display=i?.icon2?"":"none");const s=n.querySelector(".shedding-label");s&&(s.textContent=i?.textLabel??"",s.style.color=r,s.style.display=i?.textLabel?"":"none")}function Dn(t,e,n,r,o,a,s,l,c,u,d=[e],h=!1){const p=cn(e,a),f=hn(e,p),g=yn(e,a),m=_n(e,a),v=d.length>1,y=Ve(d),_=Ft(d.map(t=>t.name||i("grid.unknown")).join(" · ")),b="current"===Re(s).entityRole?te(un(e,a)):Jt(p),x=An(c||"unknown"),w=``;let S="";const C=pn(e,a,l);null!==C&&(S=`${Math.round(C)}%`);return`\n
\n
\n
\n ${y?`${y}`:""}\n ${S}\n ${_}\n
\n
\n \n ${b}\n \n ${Cn(g,m,u,v&&function(t){const e=t[0]?.shared_relay_group;return!!e&&t.every(t=>t.shared_relay_group===e)}(d))}\n
\n
\n
\n ${x}\n ${w}\n
\n
\n
\n `}function Pn(t,e){return`\n
\n —\n
\n `}function Ln(t){return"function"==typeof globalThis.CSS?.escape?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}function En(t){return Object.entries(t.circuits).filter(([,t])=>Ie(t))}function Nn(t,e){return!1!==e.show_panel&&En(t).length>0}function Rn(t,e,n){return`${Ft(function(t){const e=qt(t);if(null===e)return Xt;const n=t?.attributes.unit_of_measurement;return"Wh"===n?`${(e/1e3).toFixed(1)} kWh`:"kWh"===n?`${e.toFixed(1)} kWh`:"string"==typeof n&&n?`${e} ${n}`:String(e)}(e?t.states[e]:void 0))} ${Ft(n)}`}function On(t,e,n){const r=cn(t,e),o=null===r||0===r?"":i(r>0?"meters.importing":"meters.exporting");return`\n ${"current"===Re(n).entityRole?te(un(t,e)):Jt(r)}\n ${Ft(o)}\n ${Rn(e,t.entities?.consumed_energy,i("meters.imported"))}\n ${Rn(e,t.entities?.produced_energy,i("meters.exported"))}\n `}const zn={names:["power","battery power"],suffixes:["_power"]},Hn={names:["battery level","battery percentage"],suffixes:["_battery_level","_battery_percentage"]},Bn={names:["state of energy"],suffixes:["_soe_kwh"]};function $n(t,e){if(!t.entities)return null;for(const[n,i]of Object.entries(t.entities)){if("sensor"!==i.domain)continue;const t=(i.original_name??"").toLowerCase();if(e.names.some(e=>t===e))return n;if(i.unique_id&&e.suffixes.some(t=>i.unique_id.endsWith(t)))return n}return null}function Fn(t){return $n(t,Hn)}function Vn(t){return $n(t,Bn)}function Wn(t){const e=t.solar;return e?"inverter"===e.role?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:null}:e.power_entity_id?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:e.site_power_entity_id}:{headlineEid:e.site_power_entity_id,headlineIsSiteTotal:null!==e.site_power_entity_id,siteTotalEid:null}:{headlineEid:(n=t,$n(n,zn)),headlineIsSiteTotal:!1,siteTotalEid:null};var n}function jn(t){const{headlineEid:e,siteTotalEid:n}=Wn(t),i=[e,n];return t.type===f&&i.push(Fn(t),Vn(t)),new Set(i.filter(t=>null!==t))}function qn(t){const e=[{role:"power",entityId:Wn(t).headlineEid}];return t.type===f&&e.push({role:"soc",entityId:Fn(t)},{role:"soe",entityId:Vn(t)}),e.filter(t=>null!==t.entityId)}function Un(t,e){return qt(t.states[e])}function Gn(t){if(!t)return null;let e=null;for(const[n,i]of Object.entries(t)){if("sensor"===i.domain)return n;e||(e=n)}return e}function Xn(t,e){return qn(t).length>0||e&&null!==Gn(t.entities)}function Yn(t,e=()=>""){const n=t=>"site"===t.solar?.role?0:1,i=new Map;for(const n of t){if(n[1].type!==m)continue;const t=e(n[0]),r=i.get(t);r?r.push(n):i.set(t,[n])}for(const t of i.values())t.sort(([,t],[,e])=>n(t)-n(e)||(t.name??"").localeCompare(e.name??""));const r=[],o=new Set;for(const n of t){if(n[1].type!==m){r.push(n);continue}const t=e(n[0]);o.has(t)||(o.add(t),r.push(...i.get(t)??[]))}return r}function Zn(t,e){return void 0!==t.config_entry_id&&e.has(t.config_entry_id)&&!t.via_device_id&&!t.parent_device_id}function Kn(t,e){return void 0!==t.config_entry_id&&t.config_entry_id===e.config_entry_id}function Qn(t){return(t.name_by_user||t.name||"").trim()}function Jn(t){return(t.name??t.original_name??"").trim()}function ti(t,e,n,r){const o=!1!==n.show_battery,a=!1!==n.show_evse,s=!1!==n.show_solar;if(!t.sub_devices)return"";const l=Yn(Object.entries(t.sub_devices).filter(([,t])=>!(t.type===f&&!o)&&(!(t.type===g&&!a)&&!(t.type===m&&!s))),function(t){if(!ce(t))return()=>"";const e=t._favoriteRefs;return t=>e[t]?.panelDeviceId??""}(t));if(0===l.length)return"";const c=[];for(const[t,i]of l){const r=Wn(i),o=i.type===f,a=o?Fn(i):null,s=o?Vn(i):null,l=ri(i,e,n,jn(i)),u=oi(t,i,o,r.headlineEid,a,s),d=i.solar?ni(i.solar,r,e):"";(r.headlineEid||u||l||d)&&c.push({devId:t,sub:i,power:r,chartsHTML:u,entHTML:l,solarHTML:d})}if(0===c.length)return"";const u=c.filter(t=>t.sub.type===g).length;let d=0,h="";for(const{devId:t,sub:n,power:o,chartsHTML:a,entHTML:s,solarHTML:l}of c){const c=ei(n),p=o.headlineIsSiteTotal?`${Ft(i("subdevice.site_total"))}`:"",m=o.headlineEid?`${p}${Qt(Un(e,o.headlineEid))}`:"",v=Xn(n,r.showFavorites)?``:"",y=n.type===f,_=n.type===g;let b="";y?b="sub-device-bess":_&&(d++,d===u&&u%2==1&&(b="sub-device-full")),h+=`\n
\n
\n ${Ft(c)}\n ${Ft(n.name||"")}\n ${m}\n ${v}\n
\n ${a}\n ${l}\n ${s}\n
\n `}return h}function ei(t){return t.type===m?"inverter"===t.solar?.role?i("subdevice.solar_inverter"):i("subdevice.solar"):t.type===g?i("subdevice.ev_charger"):t.type===f?i("subdevice.battery"):i("subdevice.fallback")}function ni(t,e,n){let r="";const o="role"===t.identity?"":[t.vendor,t.model].filter(t=>!!t).join(" · ");if(o&&(r+=`
${Ft(o)}
`),e.siteTotalEid){const t=Un(n,e.siteTotalEid);r+=`\n
\n ${Ft(i("subdevice.site_total"))}:\n ${Qt(t)}\n
`}return"inverter"!==t.role||e.headlineEid||(r+=`
${Ft(i("subdevice.in_site_total"))}
`),r}function ii(t,e){const n=t.entities?.[e],i=n?.name?.trim();if(i)return i;const r=n?.device_id?t.devices?.[n.device_id]:void 0;return r&&Qn(r)||e}function ri(t,e,n,i){const r=n.visible_sub_entities||{};let o="";if(!t.entities)return o;for(const[n,a]of Object.entries(t.entities)){if(i.has(n))continue;if(!0!==r[n])continue;const s=e.states[n];if(!s)continue;let l=a.original_name||ii(e,n);const c=t.name||"";let u;if(l.startsWith(c+" ")&&(l=l.slice(c.length+1)),e.formatEntityState)u=e.formatEntityState(s);else{u=s.state;const t=s.attributes.unit_of_measurement||"";t&&(u+=" "+t)}if("Wh"===(s.attributes.unit_of_measurement||"")){const t=qt(s);null!==t&&(u=(t/1e3).toFixed(1)+" kWh")}o+=`\n
\n ${Ft(l)}:\n ${Ft(u)}\n
\n `}return o}function oi(t,e,n,r,o,a){if(n){const e=[{key:`${v}${t}_soc`,title:i("subdevice.soc"),available:!!o},{key:`${v}${t}_soe`,title:i("subdevice.soe"),available:!!a},{key:`${v}${t}_power`,title:i("subdevice.power"),available:!!r}].filter(t=>t.available);return`\n
\n ${e.map(t=>`\n
\n
${Ft(t.title)}
\n
\n
\n `).join("")}\n
\n `}return r?`
`:""}function ai(t){const e=void 0!==t.history_days||void 0!==t.history_hours||void 0!==t.history_minutes,n=60*(60*(24*(e&&parseInt(String(t.history_days))||0)+(e&&parseInt(String(t.history_hours))||0))+(e?parseInt(String(t.history_minutes))||0:5))*1e3;return Math.max(n,6e4)}function si(t){const e=s[t];return e?e.ms:s[a].ms}function li(t){const e=t/1e3;return e<=600?Math.ceil(e):Math.min(5e3,Math.ceil(e/5))}function ci(t){return Math.max(500,Math.floor(t/5e3))}function ui(t,e,n,i,r,o){t.has(e)||t.set(e,[]);const a=t.get(e);a.push({time:i,value:n});const s=a.findIndex(t=>t.time>=r);s>0?a.splice(0,s):-1===s&&(a.length=0),a.length>o&&a.splice(0,a.length-o)}function di(t,e,n=500){if(0===t.length)return t;t.sort((t,e)=>t.time-e.time);const i=[t[0]];for(let e=1;e=n&&i.push(t[e]);return i.length>e&&i.splice(0,i.length-e),i}function hi(t,e,n,i){let r=t.get(e);r||(r={entityIds:[],keysByEntity:new Map},t.set(e,r));const o=r.keysByEntity.get(n);o?o.push(i):(r.entityIds.push(n),r.keysByEntity.set(n,[i]))}async function pi(t,e,n,i,r){const o=new Date(Date.now()-i).toISOString(),a=i/36e5>72?"hour":"5minute",s=await t.callWS({type:"recorder/statistics_during_period",start_time:o,statistic_ids:e,period:a,types:["mean"]});for(const[t,e]of Object.entries(s)){const i=n.get(t);if(!i||!e)continue;const o=[];for(const t of e){const e=t.mean;if(null==e||!Number.isFinite(e))continue;const n=t.start;n>0&&o.push({time:n,value:e})}if(0!==o.length)for(const t of i){const e=r.get(t)||[],n=[...o,...e];n.sort((t,e)=>t.time-e.time),r.set(t,n)}}}async function fi(t,e,n,i,r){const o=new Date(Date.now()-i).toISOString(),a=await t.callWS({type:"history/history_during_period",start_time:o,entity_ids:e,minimal_response:!0,significant_changes_only:!0,no_attributes:!0}),s=li(i),l=ci(i);for(const[t,e]of Object.entries(a)){const i=n.get(t);if(!i||!e)continue;const o=[];for(const t of e){const e=parseFloat(t.s);if(!Number.isFinite(e))continue;const n=1e3*(t.lu||t.lc||0);n>0&&o.push({time:n,value:e})}if(0!==o.length)for(const t of i){const e=r.get(t)||[],n=[...o,...e];r.set(t,di(n,s,l))}}}function gi(t){if(!t.sub_devices)return[];const e=[];for(const[n,i]of Object.entries(t.sub_devices))for(const{role:t,entityId:r}of qn(i))e.push({entityId:r,key:`${v}${n}_${t}`,devId:n});return e}async function mi(t,e,n,i,r,o){if(!e||!t)return;const a=new Map;for(const[t,i]of Object.entries(e.circuits)){const e=Oe(i,n);if(!e)continue;let o;o=r&&r.has(t)?si(r.get(t)):ai(n),hi(a,o,e,t)}for(const{entityId:t,key:i,devId:r}of gi(e)){let e;e=o&&o.has(r)?si(o.get(r)):ai(n),hi(a,e,t,i)}const s=[];for(const[e,n]of a){if(0===n.entityIds.length)continue;e>2592e5?s.push(pi(t,n.entityIds,n.keysByEntity,e,i)):s.push(fi(t,n.entityIds,n.keysByEntity,e,i))}await Promise.all(s)}var vi=function(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1},yi=new function(){this.browser=new vi,this.node=!1,this.wxa=!1,this.worker=!1,this.svgSupported=!1,this.touchEventsSupported=!1,this.pointerEventsSupported=!1,this.domSupported=!1,this.transformSupported=!1,this.transform3dSupported=!1,this.hasGlobalWindow="undefined"!=typeof window};"object"==typeof wx&&"function"==typeof wx.getSystemInfoSync?(yi.wxa=!0,yi.touchEventsSupported=!0):"undefined"==typeof document&&"undefined"!=typeof self?yi.worker=!0:!yi.hasGlobalWindow||"Deno"in window||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Node.js")>-1?(yi.node=!0,yi.svgSupported=!0):function(t,e){var n=e.browser,i=t.match(/Firefox\/([\d.]+)/),r=t.match(/MSIE\s([\d.]+)/)||t.match(/Trident\/.+?rv:(([\d.]+))/),o=t.match(/Edge?\/([\d.]+)/),a=/micromessenger/i.test(t);i&&(n.firefox=!0,n.version=i[1]);r&&(n.ie=!0,n.version=r[1]);o&&(n.edge=!0,n.version=o[1],n.newEdge=+o[1].split(".")[0]>18);a&&(n.weChat=!0);e.svgSupported="undefined"!=typeof SVGRect,e.touchEventsSupported="ontouchstart"in window&&!n.ie&&!n.edge,e.pointerEventsSupported="onpointerdown"in window&&(n.edge||n.ie&&+n.version>=11);var s=e.domSupported="undefined"!=typeof document;if(s){var l=document.documentElement.style;e.transform3dSupported=(n.ie&&"transition"in l||n.edge||"WebKitCSSMatrix"in window&&"m11"in new WebKitCSSMatrix||"MozPerspective"in l)&&!("OTransition"in l),e.transformSupported=e.transform3dSupported||n.ie&&+n.version>=9}}(navigator.userAgent,yi);var _i="sans-serif",bi="12px "+_i;var xi,wi,Si=function(t){var e={};if("undefined"==typeof JSON)return e;for(var n=0;n=0)o=r*t.length;else for(var a=0;a>1)%2;a.style.cssText=["position: absolute","visibility: hidden","padding: 0","margin: 0","border-width: 0","user-select: none","width:0","height:0",i[s]+":0",r[l]+":0",i[1-s]+":auto",r[1-l]+":auto",""].join("!important;"),t.appendChild(a),n.push(a)}return e.clearMarkers=function(){Ui(n,function(t){t.parentNode&&t.parentNode.removeChild(t)})},n}(e,o),s=function(t,e,n){for(var i=n?"invTrans":"trans",r=e[i],o=e.srcCoords,a=[],s=[],l=!0,c=0;c<4;c++){var u=t[c].getBoundingClientRect(),d=2*c,h=u.left,p=u.top;a.push(h,p),l=l&&o&&h===o[d]&&p===o[d+1],s.push(t[c].offsetLeft,t[c].offsetTop)}return l&&r?r:(e.srcCoords=a,e[i]=n?qr(s,a):qr(a,s))}(a,o,r);if(s)return s(t,n,i),!0}return!1}function Yr(t){return"CANVAS"===t.nodeName.toUpperCase()}var Zr=/([&<>"'])/g,Kr={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qr(t){return null==t?"":(t+"").replace(Zr,function(t,e){return Kr[e]})}var Jr=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,to=[],eo=yi.browser.firefox&&+yi.browser.version.split(".")[0]<39;function no(t,e,n,i){return n=n||{},i?io(t,e,n):eo&&null!=e.layerX&&e.layerX!==e.offsetX?(n.zrX=e.layerX,n.zrY=e.layerY):null!=e.offsetX?(n.zrX=e.offsetX,n.zrY=e.offsetY):io(t,e,n),n}function io(t,e,n){if(yi.domSupported&&t.getBoundingClientRect){var i=e.clientX,r=e.clientY;if(Yr(t)){var o=t.getBoundingClientRect();return n.zrX=i-o.left,void(n.zrY=r-o.top)}if(Xr(to,t,i,r))return n.zrX=to[0],void(n.zrY=to[1])}n.zrX=n.zrY=0}function ro(t){return t||window.event}function oo(t,e,n){if(null!=(e=ro(e)).zrX)return e;var i=e.type;if(i&&i.indexOf("touch")>=0){var r="touchend"!==i?e.targetTouches[0]:e.changedTouches[0];r&&no(t,r,e,n)}else{no(t,e,e,n);var o=function(t){var e=t.wheelDelta;if(e)return e;var n=t.deltaX,i=t.deltaY;if(null==n||null==i)return e;return 3*(0!==i?Math.abs(i):Math.abs(n))*(i>0?-1:i<0?1:n>0?-1:1)}(e);e.zrDelta=o?o/120:-(e.detail||0)/3}var a=e.button;return null==e.which&&void 0!==a&&Jr.test(e.type)&&(e.which=1&a?1:2&a?3:4&a?2:0),e}function ao(t,e,n,i){t.removeEventListener(e,n,i)}var so=function(t){t.preventDefault(),t.stopPropagation(),t.cancelBubble=!0},lo=function(){function t(){this._track=[]}return t.prototype.recognize=function(t,e,n){return this._doTrack(t,e,n),this._recognize(t)},t.prototype.clear=function(){return this._track.length=0,this},t.prototype._doTrack=function(t,e,n){var i=t.touches;if(i){for(var r={points:[],touches:[],target:e,event:t},o=0,a=i.length;o1&&r&&r.length>1){var a=co(r)/co(o);!isFinite(a)&&(a=1),e.pinchScale=a;var s=[((i=r)[0][0]+i[1][0])/2,(i[0][1]+i[1][1])/2];return e.pinchX=s[0],e.pinchY=s[1],{type:"pinch",target:t[0].target,event:e}}}}};function ho(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function po(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t}function fo(t,e,n){var i=e[0]*n[0]+e[2]*n[1],r=e[1]*n[0]+e[3]*n[1],o=e[0]*n[2]+e[2]*n[3],a=e[1]*n[2]+e[3]*n[3],s=e[0]*n[4]+e[2]*n[5]+e[4],l=e[1]*n[4]+e[3]*n[5]+e[5];return t[0]=i,t[1]=r,t[2]=o,t[3]=a,t[4]=s,t[5]=l,t}function go(t,e,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4]+n[0],t[5]=e[5]+n[1],t}function mo(t,e,n,i){void 0===i&&(i=[0,0]);var r=e[0],o=e[2],a=e[4],s=e[1],l=e[3],c=e[5],u=Math.sin(n),d=Math.cos(n);return t[0]=r*d+s*u,t[1]=-r*u+s*d,t[2]=o*d+l*u,t[3]=-o*u+d*l,t[4]=d*(a-i[0])+u*(c-i[1])+i[0],t[5]=d*(c-i[1])-u*(a-i[0])+i[1],t}function vo(t,e){var n=e[0],i=e[2],r=e[4],o=e[1],a=e[3],s=e[5],l=n*a-o*i;return l?(l=1/l,t[0]=a*l,t[1]=-o*l,t[2]=-i*l,t[3]=n*l,t[4]=(i*s-a*r)*l,t[5]=(o*r-n*s)*l,t):null}var yo=function(){function t(t,e){this.x=t||0,this.y=e||0}return t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this},t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.set=function(t,e){return this.x=t,this.y=e,this},t.prototype.equal=function(t){return t.x===this.x&&t.y===this.y},t.prototype.add=function(t){return this.x+=t.x,this.y+=t.y,this},t.prototype.scale=function(t){this.x*=t,this.y*=t},t.prototype.scaleAndAdd=function(t,e){this.x+=t.x*e,this.y+=t.y*e},t.prototype.sub=function(t){return this.x-=t.x,this.y-=t.y,this},t.prototype.dot=function(t){return this.x*t.x+this.y*t.y},t.prototype.len=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.prototype.lenSquare=function(){return this.x*this.x+this.y*this.y},t.prototype.normalize=function(){var t=this.len();return this.x/=t,this.y/=t,this},t.prototype.distance=function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)},t.prototype.distanceSquare=function(t){var e=this.x-t.x,n=this.y-t.y;return e*e+n*n},t.prototype.negate=function(){return this.x=-this.x,this.y=-this.y,this},t.prototype.transform=function(t){if(t){var e=this.x,n=this.y;return this.x=t[0]*e+t[2]*n+t[4],this.y=t[1]*e+t[3]*n+t[5],this}},t.prototype.toArray=function(t){return t[0]=this.x,t[1]=this.y,t},t.prototype.fromArray=function(t){this.x=t[0],this.y=t[1]},t.set=function(t,e,n){t.x=e,t.y=n},t.copy=function(t,e){t.x=e.x,t.y=e.y},t.len=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)},t.lenSquare=function(t){return t.x*t.x+t.y*t.y},t.dot=function(t,e){return t.x*e.x+t.y*e.y},t.add=function(t,e,n){t.x=e.x+n.x,t.y=e.y+n.y},t.sub=function(t,e,n){t.x=e.x-n.x,t.y=e.y-n.y},t.scale=function(t,e,n){t.x=e.x*n,t.y=e.y*n},t.scaleAndAdd=function(t,e,n,i){t.x=e.x+n.x*i,t.y=e.y+n.y*i},t.lerp=function(t,e,n,i){var r=1-i;t.x=r*e.x+i*n.x,t.y=r*e.y+i*n.y},t}(),_o=Math.min,bo=Math.max,xo=Math.abs,wo=["x","y"],So=["width","height"],Co=new yo,ko=new yo,Mo=new yo,To=new yo,Ao=Oo(),Io=Ao.minTv,Do=Ao.maxTv,Po=[0,0],Lo=function(){function t(e,n,i,r){t.set(this,e,n,i,r)}return t.set=function(t,e,n,i,r){return i<0&&(e+=i,i=-i),r<0&&(n+=r,r=-r),t.x=e,t.y=n,t.width=i,t.height=r,t},t.prototype.union=function(t){var e=_o(t.x,this.x),n=_o(t.y,this.y);isFinite(this.x)&&isFinite(this.width)?this.width=bo(t.x+t.width,this.x+this.width)-e:this.width=t.width,isFinite(this.y)&&isFinite(this.height)?this.height=bo(t.y+t.height,this.y+this.height)-n:this.height=t.height,this.x=e,this.y=n},t.prototype.applyTransform=function(e){t.applyTransform(this,this,e)},t.prototype.calculateTransform=function(t){var e=this,n=t.width/e.width,i=t.height/e.height,r=[1,0,0,1,0,0];return go(r,r,[-e.x,-e.y]),function(t,e,n){var i=n[0],r=n[1];t[0]=e[0]*i,t[1]=e[1]*r,t[2]=e[2]*i,t[3]=e[3]*r,t[4]=e[4]*i,t[5]=e[5]*r}(r,r,[n,i]),go(r,r,[t.x,t.y]),r},t.prototype.intersect=function(e,n,i){return t.intersect(this,e,n,i)},t.intersect=function(e,n,i,r){i&&yo.set(i,0,0);var o=r&&r.outIntersectRect||null,a=r&&r.clamp;if(o&&(o.x=o.y=o.width=o.height=NaN),!e||!n)return!1;e instanceof t||(e=t.set(Eo,e.x,e.y,e.width,e.height)),n instanceof t||(n=t.set(No,n.x,n.y,n.width,n.height));var s=!!i;Ao.reset(r,s);var l=Ao.touchThreshold,c=e.x+l,u=e.x+e.width-l,d=e.y+l,h=e.y+e.height-l,p=n.x+l,f=n.x+n.width-l,g=n.y+l,m=n.y+n.height-l;if(c>u||d>h||p>f||g>m)return!1;var v=!(u=t.x&&e<=t.x+t.width&&n>=t.y&&n<=t.y+t.height},t.prototype.contain=function(e,n){return t.contain(this,e,n)},t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(e){t.copy(this,e)},t.prototype.plain=function(){return{x:this.x,y:this.y,width:this.width,height:this.height}},t.prototype.isFinite=function(){return isFinite(this.x)&&isFinite(this.y)&&isFinite(this.width)&&isFinite(this.height)},t.prototype.isZero=function(){return 0===this.width||0===this.height},t.create=function(e){return new t(e.x,e.y,e.width,e.height)},t.copy=function(t,e){return t.x=e.x,t.y=e.y,t.width=e.width,t.height=e.height,t},t.applyTransform=function(e,n,i){if(i){if(i[1]<1e-5&&i[1]>-1e-5&&i[2]<1e-5&&i[2]>-1e-5){var r=i[0],o=i[3],a=i[4],s=i[5];return e.x=n.x*r+a,e.y=n.y*o+s,e.width=n.width*r,e.height=n.height*o,e.width<0&&(e.x+=e.width,e.width=-e.width),void(e.height<0&&(e.y+=e.height,e.height=-e.height))}Co.x=Mo.x=n.x,Co.y=To.y=n.y,ko.x=To.x=n.x+n.width,ko.y=Mo.y=n.y+n.height,Co.transform(i),To.transform(i),ko.transform(i),Mo.transform(i),e.x=_o(Co.x,ko.x,Mo.x,To.x),e.y=_o(Co.y,ko.y,Mo.y,To.y);var l=bo(Co.x,ko.x,Mo.x,To.x),c=bo(Co.y,ko.y,Mo.y,To.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),Eo=new Lo(0,0,0,0),No=new Lo(0,0,0,0);function Ro(t,e,n,i,r,o,a,s){var l=xo(e-n),c=xo(i-t),u=_o(l,c),d=wo[r],h=wo[1-r],p=So[r];e=c||!Ao.bidirectional)&&(Io[d]=-c,Io[h]=0,Ao.useDir&&Ao.calcDirMTV())))}function Oo(){var t=0,e=new yo,n=new yo,i={minTv:new yo,maxTv:new yo,useDir:!1,dirMinTv:new yo,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(r,o){i.touchThreshold=0,r&&null!=r.touchThreshold&&(i.touchThreshold=bo(0,r.touchThreshold)),i.negativeSize=!1,o&&(i.minTv.set(1/0,1/0),i.maxTv.set(0,0),i.useDir=!1,r&&null!=r.direction&&(i.useDir=!0,i.dirMinTv.copy(i.minTv),n.copy(i.minTv),t=r.direction,i.bidirectional=null==r.bidirectional||!!r.bidirectional,i.bidirectional||e.set(Math.cos(t),Math.sin(t))))},calcDirMTV:function(){var o=i.minTv,a=i.dirMinTv,s=o.y*o.y+o.x*o.x,l=Math.sin(t),c=Math.cos(t),u=l*o.y+c*o.x;r(u)?r(o.x)&&r(o.y)&&a.set(0,0):(n.x=s*c/u,n.y=s*l/u,r(n.x)&&r(n.y)?a.set(0,0):(i.bidirectional||e.dot(n)>0)&&n.len()=0;c--){var u=i[c];u===n||u.ignore||u.ignoreCoarsePointer||u.parent&&u.parent.ignoreCoarsePointer||(Vo.copy(u.getBoundingRect()),u.transform&&Vo.applyTransform(u.transform),Vo.intersect(l)&&o.push(u))}if(o.length)for(var d=Math.PI/12,h=2*Math.PI,p=0;p=0;o--){var a=t[o],s=void 0;if(a!==r&&!a.ignore&&(s=jo(a,n,i))&&(!e.topTarget&&(e.topTarget=a),s!==zo)){e.target=a;break}}}function Uo(t,e,n){var i=t.painter;return e<0||e>i.getWidth()||n<0||n>i.getHeight()}Ui(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){Wo.prototype[t]=function(e){var n,i,r=e.zrX,o=e.zrY,a=Uo(this,r,o);if("mouseup"===t&&a||(i=(n=this.findHover(r,o)).target),"mousedown"===t)this._downEl=i,this._downPoint=[e.zrX,e.zrY],this._upEl=i;else if("mouseup"===t)this._upEl=i;else if("click"===t){if(this._downEl!==this._upEl||!this._downPoint||Rr(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function Go(t,e,n,i){var r=e+1;if(r===n)return 1;if(i(t[r++],t[e])<0){for(;r=0;)r++;return r-e}function Xo(t,e,n,i,r){for(i===e&&i++;i>>1])<0?l=o:s=o+1;var c=i-s;switch(c){case 3:t[s+3]=t[s+2];case 2:t[s+2]=t[s+1];case 1:t[s+1]=t[s];break;default:for(;c>0;)t[s+c]=t[s+c-1],c--}t[s]=a}}function Yo(t,e,n,i,r,o){var a=0,s=0,l=1;if(o(t,e[n+r])>0){for(s=i-r;l0;)a=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),a+=r,l+=r}else{for(s=r+1;ls&&(l=s);var c=a;a=r-l,l=r-c}for(a++;a>>1);o(t,e[n+u])>0?a=u+1:l=u}return l}function Zo(t,e,n,i,r,o){var a=0,s=0,l=1;if(o(t,e[n+r])<0){for(s=r+1;ls&&(l=s);var c=a;a=r-l,l=r-c}else{for(s=i-r;l=0;)a=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),a+=r,l+=r}for(a++;a>>1);o(t,e[n+u])<0?l=u:a=u+1}return l}function Ko(t,e){var n,i,r=7,o=0,a=[];function s(s){var l=n[s],c=i[s],u=n[s+1],d=i[s+1];i[s]=c+d,s===o-3&&(n[s+1]=n[s+2],i[s+1]=i[s+2]),o--;var h=Zo(t[u],t,l,c,0,e);l+=h,0!==(c-=h)&&0!==(d=Yo(t[l+c-1],t,u,d,d-1,e))&&(c<=d?function(n,i,o,s){var l=0;for(l=0;l=7||p>=7);if(f)break;g<0&&(g=0),g+=2}if((r=g)<1&&(r=1),1===i){for(l=0;l=0;l--)t[p+l]=t[h+l];return void(t[d]=a[u])}var f=r;for(;;){var g=0,m=0,v=!1;do{if(e(a[u],t[c])<0){if(t[d--]=t[c--],g++,m=0,0===--i){v=!0;break}}else if(t[d--]=a[u--],m++,g=0,1===--s){v=!0;break}}while((g|m)=0;l--)t[p+l]=t[h+l];if(0===i){v=!0;break}}if(t[d--]=a[u--],1===--s){v=!0;break}if(0!==(m=s-Yo(t[c],a,0,s,s-1,e))){for(s-=m,p=(d-=m)+1,h=(u-=m)+1,l=0;l=7||m>=7);if(v)break;f<0&&(f=0),f+=2}(r=f)<1&&(r=1);if(1===s){for(p=(d-=i)+1,h=(c-=i)+1,l=i-1;l>=0;l--)t[p+l]=t[h+l];t[d]=a[u]}else{if(0===s)throw new Error;for(h=d-(s-1),l=0;l1;){var t=o-2;if(t>=1&&i[t-1]<=i[t]+i[t+1]||t>=2&&i[t-2]<=i[t]+i[t-1])i[t-1]i[t+1])break;s(t)}},forceMergeRuns:function(){for(;o>1;){var t=o-2;t>0&&i[t-1]=32;)e|=1&t,t>>=1;return t+e}(r);do{if((o=Go(t,n,i,e))s&&(l=s),Xo(t,n,n+l,n+o,e),o=l}a.pushRun(n,o),a.mergeRuns(),r-=o,n+=o}while(0!==r);a.forceMergeRuns()}}}var Jo=!1;function ta(){Jo||(Jo=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function ea(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var na,ia=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=ea}return t.prototype.traverse=function(t,e){for(var n=0;n=0&&this._roots.splice(i,1)}},t.prototype.delAllRoots=function(){this._roots=[],this._displayList=[],this._displayListLen=0},t.prototype.getRoots=function(){return this._roots},t.prototype.dispose=function(){this._displayList=null,this._roots=null},t}();na=yi.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(t){return setTimeout(t,16)};var ra={linear:function(t){return t},quadraticIn:function(t){return t*t},quadraticOut:function(t){return t*(2-t)},quadraticInOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)},cubicIn:function(t){return t*t*t},cubicOut:function(t){return--t*t*t+1},cubicInOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},quarticIn:function(t){return t*t*t*t},quarticOut:function(t){return 1- --t*t*t*t},quarticInOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)},quinticIn:function(t){return t*t*t*t*t},quinticOut:function(t){return--t*t*t*t*t+1},quinticInOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},sinusoidalIn:function(t){return 1-Math.cos(t*Math.PI/2)},sinusoidalOut:function(t){return Math.sin(t*Math.PI/2)},sinusoidalInOut:function(t){return.5*(1-Math.cos(Math.PI*t))},exponentialIn:function(t){return 0===t?0:Math.pow(1024,t-1)},exponentialOut:function(t){return 1===t?1:1-Math.pow(2,-10*t)},exponentialInOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))},circularIn:function(t){return 1-Math.sqrt(1-t*t)},circularOut:function(t){return Math.sqrt(1- --t*t)},circularInOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},elasticIn:function(t){var e,n=.1;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=.4*Math.asin(1/n)/(2*Math.PI),-n*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},elasticOut:function(t){var e,n=.1;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=.4*Math.asin(1/n)/(2*Math.PI),n*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},elasticInOut:function(t){var e,n=.1,i=.4;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=i*Math.asin(1/n)/(2*Math.PI),(t*=2)<1?n*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/i)*-.5:n*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/i)*.5+1)},backIn:function(t){var e=1.70158;return t*t*((e+1)*t-e)},backOut:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},backInOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)},bounceIn:function(t){return 1-ra.bounceOut(1-t)},bounceOut:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},bounceInOut:function(t){return t<.5?.5*ra.bounceIn(2*t):.5*ra.bounceOut(2*t-1)+.5}},oa=Math.pow,aa=Math.sqrt,sa=1e-8,la=1e-4,ca=aa(3),ua=1/3,da=Ar(),ha=Ar(),pa=Ar();function fa(t){return t>-1e-8&&tsa||t<-1e-8}function ma(t,e,n,i,r){var o=1-r;return o*o*(o*t+3*r*e)+r*r*(r*i+3*o*n)}function va(t,e,n,i,r){var o=1-r;return 3*(((e-t)*o+2*(n-e)*r)*o+(i-n)*r*r)}function ya(t,e,n,i,r,o){var a=i+3*(e-n)-t,s=3*(n-2*e+t),l=3*(e-t),c=t-r,u=s*s-3*a*l,d=s*l-9*a*c,h=l*l-3*s*c,p=0;if(fa(u)&&fa(d)){if(fa(s))o[0]=0;else(C=-l/s)>=0&&C<=1&&(o[p++]=C)}else{var f=d*d-4*u*h;if(fa(f)){var g=d/u,m=-g/2;(C=-s/a+g)>=0&&C<=1&&(o[p++]=C),m>=0&&m<=1&&(o[p++]=m)}else if(f>0){var v=aa(f),y=u*s+1.5*a*(-d+v),_=u*s+1.5*a*(-d-v);(C=(-s-((y=y<0?-oa(-y,ua):oa(y,ua))+(_=_<0?-oa(-_,ua):oa(_,ua))))/(3*a))>=0&&C<=1&&(o[p++]=C)}else{var b=(2*u*s-3*a*d)/(2*aa(u*u*u)),x=Math.acos(b)/3,w=aa(u),S=Math.cos(x),C=(-s-2*w*S)/(3*a),k=(m=(-s+w*(S+ca*Math.sin(x)))/(3*a),(-s+w*(S-ca*Math.sin(x)))/(3*a));C>=0&&C<=1&&(o[p++]=C),m>=0&&m<=1&&(o[p++]=m),k>=0&&k<=1&&(o[p++]=k)}}return p}function _a(t,e,n,i,r){var o=6*n-12*e+6*t,a=9*e+3*i-3*t-9*n,s=3*e-3*t,l=0;if(fa(a)){if(ga(o))(u=-s/o)>=0&&u<=1&&(r[l++]=u)}else{var c=o*o-4*a*s;if(fa(c))r[0]=-o/(2*a);else if(c>0){var u,d=aa(c),h=(-o-d)/(2*a);(u=(-o+d)/(2*a))>=0&&u<=1&&(r[l++]=u),h>=0&&h<=1&&(r[l++]=h)}}return l}function ba(t,e,n,i,r,o){var a=(e-t)*r+t,s=(n-e)*r+e,l=(i-n)*r+n,c=(s-a)*r+a,u=(l-s)*r+s,d=(u-c)*r+c;o[0]=t,o[1]=a,o[2]=c,o[3]=d,o[4]=d,o[5]=u,o[6]=l,o[7]=i}function xa(t,e,n,i,r,o,a,s,l){for(var c=t,u=e,d=0,h=1/l,p=1;p<=l;p++){var f=p*h,g=ma(t,n,r,a,f),m=ma(e,i,o,s,f),v=g-c,y=m-u;d+=Math.sqrt(v*v+y*y),c=g,u=m}return d}function wa(t,e,n,i){var r=1-i;return r*(r*t+2*i*e)+i*i*n}function Sa(t,e,n,i){return 2*((1-i)*(e-t)+i*(n-e))}function Ca(t,e,n){var i=t+n-2*e;return 0===i?.5:(t-e)/i}function ka(t,e,n,i,r){var o=(e-t)*i+t,a=(n-e)*i+e,s=(a-o)*i+o;r[0]=t,r[1]=o,r[2]=s,r[3]=s,r[4]=a,r[5]=n}function Ma(t,e,n,i,r,o,a){for(var s=t,l=e,c=0,u=1/a,d=1;d<=a;d++){var h=d*u,p=wa(t,n,r,h),f=wa(e,i,o,h),g=p-s,m=f-l;c+=Math.sqrt(g*g+m*m),s=p,l=f}return c}var Ta=/cubic-bezier\(([0-9,\.e ]+)\)/;function Aa(t){var e=t&&Ta.exec(t);if(e){var n=e[1].split(","),i=+mr(n[0]),r=+mr(n[1]),o=+mr(n[2]),a=+mr(n[3]);if(isNaN(i+r+o+a))return;var s=[];return function(t){return t<=0?0:t>=1?1:ya(0,i,o,1,t,s)&&ma(0,r,a,1,s[0])}}}var Ia=function(){function t(t){this._inited=!1,this._startTime=0,this._pausedTime=0,this._paused=!1,this._life=t.life||1e3,this._delay=t.delay||0,this.loop=t.loop||!1,this.onframe=t.onframe||Mr,this.ondestroy=t.ondestroy||Mr,this.onrestart=t.onrestart||Mr,t.easing&&this.setEasing(t.easing)}return t.prototype.step=function(t,e){if(this._inited||(this._startTime=t+this._delay,this._inited=!0),!this._paused){var n=this._life,i=t-this._startTime-this._pausedTime,r=i/n;r<0&&(r=0),r=Math.min(r,1);var o=this.easingFunc,a=o?o(r):r;if(this.onframe(a),1===r){if(!this.loop)return!0;var s=i%n;this._startTime=t-s,this._pausedTime=0,this.onrestart()}return!1}this._pausedTime+=e},t.prototype.pause=function(){this._paused=!0},t.prototype.resume=function(){this._paused=!1},t.prototype.setEasing=function(t){this.easing=t,this.easingFunc=tr(t)?t:ra[t]||Aa(t)},t}(),Da=function(t){this.value=t},Pa=function(){function t(){this._len=0}return t.prototype.insert=function(t){var e=new Da(t);return this.insertEntry(e),e},t.prototype.insertEntry=function(t){this.head?(this.tail.next=t,t.prev=this.tail,t.next=null,this.tail=t):this.head=this.tail=t,this._len++},t.prototype.remove=function(t){var e=t.prev,n=t.next;e?e.next=n:this.head=n,n?n.prev=e:this.tail=e,t.next=t.prev=null,this._len--},t.prototype.len=function(){return this._len},t.prototype.clear=function(){this.head=this.tail=null,this._len=0},t}(),La=function(){function t(t){this._list=new Pa,this._maxSize=10,this._map={},this._maxSize=t}return t.prototype.put=function(t,e){var n=this._list,i=this._map,r=null;if(null==i[t]){var o=n.len(),a=this._lastRemovedEntry;if(o>=this._maxSize&&o>0){var s=n.head;n.remove(s),delete i[s.key],r=s.value,this._lastRemovedEntry=s}a?a.value=e:a=new Da(e),a.key=t,n.insertEntry(a),i[t]=a}return r},t.prototype.get=function(t){var e=this._map[t],n=this._list;if(null!=e)return e!==n.tail&&(n.remove(e),n.insertEntry(e)),e.value},t.prototype.clear=function(){this._list.clear(),this._map={}},t.prototype.len=function(){return this._list.len()},t}(),Ea={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function Na(t){return(t=Math.round(t))<0?0:t>255?255:t}function Ra(t){return t<0?0:t>1?1:t}function Oa(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Na(parseFloat(e)/100*255):Na(parseInt(e,10))}function za(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Ra(parseFloat(e)/100):Ra(parseFloat(e))}function Ha(t,e,n){return n<0?n+=1:n>1&&(n-=1),6*n<1?t+(e-t)*n*6:2*n<1?e:3*n<2?t+(e-t)*(2/3-n)*6:t}function Ba(t,e,n){return t+(e-t)*n}function $a(t,e,n,i,r){return t[0]=e,t[1]=n,t[2]=i,t[3]=r,t}function Fa(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}var Va=new La(20),Wa=null;function ja(t,e){Wa&&Fa(Wa,e),Wa=Va.put(t,Wa||e.slice())}function qa(t,e){if(t){e=e||[];var n=Va.get(t);if(n)return Fa(e,n);var i=(t+="").replace(/ /g,"").toLowerCase();if(i in Ea)return Fa(e,Ea[i]),ja(t,e),e;var r,o=i.length;if("#"===i.charAt(0))return 4===o||5===o?(r=parseInt(i.slice(1,4),16))>=0&&r<=4095?($a(e,(3840&r)>>4|(3840&r)>>8,240&r|(240&r)>>4,15&r|(15&r)<<4,5===o?parseInt(i.slice(4),16)/15:1),ja(t,e),e):void $a(e,0,0,0,1):7===o||9===o?(r=parseInt(i.slice(1,7),16))>=0&&r<=16777215?($a(e,(16711680&r)>>16,(65280&r)>>8,255&r,9===o?parseInt(i.slice(7),16)/255:1),ja(t,e),e):void $a(e,0,0,0,1):void 0;var a=i.indexOf("("),s=i.indexOf(")");if(-1!==a&&s+1===o){var l=i.substr(0,a),c=i.substr(a+1,s-(a+1)).split(","),u=1;switch(l){case"rgba":if(4!==c.length)return 3===c.length?$a(e,+c[0],+c[1],+c[2],1):$a(e,0,0,0,1);u=za(c.pop());case"rgb":return c.length>=3?($a(e,Oa(c[0]),Oa(c[1]),Oa(c[2]),3===c.length?u:za(c[3])),ja(t,e),e):void $a(e,0,0,0,1);case"hsla":return 4!==c.length?void $a(e,0,0,0,1):(c[3]=za(c[3]),Ua(c,e),ja(t,e),e);case"hsl":return 3!==c.length?void $a(e,0,0,0,1):(Ua(c,e),ja(t,e),e);default:return}}$a(e,0,0,0,1)}}function Ua(t,e){var n=(parseFloat(t[0])%360+360)%360/360,i=za(t[1]),r=za(t[2]),o=r<=.5?r*(i+1):r+i-r*i,a=2*r-o;return $a(e=e||[],Na(255*Ha(a,o,n+1/3)),Na(255*Ha(a,o,n)),Na(255*Ha(a,o,n-1/3)),1),4===t.length&&(e[3]=t[3]),e}function Ga(t,e){var n=qa(t);if(n){for(var i=0;i<3;i++)n[i]=n[i]*(1-e)|0,n[i]>255?n[i]=255:n[i]<0&&(n[i]=0);return Ya(n,4===n.length?"rgba":"rgb")}}function Xa(t,e,n,i){var r=qa(t);if(t)return r=function(t){if(t){var e,n,i=t[0]/255,r=t[1]/255,o=t[2]/255,a=Math.min(i,r,o),s=Math.max(i,r,o),l=s-a,c=(s+a)/2;if(0===l)e=0,n=0;else{n=c<.5?l/(s+a):l/(2-s-a);var u=((s-i)/6+l/2)/l,d=((s-r)/6+l/2)/l,h=((s-o)/6+l/2)/l;i===s?e=h-d:r===s?e=1/3+u-h:o===s&&(e=2/3+d-u),e<0&&(e+=1),e>1&&(e-=1)}var p=[360*e,n,c];return null!=t[3]&&p.push(t[3]),p}}(r),null!=n&&(r[1]=za(tr(n)?n(r[1]):n)),null!=i&&(r[2]=za(tr(i)?i(r[2]):i)),Ya(Ua(r),"rgba")}function Ya(t,e){if(t&&t.length){var n=t[0]+","+t[1]+","+t[2];return"rgba"!==e&&"hsva"!==e&&"hsla"!==e||(n+=","+t[3]),e+"("+n+")"}}function Za(t,e){var n=qa(t);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*e:0}var Ka=new La(100);function Qa(t){if(er(t)){var e=Ka.get(t);return e||(e=Ga(t,-.1),Ka.put(t,e)),e}if(lr(t)){var n=Fi({},t);return n.colorStops=Gi(t.colorStops,function(t){return{offset:t.offset,color:Ga(t.color,-.1)}}),n}return t}var Ja=Math.round;function ts(t){var e;if(t&&"transparent"!==t){if("string"==typeof t&&t.indexOf("rgba")>-1){var n=qa(t);n&&(t="rgb("+n[0]+","+n[1]+","+n[2]+")",e=n[3])}}else t="none";return{color:t,opacity:null==e?1:e}}var es=1e-4;function ns(t){return t-1e-4}function is(t){return Ja(1e3*t)/1e3}function rs(t){return Ja(1e4*t)/1e4}var os={left:"start",right:"end",center:"middle",middle:"middle"};function as(t){return t&&!!t.image}function ss(t){return as(t)||function(t){return t&&!!t.svgElement}(t)}function ls(t){return"linear"===t.type}function cs(t){return"radial"===t.type}function us(t){return t&&("linear"===t.type||"radial"===t.type)}function ds(t){return"url(#"+t+")"}function hs(t){var e=t.getGlobalScale(),n=Math.max(e[0],e[1]);return Math.max(Math.ceil(Math.log(n)/Math.log(10)),1)}function ps(t){var e=t.x||0,n=t.y||0,i=(t.rotation||0)*Tr,r=dr(t.scaleX,1),o=dr(t.scaleY,1),a=t.skewX||0,s=t.skewY||0,l=[];return(e||n)&&l.push("translate("+e+"px,"+n+"px)"),i&&l.push("rotate("+i+")"),1===r&&1===o||l.push("scale("+r+","+o+")"),(a||s)&&l.push("skew("+Ja(a*Tr)+"deg, "+Ja(s*Tr)+"deg)"),l.join(" ")}var fs=yi.hasGlobalWindow&&tr(window.btoa)?function(t){return window.btoa(unescape(encodeURIComponent(t)))}:"undefined"!=typeof Buffer?function(t){return Buffer.from(t).toString("base64")}:function(t){return null},gs=Array.prototype.slice;function ms(t,e,n){return(e-t)*n+t}function vs(t,e,n,i){for(var r=e.length,o=0;oi?e:t,o=Math.min(n,i),a=r[o-1]||{color:[0,0,0,0],offset:0},s=o;sa)i.length=a;else for(var s=o;s=1},t.prototype.getAdditiveTrack=function(){return this._additiveTrack},t.prototype.addKeyframe=function(t,e,n){this._needsSort=!0;var i=this.keyframes,r=i.length,o=!1,a=6,s=e;if(qi(e)){var l=function(t){return qi(t&&t[0])?2:1}(e);a=l,(1===l&&!ir(e[0])||2===l&&!ir(e[0][0]))&&(o=!0)}else if(ir(e)&&!cr(e))a=0;else if(er(e))if(isNaN(+e)){var c=qa(e);c&&(s=c,a=3)}else a=0;else if(lr(e)){var u=Fi({},s);u.colorStops=Gi(e.colorStops,function(t){return{offset:t.offset,color:qa(t.color)}}),ls(e)?a=4:cs(e)&&(a=5),s=u}0===r?this.valType=a:a===this.valType&&6!==a||(o=!0),this.discrete=this.discrete||o;var d={time:t,value:s,rawValue:e,percent:0};return n&&(d.easing=n,d.easingFunc=tr(n)?n:ra[n]||Aa(n)),i.push(d),d},t.prototype.prepare=function(t,e){var n=this.keyframes;this._needsSort&&n.sort(function(t,e){return t.time-e.time});for(var i=this.valType,r=n.length,o=n[r-1],a=this.discrete,s=ks(i),l=Cs(i),c=0;c=0&&!(l[n].percent<=e);n--);n=p(n,c-2)}else{for(n=h;ne);n++);n=p(n-1,c-2)}r=l[n+1],i=l[n]}if(i&&r){this._lastFr=n,this._lastFrP=e;var f=r.percent-i.percent,g=0===f?1:p((e-i.percent)/f,1);r.easingFunc&&(g=r.easingFunc(g));var m=o?this._additiveValue:d?Ms:t[u];if(!ks(s)&&!d||m||(m=this._additiveValue=[]),this.discrete)t[u]=g<1?i.rawValue:r.rawValue;else if(ks(s))1===s?vs(m,i[a],r[a],g):function(t,e,n,i){for(var r=e.length,o=r&&e[0].length,a=0;a0&&s.addKeyframe(0,ws(l),i),this._trackKeys.push(a)}s.addKeyframe(t,ws(e[a]),i)}return this._maxTime=Math.max(this._maxTime,t),this},t.prototype.pause=function(){this._clip.pause(),this._paused=!0},t.prototype.resume=function(){this._clip.resume(),this._paused=!1},t.prototype.isPaused=function(){return!!this._paused},t.prototype.duration=function(t){return this._maxTime=t,this._force=!0,this},t.prototype._doneCallback=function(){this._setTracksFinished(),this._clip=null;var t=this._doneCbs;if(t)for(var e=t.length,n=0;n0)){this._started=1;for(var e=this,n=[],i=this._maxTime||0,r=0;r1){var a=o.pop();r.addKeyframe(a.time,t[i]),r.prepare(this._maxTime,r.getAdditiveTrack())}}}},t}();function Is(){return(new Date).getTime()}var Ds,Ps,Ls=function(t){function e(e){var n=t.call(this)||this;return n._running=!1,n._time=0,n._pausedTime=0,n._pauseStart=0,n._paused=!1,e=e||{},n.stage=e.stage||{},n}return S(e,t),e.prototype.addClip=function(t){t.animation&&this.removeClip(t),this._head?(this._tail.next=t,t.prev=this._tail,t.next=null,this._tail=t):this._head=this._tail=t,t.animation=this},e.prototype.addAnimator=function(t){t.animation=this;var e=t.getClip();e&&this.addClip(e)},e.prototype.removeClip=function(t){if(t.animation){var e=t.prev,n=t.next;e?e.next=n:this._head=n,n?n.prev=e:this._tail=e,t.next=t.prev=t.animation=null}},e.prototype.removeAnimator=function(t){var e=t.getClip();e&&this.removeClip(e),t.animation=null},e.prototype.update=function(t){for(var e=Is()-this._pausedTime,n=e-this._time,i=this._head;i;){var r=i.next;i.step(e,n)?(i.ondestroy(),this.removeClip(i),i=r):i=r}this._time=e,t||(this.trigger("frame",n),this.stage.update&&this.stage.update())},e.prototype._startLoop=function(){var t=this;this._running=!0,na(function e(){t._running&&(na(e),!t._paused&&t.update())})},e.prototype.start=function(){this._running||(this._time=Is(),this._pausedTime=0,this._startLoop())},e.prototype.stop=function(){this._running=!1},e.prototype.pause=function(){this._paused||(this._pauseStart=Is(),this._paused=!0)},e.prototype.resume=function(){this._paused&&(this._pausedTime+=Is()-this._pauseStart,this._paused=!1)},e.prototype.clear=function(){for(var t=this._head;t;){var e=t.next;t.prev=t.next=t.animation=null,t=e}this._head=this._tail=null},e.prototype.isFinished=function(){return null==this._head},e.prototype.animate=function(t,e){e=e||{},this.start();var n=new As(t,e.loop);return this.addAnimator(n),n},e}(Vr),Es=yi.domSupported,Ns=(Ps={pointerdown:1,pointerup:1,pointermove:1,pointerout:1},{mouse:Ds=["click","dblclick","mousewheel","wheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],touch:["touchstart","touchend","touchmove"],pointer:Gi(Ds,function(t){var e=t.replace("mouse","pointer");return Ps.hasOwnProperty(e)?e:t})}),Rs=["mousemove","mouseup"],Os=["pointermove","pointerup"],zs=!1;function Hs(t){var e=t.pointerType;return"pen"===e||"touch"===e}function Bs(t){t&&(t.zrByTouch=!0)}function $s(t,e){for(var n=e,i=!1;n&&9!==n.nodeType&&!(i=n.domBelongToZr||n!==e&&n===t.painterRoot);)n=n.parentNode;return i}var Fs=function(t,e){this.stopPropagation=Mr,this.stopImmediatePropagation=Mr,this.preventDefault=Mr,this.type=e.type,this.target=this.currentTarget=t.dom,this.pointerType=e.pointerType,this.clientX=e.clientX,this.clientY=e.clientY},Vs={mousedown:function(t){t=oo(this.dom,t),this.__mayPointerCapture=[t.zrX,t.zrY],this.trigger("mousedown",t)},mousemove:function(t){t=oo(this.dom,t);var e=this.__mayPointerCapture;!e||t.zrX===e[0]&&t.zrY===e[1]||this.__togglePointerCapture(!0),this.trigger("mousemove",t)},mouseup:function(t){t=oo(this.dom,t),this.__togglePointerCapture(!1),this.trigger("mouseup",t)},mouseout:function(t){$s(this,(t=oo(this.dom,t)).toElement||t.relatedTarget)||(this.__pointerCapturing&&(t.zrEventControl="no_globalout"),this.trigger("mouseout",t))},wheel:function(t){zs=!0,t=oo(this.dom,t),this.trigger("mousewheel",t)},mousewheel:function(t){zs||(t=oo(this.dom,t),this.trigger("mousewheel",t))},touchstart:function(t){Bs(t=oo(this.dom,t)),this.__lastTouchMoment=new Date,this.handler.processGesture(t,"start"),Vs.mousemove.call(this,t),Vs.mousedown.call(this,t)},touchmove:function(t){Bs(t=oo(this.dom,t)),this.handler.processGesture(t,"change"),Vs.mousemove.call(this,t)},touchend:function(t){Bs(t=oo(this.dom,t)),this.handler.processGesture(t,"end"),Vs.mouseup.call(this,t),+new Date-+this.__lastTouchMoment<300&&Vs.click.call(this,t)},pointerdown:function(t){Vs.mousedown.call(this,t)},pointermove:function(t){Hs(t)||Vs.mousemove.call(this,t)},pointerup:function(t){Vs.mouseup.call(this,t)},pointerout:function(t){Hs(t)||Vs.mouseout.call(this,t)}};Ui(["click","dblclick","contextmenu"],function(t){Vs[t]=function(e){e=oo(this.dom,e),this.trigger(t,e)}});var Ws={pointermove:function(t){Hs(t)||Ws.mousemove.call(this,t)},pointerup:function(t){Ws.mouseup.call(this,t)},mousemove:function(t){this.trigger("mousemove",t)},mouseup:function(t){var e=this.__pointerCapturing;this.__togglePointerCapture(!1),this.trigger("mouseup",t),e&&(t.zrEventControl="only_globalout",this.trigger("mouseout",t))}};function js(t,e){var n=e.domHandlers;yi.pointerEventsSupported?Ui(Ns.pointer,function(i){Us(e,i,function(e){n[i].call(t,e)})}):(yi.touchEventsSupported&&Ui(Ns.touch,function(i){Us(e,i,function(r){n[i].call(t,r),function(t){t.touching=!0,null!=t.touchTimer&&(clearTimeout(t.touchTimer),t.touchTimer=null),t.touchTimer=setTimeout(function(){t.touching=!1,t.touchTimer=null},700)}(e)})}),Ui(Ns.mouse,function(i){Us(e,i,function(r){r=ro(r),e.touching||n[i].call(t,r)})}))}function qs(t,e){function n(n){Us(e,n,function(i){i=ro(i),$s(t,i.target)||(i=function(t,e){return oo(t.dom,new Fs(t,e),!0)}(t,i),e.domHandlers[n].call(t,i))},{capture:!0})}yi.pointerEventsSupported?Ui(Os,n):yi.touchEventsSupported||Ui(Rs,n)}function Us(t,e,n,i){t.mounted[e]=n,t.listenerOpts[e]=i,function(t,e,n,i){t.addEventListener(e,n,i)}(t.domTarget,e,n,i)}function Gs(t){var e=t.mounted;for(var n in e)e.hasOwnProperty(n)&&ao(t.domTarget,n,e[n],t.listenerOpts[n]);t.mounted={}}var Xs=function(t,e){this.mounted={},this.listenerOpts={},this.touching=!1,this.domTarget=t,this.domHandlers=e},Ys=function(t){function e(e,n){var i=t.call(this)||this;return i.__pointerCapturing=!1,i.dom=e,i.painterRoot=n,i._localHandlerScope=new Xs(e,Vs),Es&&(i._globalHandlerScope=new Xs(document,Ws)),js(i,i._localHandlerScope),i}return S(e,t),e.prototype.dispose=function(){Gs(this._localHandlerScope),Es&&Gs(this._globalHandlerScope)},e.prototype.setCursor=function(t){this.dom.style&&(this.dom.style.cursor=t||"default")},e.prototype.__togglePointerCapture=function(t){if(this.__mayPointerCapture=null,Es&&+this.__pointerCapturing^+t){this.__pointerCapturing=t;var e=this._globalHandlerScope;t?qs(this,e):Gs(e)}},e}(Vr),Zs=1;yi.hasGlobalWindow&&(Zs=Math.max(window.devicePixelRatio||window.screen&&window.screen.deviceXDPI/window.screen.logicalXDPI||1,1));var Ks=Zs,Qs="#333",Js="#ccc",tl=ho,el=5e-5;function nl(t){return t>el||t<-5e-5}var il,rl=[],ol=[],al=[1,0,0,1,0,0],sl=Math.abs,ll=function(){function t(){}var e;return t.prototype.getLocalTransform=function(e){return t.getLocalTransform(this,e)},t.prototype.setPosition=function(t){this.x=t[0],this.y=t[1]},t.prototype.setScale=function(t){this.scaleX=t[0],this.scaleY=t[1]},t.prototype.setSkew=function(t){this.skewX=t[0],this.skewY=t[1]},t.prototype.setOrigin=function(t){this.originX=t[0],this.originY=t[1]},t.prototype.needLocalTransform=function(){return nl(this.rotation)||nl(this.x)||nl(this.y)||nl(this.scaleX-1)||nl(this.scaleY-1)||nl(this.skewX)||nl(this.skewY)},t.prototype.updateTransform=function(){var t=this.parent&&this.parent.transform,e=this.needLocalTransform(),n=this.transform;e||t?(n=n||[1,0,0,1,0,0],e?this.getLocalTransform(n):tl(n),t&&(e?fo(n,t,n):po(n,t)),this.transform=n,this._resolveGlobalScaleRatio(n)):n&&(tl(n),this.invTransform=null)},t.prototype._resolveGlobalScaleRatio=function(t){var e=this.globalScaleRatio;if(null!=e&&1!==e){this.getGlobalScale(rl);var n=rl[0]<0?-1:1,i=rl[1]<0?-1:1,r=((rl[0]-n)*e+n)/rl[0]||0,o=((rl[1]-i)*e+i)/rl[1]||0;t[0]*=r,t[1]*=r,t[2]*=o,t[3]*=o}this.invTransform=this.invTransform||[1,0,0,1,0,0],vo(this.invTransform,t)},t.prototype.getComputedTransform=function(){for(var t=this,e=[];t;)e.push(t),t=t.parent;for(;t=e.pop();)t.updateTransform();return this.transform},t.prototype.setLocalTransform=function(t){if(t){var e=t[0]*t[0]+t[1]*t[1],n=t[2]*t[2]+t[3]*t[3],i=Math.atan2(t[1],t[0]),r=Math.PI/2+i-Math.atan2(t[3],t[2]);n=Math.sqrt(n)*Math.cos(r),e=Math.sqrt(e),this.skewX=r,this.skewY=0,this.rotation=-i,this.x=+t[4],this.y=+t[5],this.scaleX=e,this.scaleY=n,this.originX=0,this.originY=0}},t.prototype.decomposeTransform=function(){if(this.transform){var t=this.parent,e=this.transform;t&&t.transform&&(t.invTransform=t.invTransform||[1,0,0,1,0,0],fo(ol,t.invTransform,e),e=ol);var n=this.originX,i=this.originY;(n||i)&&(al[4]=n,al[5]=i,fo(ol,e,al),ol[4]-=n,ol[5]-=i,e=ol),this.setLocalTransform(e)}},t.prototype.getGlobalScale=function(t){var e=this.transform;return t=t||[],e?(t[0]=Math.sqrt(e[0]*e[0]+e[1]*e[1]),t[1]=Math.sqrt(e[2]*e[2]+e[3]*e[3]),e[0]<0&&(t[0]=-t[0]),e[3]<0&&(t[1]=-t[1]),t):(t[0]=1,t[1]=1,t)},t.prototype.transformCoordToLocal=function(t,e){var n=[t,e],i=this.invTransform;return i&&zr(n,n,i),n},t.prototype.transformCoordToGlobal=function(t,e){var n=[t,e],i=this.transform;return i&&zr(n,n,i),n},t.prototype.getLineScale=function(){var t=this.transform;return t&&sl(t[0]-1)>1e-10&&sl(t[3]-1)>1e-10?Math.sqrt(sl(t[0]*t[3]-t[2]*t[1])):1},t.prototype.copyTransform=function(t){ul(this,t)},t.getLocalTransform=function(t,e){e=e||[];var n=t.originX||0,i=t.originY||0,r=t.scaleX,o=t.scaleY,a=t.anchorX,s=t.anchorY,l=t.rotation||0,c=t.x,u=t.y,d=t.skewX?Math.tan(t.skewX):0,h=t.skewY?Math.tan(-t.skewY):0;if(n||i||a||s){var p=n+a,f=i+s;e[4]=-p*r-d*f*o,e[5]=-f*o-h*p*r}else e[4]=e[5]=0;return e[0]=r,e[3]=o,e[1]=h*r,e[2]=d*o,l&&mo(e,e,l),e[4]+=n+c,e[5]+=i+u,e},t.initDefaultProps=((e=t.prototype).scaleX=e.scaleY=e.globalScaleRatio=1,void(e.x=e.y=e.originX=e.originY=e.skewX=e.skewY=e.rotation=e.anchorX=e.anchorY=0)),t}(),cl=["x","y","originX","originY","anchorX","anchorY","rotation","scaleX","scaleY","skewX","skewY"];function ul(t,e){for(var n=0;n=pl)){t=t||bi;for(var e=[],n=+new Date,i=0;i<=127;i++)e[i]=Ci.measureText(String.fromCharCode(i),t).width;var r=+new Date-n;return r>16?hl=pl:r>2&&hl++,e}}(t.font),t.asciiWidthMapTried=!0),0<=e&&e<=127?null!=t.asciiWidthMap?t.asciiWidthMap[e]:t.asciiCharWidth:t.stWideCharWidth}function gl(t,e){var n=t.strWidthCache,i=n.get(e);return null==i&&(i=Ci.measureText(e,t.font).width,n.put(e,i)),i}function ml(t,e,n,i){var r=gl(dl(e),t),o=bl(e),a=yl(0,r,n),s=_l(0,o,i);return new Lo(a,s,r,o)}function vl(t,e,n,i){var r=((t||"")+"").split("\n");if(1===r.length)return ml(r[0],e,n,i);for(var o=new Lo(0,0,0,0),a=0;a=0?parseFloat(t)/100*e:parseFloat(t):t}function wl(t,e,n){var i=e.position||"inside",r=null!=e.distance?e.distance:5,o=n.height,a=n.width,s=o/2,l=n.x,c=n.y,u="left",d="top";if(i instanceof Array)l+=xl(i[0],n.width),c+=xl(i[1],n.height),u=null,d=null;else switch(i){case"left":l-=r,c+=s,u="right",d="middle";break;case"right":l+=r+a,c+=s,d="middle";break;case"top":l+=a/2,c-=r,u="center",d="bottom";break;case"bottom":l+=a/2,c+=o+r,u="center";break;case"inside":l+=a/2,c+=s,u="center",d="middle";break;case"insideLeft":l+=r,c+=s,d="middle";break;case"insideRight":l+=a-r,c+=s,u="right",d="middle";break;case"insideTop":l+=a/2,c+=r,u="center";break;case"insideBottom":l+=a/2,c+=o-r,u="center",d="bottom";break;case"insideTopLeft":l+=r,c+=r;break;case"insideTopRight":l+=a-r,c+=r,u="right";break;case"insideBottomLeft":l+=r,c+=o-r,d="bottom";break;case"insideBottomRight":l+=a-r,c+=o-r,u="right",d="bottom"}return(t=t||{}).x=l,t.y=c,t.align=u,t.verticalAlign=d,t}var Sl="__zr_normal__",Cl=cl.concat(["ignore"]),kl=Xi(cl,function(t,e){return t[e]=!0,t},{ignore:!1}),Ml={},Tl=new Lo(0,0,0,0),Al=[],Il=function(){function t(t){this.id=zi(),this.animators=[],this.currentStates=[],this.states={},this._init(t)}return t.prototype._init=function(t){this.attr(t)},t.prototype.drift=function(t,e,n){switch(this.draggable){case"horizontal":e=0;break;case"vertical":t=0}var i=this.transform;i||(i=this.transform=[1,0,0,1,0,0]),i[4]+=t,i[5]+=e,this.decomposeTransform(),this.markRedraw()},t.prototype.beforeUpdate=function(){},t.prototype.afterUpdate=function(){},t.prototype.update=function(){this.updateTransform(),this.__dirty&&this.updateInnerText()},t.prototype.updateInnerText=function(t){var e=this._textContent;if(e&&(!e.ignore||t)){this.textConfig||(this.textConfig={});var n=this.textConfig,i=n.local,r=e.innerTransformable,o=void 0,a=void 0,s=!1;r.parent=i?this:null;var l=!1;r.copyTransform(e);var c=null!=n.position,u=n.autoOverflowArea,d=void 0;if((u||c)&&(d=Tl,n.layoutRect?d.copy(n.layoutRect):d.copy(this.getBoundingRect()),i||d.applyTransform(this.transform)),c){this.calculateTextPosition?this.calculateTextPosition(Ml,n,d):wl(Ml,n,d),r.x=Ml.x,r.y=Ml.y,o=Ml.align,a=Ml.verticalAlign;var h=n.origin;if(h&&null!=n.rotation){var p=void 0,f=void 0;"center"===h?(p=.5*d.width,f=.5*d.height):(p=xl(h[0],d.width),f=xl(h[1],d.height)),l=!0,r.originX=-r.x+p+(i?0:d.x),r.originY=-r.y+f+(i?0:d.y)}}null!=n.rotation&&(r.rotation=n.rotation);var g=n.offset;g&&(r.x+=g[0],r.y+=g[1],l||(r.originX=-g[0],r.originY=-g[1]));var m=this._innerTextDefaultStyle||(this._innerTextDefaultStyle={});if(u){var v=m.overflowRect=m.overflowRect||new Lo(0,0,0,0);r.getLocalTransform(Al),vo(Al,Al),Lo.copy(v,d),v.applyTransform(Al)}else m.overflowRect=null;var y=void 0,_=void 0,b=void 0;(null==n.inside?"string"==typeof n.position&&n.position.indexOf("inside")>=0:n.inside)&&this.canBeInsideText()?(y=n.insideFill,_=n.insideStroke,null!=y&&"auto"!==y||(y=this.getInsideTextFill()),null!=_&&"auto"!==_||(_=this.getInsideTextStroke(y),b=!0)):(y=n.outsideFill,_=n.outsideStroke,null!=y&&"auto"!==y||(y=this.getOutsideFill()),null!=_&&"auto"!==_||(_=this.getOutsideStroke(y),b=!0)),(y=y||"#000")===m.fill&&_===m.stroke&&b===m.autoStroke&&o===m.align&&a===m.verticalAlign||(s=!0,m.fill=y,m.stroke=_,m.autoStroke=b,m.align=o,m.verticalAlign=a,e.setDefaultTextStyle(m)),e.__dirty|=1,s&&e.dirtyStyle(!0)}},t.prototype.canBeInsideText=function(){return!0},t.prototype.getInsideTextFill=function(){return"#fff"},t.prototype.getInsideTextStroke=function(t){return"#000"},t.prototype.getOutsideFill=function(){return this.__zr&&this.__zr.isDarkMode()?Js:Qs},t.prototype.getOutsideStroke=function(t){var e=this.__zr&&this.__zr.getBackgroundColor(),n="string"==typeof e&&qa(e);n||(n=[255,255,255,1]);for(var i=n[3],r=this.__zr.isDarkMode(),o=0;o<3;o++)n[o]=n[o]*i+(r?0:255)*(1-i);return n[3]=1,Ya(n,"rgba")},t.prototype.traverse=function(t,e){},t.prototype.attrKV=function(t,e){"textConfig"===t?this.setTextConfig(e):"textContent"===t?this.setTextContent(e):"clipPath"===t?this.setClipPath(e):"extra"===t?(this.extra=this.extra||{},Fi(this.extra,e)):this[t]=e},t.prototype.hide=function(){this.ignore=!0,this.markRedraw()},t.prototype.show=function(){this.ignore=!1,this.markRedraw()},t.prototype.attr=function(t,e){if("string"==typeof t)this.attrKV(t,e);else if(rr(t))for(var n=Zi(t),i=0;i0},t.prototype.getState=function(t){return this.states[t]},t.prototype.ensureState=function(t){var e=this.states;return e[t]||(e[t]={}),e[t]},t.prototype.clearStates=function(t){this.useState(Sl,!1,t)},t.prototype.useState=function(t,e,n,i){var r=t===Sl;if(this.hasState()||!r){var o=this.currentStates,a=this.stateTransition;if(!(Wi(o,t)>=0)||!e&&1!==o.length){var s;if(this.stateProxy&&!r&&(s=this.stateProxy(t)),s||(s=this.states&&this.states[t]),s||r){r||this.saveCurrentToNormalState(s);var l=!!(s&&s.hoverLayer||i);l&&this._toggleHoverLayerFlag(!0),this._applyStateObj(t,s,this._normalState,e,!n&&!this.__inHover&&a&&a.duration>0,a);var c=this._textContent,u=this._textGuide;return c&&c.useState(t,e,n,l),u&&u.useState(t,e,n,l),r?(this.currentStates=[],this._normalState={}):e?this.currentStates.push(t):this.currentStates=[t],this._updateAnimationTargets(),this.markRedraw(),!l&&this.__inHover&&(this._toggleHoverLayerFlag(!1),this.__dirty&=-2),s}Hi("State "+t+" not exists.")}}},t.prototype.useStates=function(t,e,n){if(t.length){var i=[],r=this.currentStates,o=t.length,a=o===r.length;if(a)for(var s=0;s0,p);var f=this._textContent,g=this._textGuide;f&&f.useStates(t,e,d),g&&g.useStates(t,e,d),this._updateAnimationTargets(),this.currentStates=t.slice(),this.markRedraw(),!d&&this.__inHover&&(this._toggleHoverLayerFlag(!1),this.__dirty&=-2)}else this.clearStates()},t.prototype.isSilent=function(){for(var t=this;t;){if(t.silent)return!0;var e=t.__hostTarget;t=e?t.ignoreHostSilent?null:e:t.parent}return!1},t.prototype._updateAnimationTargets=function(){for(var t=0;t=0){var n=this.currentStates.slice();n.splice(e,1),this.useStates(n)}},t.prototype.replaceState=function(t,e,n){var i=this.currentStates.slice(),r=Wi(i,t),o=Wi(i,e)>=0;r>=0?o?i.splice(r,1):i[r]=e:n&&!o&&i.push(e),this.useStates(i)},t.prototype.toggleState=function(t,e){e?this.useState(t,!0):this.removeState(t)},t.prototype._mergeStates=function(t){for(var e,n={},i=0;i=0&&e.splice(n,1)}),this.animators.push(t),n&&n.animation.addAnimator(t),n&&n.wakeUp()},t.prototype.updateDuringAnimation=function(t){this.markRedraw()},t.prototype.stopAnimation=function(t,e){for(var n=this.animators,i=n.length,r=[],o=0;o0&&n.during&&o[0].during(function(t,e){n.during(e)});for(var h=0;h0||r.force&&!a.length){var w,S=void 0,C=void 0,k=void 0;if(s){C={},h&&(S={});for(b=0;b<_;b++){C[v=g[b]]=n[v],h?S[v]=i[v]:n[v]=i[v]}}else if(h){k={};for(b=0;b<_;b++){k[v=g[b]]=ws(n[v]),Ll(n,i,v)}}(w=new As(n,!1,!1,d?Yi(f,function(t){return t.targetName===e}):null)).targetName=e,r.scope&&(w.scope=r.scope),h&&S&&w.whenWithKeys(0,S,g),k&&w.whenWithKeys(0,k,g),w.whenWithKeys(null==c?500:c,s?C:i,g).delay(u||0),t.addAnimator(w,e),a.push(w)}}ji(Il,Vr),ji(Il,ll);var Nl=function(t){function e(e){var n=t.call(this)||this;return n.isGroup=!0,n._children=[],n.attr(e),n}return S(e,t),e.prototype.childrenRef=function(){return this._children},e.prototype.children=function(){return this._children.slice()},e.prototype.childAt=function(t){return this._children[t]},e.prototype.childOfName=function(t){for(var e=this._children,n=0;n=0&&(n.splice(i,0,t),this._doAdd(t))}return this},e.prototype.replace=function(t,e){var n=Wi(this._children,t);return n>=0&&this.replaceAt(e,n),this},e.prototype.replaceAt=function(t,e){var n=this._children,i=n[e];if(t&&t!==this&&t.parent!==this&&t!==i){n[e]=t,i.parent=null;var r=this.__zr;r&&i.removeSelfFromZr(r),this._doAdd(t)}return this},e.prototype._doAdd=function(t){t.parent&&t.parent.remove(t),t.parent=this;var e=this.__zr;e&&e!==t.__zr&&t.addSelfToZr(e),e&&e.refresh()},e.prototype.remove=function(t){var e=this.__zr,n=this._children,i=Wi(n,t);return i<0||(n.splice(i,1),t.parent=null,e&&t.removeSelfFromZr(e),e&&e.refresh()),this},e.prototype.removeAll=function(){for(var t=this._children,e=this.__zr,n=0;n":">",'"':""","'":"'"};function jt(t){return String(t).replace(/[&<>"']/g,t=>Wt[t]??t)}function qt(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}const Ut=y.power,Gt=y.current,Xt="--",Yt=`${Xt}`;function Zt(t){return Ut.unit(t)}function Kt(t){return(t<0?"-":"")+Ut.format(t)}function Qt(t){return null===t?Yt:`${Kt(t)} ${Zt(t)}`}function Jt(t){return null===t?Yt:`${Kt(t)}${Zt(t)}`}function te(t){return null===t?Yt:`${Gt.format(t)}A`}function ee(t){return t instanceof Error||"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message?t.message:String(t)}const ne=new Set(["Unauthorized","UnknownUser"]);function ie(t){if("object"!=typeof t||null===t)return!1;const e="code"in t?t.code:void 0;return"unauthorized"===e||"home_assistant_error"===e&&"message"in t&&ne.has(t.message)}const re="Validation error: ",oe={translation_domain:t=>"translation_domain"in t?t.translation_domain:void 0,translation_key:t=>"translation_key"in t?t.translation_key:void 0,translation_placeholders:t=>"translation_placeholders"in t?t.translation_placeholders:void 0};function ae(t,e){return"object"==typeof t&&null!==t?oe[e](t):void 0}async function se(t,e,n,i){const r=ae(e,"translation_key");if(t&&"string"==typeof r&&ae(e,"translation_domain")===n){const i=`component.${n}.exceptions.${r}.message`;try{const r=t.loadBackendTranslation?await t.loadBackendTranslation("exceptions",n):t.localize,o=r?.(i,function(t){const e=ae(t,"translation_placeholders");if("object"!=typeof e||null===e)return{};const n={};for(const[t,i]of Object.entries(e))"string"!=typeof i&&"number"!=typeof i||(n[t]=i);return n}(e));if(o)return o}catch{}}const o=ee(e),a=o.startsWith(re)?o.slice(18):o;return a&&"[object Object]"!==a?a:i}const le=["relay_state","relay_state_target","priority","priority_target"];function ce(t){return"_favoriteRefs"in t}const ue=Object.freeze({mayOperate:!0,reason:null}),de=Object.freeze({mayOperate:!1,reason:null}),he=["control_disabled","admin_only","read_only"];function pe(t){const e=t?.control_access;return"object"==typeof e&&null!==e&&"may_operate"in e&&"boolean"==typeof e.may_operate?e.may_operate?ue:{mayOperate:!1,reason:"reason"in e&&(n=e.reason,he.some(t=>t===n))?e.reason:null}:ue;var n}function fe(t){return"circuit"===t?.kind}function ge(t,e){if(!t||!ce(t))return pe(t);const n=t._favoriteRefs[e];return fe(n)?n.controlAccess:de}function me(t){return!!t?.entities?.switch&&!1!==t.is_user_controllable}function ve(t,e){const n=new Map;for(const[i,r]of Object.entries(t._favoriteRefs))fe(r)&&e(t.circuits[i])&&n.set(r.panelDeviceId,r.controlAccess);return n}const ye={control_disabled:()=>i("controls.disabled"),admin_only:()=>i("controls.admin_only"),read_only:()=>i("controls.read_only")};function _e(t){return t.mayOperate?"":t.reason?ye[t.reason]():i("controls.not_operable")}class be extends Error{constructor(t){super(t),this.name="ControlChangeRefused"}}function xe(t,e){return{setRelay:(n,i)=>we(t,e,"switch",i?"turn_on":"turn_off",n,{}),setPriority:(n,i)=>we(t,e,"select","select_option",n,{option:i})}}async function we(t,e,n,r,o,a){if(!e.mayOperate)throw new be(_e(e));try{await t.callWS({type:"call_service",domain:n,service:r,service_data:a,target:{entity_id:o}})}catch(t){throw ie(t)?new be(i("controls.entity_unauthorized")):t}}const Se={relay:{key:"service:relay",fallback:()=>i("error.relay_failed")},priority:{key:"service:shedding",fallback:()=>i("error.shedding_failed")}};function Ce(t,e,n,i){console.warn(`SPAN Panel: ${i} change failed`,n);const{key:r,fallback:o}=Se[i];se(t,n,l,o()).then(t=>{e?.add({key:r,level:"error",message:t,persistent:!1})})}function ke(t,e){const n=_e(e);n?t.title=n:t.removeAttribute("title")}function Me(t){const e=_e(t);return e?`

${jt(e)}

`:""}function Te(t,e,n={}){const r=jt(t.device_name||i("header.default_name")),o=jt(t.serial||""),a=jt(t.firmware||""),s="current"===(e.chart_metric||"power"),l=!1!==n.showSwitches;return`\n
\n
\n
\n

${r}

\n ${o}\n \n ${l?function(t,e={}){const n=!t.mayOperate;return`
\n ${jt(i("header.enable_switches"))}\n
\n \n
\n
${!1===e.note?"":Me(t)}`}(function(t){if(!t||!ce(t))return pe(t);const e=[...ve(t,me).values()],[n]=e;return!n||e.some(t=>t.mayOperate)?ue:n}(t)):""}\n
\n ${function(t,e){const n="current"===(e.chart_metric||"power"),r=!!t.panel_entities?.site_power,o=!!t.panel_entities?.dsm_state,a=!!t.panel_entities?.current_power,s=!!t.panel_entities?.feedthrough_power,l=!!t.panel_entities?.pv_power,c=!!t.panel_entities?.battery_level;return`\n
\n ${r?`\n
\n ${i("header.site")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${o?`\n
\n ${i("header.grid")}\n
\n ${Xt}\n
\n
`:""}\n ${a?`\n
\n ${i("header.upstream")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${s?`\n
\n ${i("header.downstream")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${l?`\n
\n ${i("header.solar")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${c?`\n
\n ${i("header.battery")}\n
\n ${Xt}\n %\n
\n
`:""}\n
\n `}(t,e)}\n
\n
\n
\n ${a}\n
\n \n \n
\n
\n
\n ${Object.entries(b).filter(([t])=>"unknown"!==t).map(([,t])=>{const e=jt(t.icon),n=jt(t.color),i=jt(t.label());let r;return r=t.icon2?``:t.textLabel?`${jt(t.textLabel)}`:``,`
${r}${i}
`}).join("")}\n
\n
\n
\n `}function Ae(t){return"number"==typeof t&&Number.isInteger(t)&&t>0}function Ie(t){return!0===t.outside_panel}function De(t,e){if(!t)return null;let n=null,i=null;const{first_position:r,last_position:o}=t;Ae(r)&&Ae(o)&&r<=o?(n=r,i=o):Ae(e)&&(n=1,i=e);for(const e of Object.values(t.circuits))if(e&&!Ie(e))for(const t of e.tabs??[])Ae(t)&&(n=null===n?t:Math.min(n,t),i=null===i?t:Math.max(i,t));return null===n||null===i?null:{first:n,last:i}}function Pe(t){return Le(t.last)-Le(t.first)+1}function Le(t){return Math.ceil(t/2)}function Ee(t){return t%2==0?1:0}function Ne(t){if(2!==t.length)return null;const[e,n]=[Math.min(...t),Math.max(...t)];return Le(e)===Le(n)?"row-span":Ee(e)===Ee(n)?"col-span":"row-span"}function Re(t){const e=t.chart_metric??o;return y[e]??y[o]}function Oe(t,e){const n=function(t){return Re(t).entityRole}(e);return t.entities?.[n]??t.entities?.power??null}function ze(t){return t.members.map((e,n)=>({uuid:t.memberIds[n],circuit:e}))}function He(t){return new Map(t.flatMap(t=>t.memberIds.map(e=>[e,t])))}function Be(t,e){if(!e)return t;const{breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}=e.circuit;return{...t,breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}}function Fe(t){const e=t.circuits,n=new Map;for(const[t,i]of Object.entries(e)){const e=i.shared_meter_group;e&&n.set(e,[...n.get(e)??[],[t,i]])}const i=[];for(const[r,o]of Object.entries(e)){const e=o.shared_meter_group,a=e?n.get(e):void 0;if(e&&a){if(a[0][0]===r){const[n,r]=a.find(([t])=>t===e)??a[0],o=a.map(([,t])=>t),s=t.shared_meter_groups?.[e];i.push({uuid:n,circuit:{...r,tabs:$e(o),breaker_rating_a:s?s.breaker_rating_a:We(o),monitoring_rating_a:s?.monitoring_rating_a,monitoring_rating_user_set:!0===s?.monitoring_rating_user_set},members:o,memberIds:a.map(([t])=>t)})}}else i.push({uuid:r,circuit:o,members:[o],memberIds:[r]})}return i}function $e(t){return[...new Set(t.flatMap(t=>t.tabs))].sort((t,e)=>t-e)}function Ve(t){const e=function(t){return t.some(t=>!t.breaker_rating_a)?"":t.map(t=>Math.round(t.breaker_rating_a)).join("·")}(t);return e?1===t.length?`${e}A`:`${e} A`:""}function We(t){let e=0;for(const n of t){if(!n.breaker_rating_a)return null;e+=n.breaker_rating_a}return e}function je(t){if(1===t.length){const e=t[0].breaker_rating_a;return e?`${e}A`:""}return Ve(t)}function qe(t){return new Promise(e=>setTimeout(e,t))}class Ue{constructor(t,{passThrough:e=()=>!1}={}){this._store=t,this._passThrough=e}async callWS(t,e,n){const i=n?.retries??3,r=n?.errorId??`ws:${String(e.type??"unknown")}`;return this._withRetry(()=>t.callWS(e),i,r,n?.errorMessage)}async _withRetry(t,e,n,r){if(this._store.hasAnyPanelOffline())try{const e=await t();return this._store.remove(n),e}catch(t){if(this._passThrough(t))throw t;const e=t instanceof Error?t:new Error(ee(t));throw this._store.add({key:n,level:"error",message:r??i("error.panel_offline"),persistent:!1}),e}let o;for(let i=0;i<=e;i++)try{const e=await t();return this._store.remove(n),e}catch(t){if(this._passThrough(t))throw t;if(o=t instanceof Error?t:new Error(ee(t)),i{try{const n={};e&&(n.config_entry_id=e);const o={type:"call_service",domain:l,service:"get_monitoring_status",service_data:n,return_response:!0},a=this._retry?await this._retry.callWS(t,o,{errorId:"fetch:monitoring",errorMessage:i("error.monitoring_failed")}):await t.callWS(o),s=Ge(a?.response);return r===this._generation&&(this._status=s,this._lastFetch=Date.now()),s}catch(t){return console.warn("SPAN Panel: monitoring status fetch failed",t),r===this._generation&&(this._status=null),this._retry||this._errorStore?.add({key:"fetch:monitoring",level:"warning",message:i("error.monitoring_failed"),persistent:!1}),null}finally{this._inflight?.gen===r&&(this._inflight=null)}})();return this._inflight={gen:r,promise:o},o}invalidate(){this._lastFetch=0,this._generation++}get status(){return this._status}clear(){this._status=null,this._lastFetch=0,this._generation++}}class Ye{constructor(){this._caches=new Map,this._errorStore=null}get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t;for(const e of this._caches.values())e.errorStore=t}async fetchOne(t,e){let n=this._caches.get(e);return n||(n=new Xe,n.errorStore=this._errorStore,this._caches.set(e,n)),n.fetch(t,e)}invalidate(){for(const t of this._caches.values())t.invalidate()}clear(){this._caches.clear()}}function Ze(t,e){return function(t,e){return t?.circuits?t.circuits[e]??null:null}(t,function(t){return t.entities?.current??t.entities?.power??""}(e))}function Ke(t){return{continuousPct:t?.continuous_threshold_pct??80,spikePct:t?.spike_threshold_pct??100}}function Qe(t,e){const{continuousPct:n,spikePct:i}=Ke(e);return t>=i?"alert":t>=n?"warning":"normal"}function Je(t,e){return`utilization-${Qe(t,e)}`}function tn(t){return(void 0===t.monitoring_rating_a?t.breaker_rating_a:t.monitoring_rating_a)??null}function en(t){return null!=t&&!1!==t.monitoring_enabled}function nn(t,e){return en(e)?tn(t):t.breaker_rating_a??null}const rn=["continuous_threshold_pct","spike_threshold_pct"];function on(t,e){return en(e)?function(t,e){return"averaged_legs"===t?.package_ratings_state&&en(e)}(t,e)?"averaged_legs":function(t,e){return t&&e&&function(t){const e=t.package_ratings_state;return"applies"===e||"pending"===e&&"one_space"===t.package_ratings_form}(t)&&rn.some(t=>(e[t]??0)>100)?!0===e.has_override?"own":"global":null}(t,e):null}function an(t){return t.packageRatings?.length&&t.panelAmps?r("monitoringRating.copied",{package:t.packageRatings.join("-"),panel:String(t.panelAmps)}):i("monitoringRating.copied_unnamed")}function sn(t,e,n,i){const r=[];return n||r.push("circuit-off"),i&&r.push("circuit-producer"),function(t){return!!t&&null!=t.over_threshold_since}(e)&&r.push("circuit-alert"),r.join(" ")}function ln(t,e){return Ie(t)||yn(t,e)}function cn(t,e){const n=t.entities?.power;return qt(n?e.states[n]:void 0)}function un(t,e){const n=t.entities?.current;return qt(n?e.states[n]:void 0)}function dn(t){return t.is_generation??"pv"===t.device_type}function hn(t,e){return dn(t)||null!==e&&e<0}function pn(t,e,n){const i=un(t,e);if(t.entities?.current&&null===i)return null;const r=n?.utilization_pct??null,o=nn(t,n);return null===r&&null!==i&&o?Math.round(Math.abs(i)/o*1e3)/10:r}const fn=new Set(x),gn={NEVER:"never",SOC_THRESHOLD:"soc_threshold",OFF_GRID:"off_grid"};function mn(t,e){const n=t.entities?.switch;return n?e.states[n]?.state:void 0}function vn(t,e,n){const i=t.entities?.power,r=i?e.states[i]?.attributes?.[n]:void 0;return"string"==typeof r&&r?r:void 0}function yn(t,e){const n=mn(t,e);return"on"===n||"off"===n?"on"===n:"CLOSED"===(vn(t,e,"relay_state")??t.relay_state)}function _n(t,e){if(!t.entities?.switch||!1===t.is_user_controllable)return"none";const n=mn(t,e);return void 0===n?"none":"on"===n||"off"===n?"operable":"inert"}function bn(t){return void 0===t?void 0:gn[t]}function xn(t,e){const n=t.entities?.select;return n?e.states[n]?.state:void 0}function wn(t,e){if(t.always_on)return"always_on";if(!t.entities?.select)return"unknown";const n=xn(t,e);return void 0!==n&&fn.has(n)?n:bn(vn(t,e,"shed_priority"))??bn(t.priority)??"unknown"}function Sn(t,e){return _e(t)||(e?i("grid.shared_switch"):"")}function Cn(t,e,n,r=!1){if("none"===e)return"";const o=["toggle-pill",t?"toggle-on":"toggle-off"];"inert"===e&&o.push("toggle-unavailable"),r&&o.push("toggle-shared"),n.mayOperate||o.push("toggle-forbidden");const a=Sn(n,r);return`
\n ${i(t?"grid.on":"grid.off")}\n \n
`}function kn(t,e,n,r){const o=t.querySelector(".toggle-pill");if(!o)return;o.classList.toggle("toggle-on",e),o.classList.toggle("toggle-off",!e),o.classList.toggle("toggle-unavailable","operable"!==n),o.classList.toggle("toggle-forbidden",!r.mayOperate);const a=Sn(r,o.classList.contains("toggle-shared"));a?o.title=a:o.removeAttribute("title");const s=o.querySelector(".toggle-label");s&&(s.textContent=i(e?"grid.on":"grid.off"))}function Mn(t){return"unknown"===t?void 0:b[t]}const Tn="display:none;";function An(t){const e=Mn(t),n=e?jt(e.color):"",i=e?` title="${jt(e.label())}"`:"",r=e?jt(e.icon):"",o=e?.icon2?jt(e.icon2):"",a=e?.textLabel?jt(e.textLabel):"";return`\n \n \n ${a}\n `}function In(t,e){const n=t.querySelector(".shedding-composite");if(!n)return;const i=Mn(e);n.style.display=i?"":"none",n.title=i?i.label():"";const r=i?.color??"",o=n.querySelector(".shedding-icon");o&&(o.setAttribute("icon",i?.icon??""),o.style.color=r);const a=n.querySelector(".shedding-icon-secondary");a&&(a.setAttribute("icon",i?.icon2??""),a.style.color=r,a.style.display=i?.icon2?"":"none");const s=n.querySelector(".shedding-label");s&&(s.textContent=i?.textLabel??"",s.style.color=r,s.style.display=i?.textLabel?"":"none")}function Dn(t,e,n,r,o,a,s,l,c,u,d=[e],h=!1){const p=cn(e,a),f=hn(e,p),g=yn(e,a),m=_n(e,a),v=d.length>1,y=Ve(d),_=jt(d.map(t=>t.name||i("grid.unknown")).join(" · ")),b="current"===Re(s).entityRole?te(un(e,a)):Jt(p),x=An(c||"unknown"),w=``;let S="";const C=pn(e,a,l);null!==C&&(S=`${Math.round(C)}%`);return`\n
\n
\n
\n ${y?`${y}`:""}\n ${S}\n ${_}\n
\n
\n \n ${b}\n \n ${Cn(g,m,u,v&&function(t){const e=t[0]?.shared_relay_group;return!!e&&t.every(t=>t.shared_relay_group===e)}(d))}\n
\n
\n
\n ${x}\n ${w}\n
\n
\n
\n `}function Pn(t,e){return`\n
\n —\n
\n `}function Ln(t){return"function"==typeof globalThis.CSS?.escape?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}function En(t){return Object.entries(t.circuits).filter(([,t])=>Ie(t))}function Nn(t,e){return!1!==e.show_panel&&En(t).length>0}function Rn(t,e,n){return`${jt(function(t){const e=qt(t);if(null===e)return Xt;const n=t?.attributes.unit_of_measurement;return"Wh"===n?`${(e/1e3).toFixed(1)} kWh`:"kWh"===n?`${e.toFixed(1)} kWh`:"string"==typeof n&&n?`${e} ${n}`:String(e)}(e?t.states[e]:void 0))} ${jt(n)}`}function On(t,e,n){const r=cn(t,e),o=null===r||0===r?"":i(r>0?"meters.importing":"meters.exporting");return`\n ${"current"===Re(n).entityRole?te(un(t,e)):Jt(r)}\n ${jt(o)}\n ${Rn(e,t.entities?.consumed_energy,i("meters.imported"))}\n ${Rn(e,t.entities?.produced_energy,i("meters.exported"))}\n `}const zn={names:["power","battery power"],suffixes:["_power"]},Hn={names:["battery level","battery percentage"],suffixes:["_battery_level","_battery_percentage"]},Bn={names:["state of energy"],suffixes:["_soe_kwh"]};function Fn(t,e){if(!t.entities)return null;for(const[n,i]of Object.entries(t.entities)){if("sensor"!==i.domain)continue;const t=(i.original_name??"").toLowerCase();if(e.names.some(e=>t===e))return n;if(i.unique_id&&e.suffixes.some(t=>i.unique_id.endsWith(t)))return n}return null}function $n(t){return Fn(t,Hn)}function Vn(t){return Fn(t,Bn)}function Wn(t){const e=t.solar;return e?"inverter"===e.role?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:null}:e.power_entity_id?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:e.site_power_entity_id}:{headlineEid:e.site_power_entity_id,headlineIsSiteTotal:null!==e.site_power_entity_id,siteTotalEid:null}:{headlineEid:(n=t,Fn(n,zn)),headlineIsSiteTotal:!1,siteTotalEid:null};var n}function jn(t){const{headlineEid:e,siteTotalEid:n}=Wn(t),i=[e,n];return t.type===f&&i.push($n(t),Vn(t)),new Set(i.filter(t=>null!==t))}function qn(t){const e=[{role:"power",entityId:Wn(t).headlineEid}];return t.type===f&&e.push({role:"soc",entityId:$n(t)},{role:"soe",entityId:Vn(t)}),e.filter(t=>null!==t.entityId)}function Un(t,e){return qt(t.states[e])}function Gn(t){if(!t)return null;let e=null;for(const[n,i]of Object.entries(t)){if("sensor"===i.domain)return n;e||(e=n)}return e}function Xn(t,e){return qn(t).length>0||e&&null!==Gn(t.entities)}function Yn(t,e=()=>""){const n=t=>"site"===t.solar?.role?0:1,i=new Map;for(const n of t){if(n[1].type!==m)continue;const t=e(n[0]),r=i.get(t);r?r.push(n):i.set(t,[n])}for(const t of i.values())t.sort(([,t],[,e])=>n(t)-n(e)||(t.name??"").localeCompare(e.name??""));const r=[],o=new Set;for(const n of t){if(n[1].type!==m){r.push(n);continue}const t=e(n[0]);o.has(t)||(o.add(t),r.push(...i.get(t)??[]))}return r}function Zn(t,e){return void 0!==t.config_entry_id&&e.has(t.config_entry_id)&&!t.via_device_id&&!t.parent_device_id}function Kn(t){return(t.name_by_user||t.name||"").trim()}function Qn(t,e,n,r){const o=!1!==n.show_battery,a=!1!==n.show_evse,s=!1!==n.show_solar;if(!t.sub_devices)return"";const l=Yn(Object.entries(t.sub_devices).filter(([,t])=>!(t.type===f&&!o)&&(!(t.type===g&&!a)&&!(t.type===m&&!s))),function(t){if(!ce(t))return()=>"";const e=t._favoriteRefs;return t=>e[t]?.panelDeviceId??""}(t));if(0===l.length)return"";const c=[];for(const[t,i]of l){const r=Wn(i),o=i.type===f,a=o?$n(i):null,s=o?Vn(i):null,l=ni(i,e,n,jn(i)),u=ii(t,i,o,r.headlineEid,a,s),d=i.solar?ti(i.solar,r,e):"";(r.headlineEid||u||l||d)&&c.push({devId:t,sub:i,power:r,chartsHTML:u,entHTML:l,solarHTML:d})}if(0===c.length)return"";const u=c.filter(t=>t.sub.type===g).length;let d=0,h="";for(const{devId:t,sub:n,power:o,chartsHTML:a,entHTML:s,solarHTML:l}of c){const c=Jn(n),p=o.headlineIsSiteTotal?`${jt(i("subdevice.site_total"))}`:"",m=o.headlineEid?`${p}${Qt(Un(e,o.headlineEid))}`:"",v=Xn(n,r.showFavorites)?``:"",y=n.type===f,_=n.type===g;let b="";y?b="sub-device-bess":_&&(d++,d===u&&u%2==1&&(b="sub-device-full")),h+=`\n
\n
\n ${jt(c)}\n ${jt(n.name||"")}\n ${m}\n ${v}\n
\n ${a}\n ${l}\n ${s}\n
\n `}return h}function Jn(t){return t.type===m?"inverter"===t.solar?.role?i("subdevice.solar_inverter"):i("subdevice.solar"):t.type===g?i("subdevice.ev_charger"):t.type===f?i("subdevice.battery"):i("subdevice.fallback")}function ti(t,e,n){let r="";const o="role"===t.identity?"":[t.vendor,t.model].filter(t=>!!t).join(" · ");if(o&&(r+=`
${jt(o)}
`),e.siteTotalEid){const t=Un(n,e.siteTotalEid);r+=`\n
\n ${jt(i("subdevice.site_total"))}:\n ${Qt(t)}\n
`}return"inverter"!==t.role||e.headlineEid||(r+=`
${jt(i("subdevice.in_site_total"))}
`),r}function ei(t,e){const n=t.entities?.[e],i=n?.name?.trim();if(i)return i;const r=n?.device_id?t.devices?.[n.device_id]:void 0;return r&&Kn(r)||e}function ni(t,e,n,i){const r=n.visible_sub_entities||{};let o="";if(!t.entities)return o;for(const[n,a]of Object.entries(t.entities)){if(i.has(n))continue;if(!0!==r[n])continue;const s=e.states[n];if(!s)continue;let l=a.original_name||ei(e,n);const c=t.name||"";let u;if(l.startsWith(c+" ")&&(l=l.slice(c.length+1)),e.formatEntityState)u=e.formatEntityState(s);else{u=s.state;const t=s.attributes.unit_of_measurement||"";t&&(u+=" "+t)}if("Wh"===(s.attributes.unit_of_measurement||"")){const t=qt(s);null!==t&&(u=(t/1e3).toFixed(1)+" kWh")}o+=`\n
\n ${jt(l)}:\n ${jt(u)}\n
\n `}return o}function ii(t,e,n,r,o,a){if(n){const e=[{key:`${v}${t}_soc`,title:i("subdevice.soc"),available:!!o},{key:`${v}${t}_soe`,title:i("subdevice.soe"),available:!!a},{key:`${v}${t}_power`,title:i("subdevice.power"),available:!!r}].filter(t=>t.available);return`\n
\n ${e.map(t=>`\n
\n
${jt(t.title)}
\n
\n
\n `).join("")}\n
\n `}return r?`
`:""}function ri(t){const e=void 0!==t.history_days||void 0!==t.history_hours||void 0!==t.history_minutes,n=60*(60*(24*(e&&parseInt(String(t.history_days))||0)+(e&&parseInt(String(t.history_hours))||0))+(e?parseInt(String(t.history_minutes))||0:5))*1e3;return Math.max(n,6e4)}function oi(t){const e=s[t];return e?e.ms:s[a].ms}function ai(t){const e=t/1e3;return e<=600?Math.ceil(e):Math.min(5e3,Math.ceil(e/5))}function si(t){return Math.max(500,Math.floor(t/5e3))}function li(t,e,n,i,r,o){t.has(e)||t.set(e,[]);const a=t.get(e);a.push({time:i,value:n});const s=a.findIndex(t=>t.time>=r);s>0?a.splice(0,s):-1===s&&(a.length=0),a.length>o&&a.splice(0,a.length-o)}function ci(t,e,n=500){if(0===t.length)return t;t.sort((t,e)=>t.time-e.time);const i=[t[0]];for(let e=1;e=n&&i.push(t[e]);return i.length>e&&i.splice(0,i.length-e),i}function ui(t,e,n,i){let r=t.get(e);r||(r={entityIds:[],keysByEntity:new Map},t.set(e,r));const o=r.keysByEntity.get(n);o?o.push(i):(r.entityIds.push(n),r.keysByEntity.set(n,[i]))}async function di(t,e,n,i,r){const o=new Date(Date.now()-i).toISOString(),a=i/36e5>72?"hour":"5minute",s=await t.callWS({type:"recorder/statistics_during_period",start_time:o,statistic_ids:e,period:a,types:["mean"]});for(const[t,e]of Object.entries(s)){const i=n.get(t);if(!i||!e)continue;const o=[];for(const t of e){const e=t.mean;if(null==e||!Number.isFinite(e))continue;const n=t.start;n>0&&o.push({time:n,value:e})}if(0!==o.length)for(const t of i){const e=r.get(t)||[],n=[...o,...e];n.sort((t,e)=>t.time-e.time),r.set(t,n)}}}async function hi(t,e,n,i,r){const o=new Date(Date.now()-i).toISOString(),a=await t.callWS({type:"history/history_during_period",start_time:o,entity_ids:e,minimal_response:!0,significant_changes_only:!0,no_attributes:!0}),s=ai(i),l=si(i);for(const[t,e]of Object.entries(a)){const i=n.get(t);if(!i||!e)continue;const o=[];for(const t of e){const e=parseFloat(t.s);if(!Number.isFinite(e))continue;const n=1e3*(t.lu||t.lc||0);n>0&&o.push({time:n,value:e})}if(0!==o.length)for(const t of i){const e=r.get(t)||[],n=[...o,...e];r.set(t,ci(n,s,l))}}}function pi(t){if(!t.sub_devices)return[];const e=[];for(const[n,i]of Object.entries(t.sub_devices))for(const{role:t,entityId:r}of qn(i))e.push({entityId:r,key:`${v}${n}_${t}`,devId:n});return e}async function fi(t,e,n,i,r,o){if(!e||!t)return;const a=new Map;for(const[t,i]of Object.entries(e.circuits)){const e=Oe(i,n);if(!e)continue;let o;o=r&&r.has(t)?oi(r.get(t)):ri(n),ui(a,o,e,t)}for(const{entityId:t,key:i,devId:r}of pi(e)){let e;e=o&&o.has(r)?oi(o.get(r)):ri(n),ui(a,e,t,i)}const s=[];for(const[e,n]of a){if(0===n.entityIds.length)continue;e>2592e5?s.push(di(t,n.entityIds,n.keysByEntity,e,i)):s.push(hi(t,n.entityIds,n.keysByEntity,e,i))}await Promise.all(s)}var gi=function(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1},mi=new function(){this.browser=new gi,this.node=!1,this.wxa=!1,this.worker=!1,this.svgSupported=!1,this.touchEventsSupported=!1,this.pointerEventsSupported=!1,this.domSupported=!1,this.transformSupported=!1,this.transform3dSupported=!1,this.hasGlobalWindow="undefined"!=typeof window};"object"==typeof wx&&"function"==typeof wx.getSystemInfoSync?(mi.wxa=!0,mi.touchEventsSupported=!0):"undefined"==typeof document&&"undefined"!=typeof self?mi.worker=!0:!mi.hasGlobalWindow||"Deno"in window||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Node.js")>-1?(mi.node=!0,mi.svgSupported=!0):function(t,e){var n=e.browser,i=t.match(/Firefox\/([\d.]+)/),r=t.match(/MSIE\s([\d.]+)/)||t.match(/Trident\/.+?rv:(([\d.]+))/),o=t.match(/Edge?\/([\d.]+)/),a=/micromessenger/i.test(t);i&&(n.firefox=!0,n.version=i[1]);r&&(n.ie=!0,n.version=r[1]);o&&(n.edge=!0,n.version=o[1],n.newEdge=+o[1].split(".")[0]>18);a&&(n.weChat=!0);e.svgSupported="undefined"!=typeof SVGRect,e.touchEventsSupported="ontouchstart"in window&&!n.ie&&!n.edge,e.pointerEventsSupported="onpointerdown"in window&&(n.edge||n.ie&&+n.version>=11);var s=e.domSupported="undefined"!=typeof document;if(s){var l=document.documentElement.style;e.transform3dSupported=(n.ie&&"transition"in l||n.edge||"WebKitCSSMatrix"in window&&"m11"in new WebKitCSSMatrix||"MozPerspective"in l)&&!("OTransition"in l),e.transformSupported=e.transform3dSupported||n.ie&&+n.version>=9}}(navigator.userAgent,mi);var vi="sans-serif",yi="12px "+vi;var _i,bi,xi=function(t){var e={};if("undefined"==typeof JSON)return e;for(var n=0;n=0)o=r*t.length;else for(var a=0;a>1)%2;a.style.cssText=["position: absolute","visibility: hidden","padding: 0","margin: 0","border-width: 0","user-select: none","width:0","height:0",i[s]+":0",r[l]+":0",i[1-s]+":auto",r[1-l]+":auto",""].join("!important;"),t.appendChild(a),n.push(a)}return e.clearMarkers=function(){ji(n,function(t){t.parentNode&&t.parentNode.removeChild(t)})},n}(e,o),s=function(t,e,n){for(var i=n?"invTrans":"trans",r=e[i],o=e.srcCoords,a=[],s=[],l=!0,c=0;c<4;c++){var u=t[c].getBoundingClientRect(),d=2*c,h=u.left,p=u.top;a.push(h,p),l=l&&o&&h===o[d]&&p===o[d+1],s.push(t[c].offsetLeft,t[c].offsetTop)}return l&&r?r:(e.srcCoords=a,e[i]=n?Wr(s,a):Wr(a,s))}(a,o,r);if(s)return s(t,n,i),!0}return!1}function Gr(t){return"CANVAS"===t.nodeName.toUpperCase()}var Xr=/([&<>"'])/g,Yr={"&":"&","<":"<",">":">",'"':""","'":"'"};function Zr(t){return null==t?"":(t+"").replace(Xr,function(t,e){return Yr[e]})}var Kr=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Qr=[],Jr=mi.browser.firefox&&+mi.browser.version.split(".")[0]<39;function to(t,e,n,i){return n=n||{},i?eo(t,e,n):Jr&&null!=e.layerX&&e.layerX!==e.offsetX?(n.zrX=e.layerX,n.zrY=e.layerY):null!=e.offsetX?(n.zrX=e.offsetX,n.zrY=e.offsetY):eo(t,e,n),n}function eo(t,e,n){if(mi.domSupported&&t.getBoundingClientRect){var i=e.clientX,r=e.clientY;if(Gr(t)){var o=t.getBoundingClientRect();return n.zrX=i-o.left,void(n.zrY=r-o.top)}if(Ur(Qr,t,i,r))return n.zrX=Qr[0],void(n.zrY=Qr[1])}n.zrX=n.zrY=0}function no(t){return t||window.event}function io(t,e,n){if(null!=(e=no(e)).zrX)return e;var i=e.type;if(i&&i.indexOf("touch")>=0){var r="touchend"!==i?e.targetTouches[0]:e.changedTouches[0];r&&to(t,r,e,n)}else{to(t,e,e,n);var o=function(t){var e=t.wheelDelta;if(e)return e;var n=t.deltaX,i=t.deltaY;if(null==n||null==i)return e;return 3*(0!==i?Math.abs(i):Math.abs(n))*(i>0?-1:i<0?1:n>0?-1:1)}(e);e.zrDelta=o?o/120:-(e.detail||0)/3}var a=e.button;return null==e.which&&void 0!==a&&Kr.test(e.type)&&(e.which=1&a?1:2&a?3:4&a?2:0),e}function ro(t,e,n,i){t.removeEventListener(e,n,i)}var oo=function(t){t.preventDefault(),t.stopPropagation(),t.cancelBubble=!0},ao=function(){function t(){this._track=[]}return t.prototype.recognize=function(t,e,n){return this._doTrack(t,e,n),this._recognize(t)},t.prototype.clear=function(){return this._track.length=0,this},t.prototype._doTrack=function(t,e,n){var i=t.touches;if(i){for(var r={points:[],touches:[],target:e,event:t},o=0,a=i.length;o1&&r&&r.length>1){var a=so(r)/so(o);!isFinite(a)&&(a=1),e.pinchScale=a;var s=[((i=r)[0][0]+i[1][0])/2,(i[0][1]+i[1][1])/2];return e.pinchX=s[0],e.pinchY=s[1],{type:"pinch",target:t[0].target,event:e}}}}};function co(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function uo(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t}function ho(t,e,n){var i=e[0]*n[0]+e[2]*n[1],r=e[1]*n[0]+e[3]*n[1],o=e[0]*n[2]+e[2]*n[3],a=e[1]*n[2]+e[3]*n[3],s=e[0]*n[4]+e[2]*n[5]+e[4],l=e[1]*n[4]+e[3]*n[5]+e[5];return t[0]=i,t[1]=r,t[2]=o,t[3]=a,t[4]=s,t[5]=l,t}function po(t,e,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4]+n[0],t[5]=e[5]+n[1],t}function fo(t,e,n,i){void 0===i&&(i=[0,0]);var r=e[0],o=e[2],a=e[4],s=e[1],l=e[3],c=e[5],u=Math.sin(n),d=Math.cos(n);return t[0]=r*d+s*u,t[1]=-r*u+s*d,t[2]=o*d+l*u,t[3]=-o*u+d*l,t[4]=d*(a-i[0])+u*(c-i[1])+i[0],t[5]=d*(c-i[1])-u*(a-i[0])+i[1],t}function go(t,e){var n=e[0],i=e[2],r=e[4],o=e[1],a=e[3],s=e[5],l=n*a-o*i;return l?(l=1/l,t[0]=a*l,t[1]=-o*l,t[2]=-i*l,t[3]=n*l,t[4]=(i*s-a*r)*l,t[5]=(o*r-n*s)*l,t):null}var mo=function(){function t(t,e){this.x=t||0,this.y=e||0}return t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this},t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.set=function(t,e){return this.x=t,this.y=e,this},t.prototype.equal=function(t){return t.x===this.x&&t.y===this.y},t.prototype.add=function(t){return this.x+=t.x,this.y+=t.y,this},t.prototype.scale=function(t){this.x*=t,this.y*=t},t.prototype.scaleAndAdd=function(t,e){this.x+=t.x*e,this.y+=t.y*e},t.prototype.sub=function(t){return this.x-=t.x,this.y-=t.y,this},t.prototype.dot=function(t){return this.x*t.x+this.y*t.y},t.prototype.len=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.prototype.lenSquare=function(){return this.x*this.x+this.y*this.y},t.prototype.normalize=function(){var t=this.len();return this.x/=t,this.y/=t,this},t.prototype.distance=function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)},t.prototype.distanceSquare=function(t){var e=this.x-t.x,n=this.y-t.y;return e*e+n*n},t.prototype.negate=function(){return this.x=-this.x,this.y=-this.y,this},t.prototype.transform=function(t){if(t){var e=this.x,n=this.y;return this.x=t[0]*e+t[2]*n+t[4],this.y=t[1]*e+t[3]*n+t[5],this}},t.prototype.toArray=function(t){return t[0]=this.x,t[1]=this.y,t},t.prototype.fromArray=function(t){this.x=t[0],this.y=t[1]},t.set=function(t,e,n){t.x=e,t.y=n},t.copy=function(t,e){t.x=e.x,t.y=e.y},t.len=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)},t.lenSquare=function(t){return t.x*t.x+t.y*t.y},t.dot=function(t,e){return t.x*e.x+t.y*e.y},t.add=function(t,e,n){t.x=e.x+n.x,t.y=e.y+n.y},t.sub=function(t,e,n){t.x=e.x-n.x,t.y=e.y-n.y},t.scale=function(t,e,n){t.x=e.x*n,t.y=e.y*n},t.scaleAndAdd=function(t,e,n,i){t.x=e.x+n.x*i,t.y=e.y+n.y*i},t.lerp=function(t,e,n,i){var r=1-i;t.x=r*e.x+i*n.x,t.y=r*e.y+i*n.y},t}(),vo=Math.min,yo=Math.max,_o=Math.abs,bo=["x","y"],xo=["width","height"],wo=new mo,So=new mo,Co=new mo,ko=new mo,Mo=No(),To=Mo.minTv,Ao=Mo.maxTv,Io=[0,0],Do=function(){function t(e,n,i,r){t.set(this,e,n,i,r)}return t.set=function(t,e,n,i,r){return i<0&&(e+=i,i=-i),r<0&&(n+=r,r=-r),t.x=e,t.y=n,t.width=i,t.height=r,t},t.prototype.union=function(t){var e=vo(t.x,this.x),n=vo(t.y,this.y);isFinite(this.x)&&isFinite(this.width)?this.width=yo(t.x+t.width,this.x+this.width)-e:this.width=t.width,isFinite(this.y)&&isFinite(this.height)?this.height=yo(t.y+t.height,this.y+this.height)-n:this.height=t.height,this.x=e,this.y=n},t.prototype.applyTransform=function(e){t.applyTransform(this,this,e)},t.prototype.calculateTransform=function(t){var e=this,n=t.width/e.width,i=t.height/e.height,r=[1,0,0,1,0,0];return po(r,r,[-e.x,-e.y]),function(t,e,n){var i=n[0],r=n[1];t[0]=e[0]*i,t[1]=e[1]*r,t[2]=e[2]*i,t[3]=e[3]*r,t[4]=e[4]*i,t[5]=e[5]*r}(r,r,[n,i]),po(r,r,[t.x,t.y]),r},t.prototype.intersect=function(e,n,i){return t.intersect(this,e,n,i)},t.intersect=function(e,n,i,r){i&&mo.set(i,0,0);var o=r&&r.outIntersectRect||null,a=r&&r.clamp;if(o&&(o.x=o.y=o.width=o.height=NaN),!e||!n)return!1;e instanceof t||(e=t.set(Po,e.x,e.y,e.width,e.height)),n instanceof t||(n=t.set(Lo,n.x,n.y,n.width,n.height));var s=!!i;Mo.reset(r,s);var l=Mo.touchThreshold,c=e.x+l,u=e.x+e.width-l,d=e.y+l,h=e.y+e.height-l,p=n.x+l,f=n.x+n.width-l,g=n.y+l,m=n.y+n.height-l;if(c>u||d>h||p>f||g>m)return!1;var v=!(u=t.x&&e<=t.x+t.width&&n>=t.y&&n<=t.y+t.height},t.prototype.contain=function(e,n){return t.contain(this,e,n)},t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(e){t.copy(this,e)},t.prototype.plain=function(){return{x:this.x,y:this.y,width:this.width,height:this.height}},t.prototype.isFinite=function(){return isFinite(this.x)&&isFinite(this.y)&&isFinite(this.width)&&isFinite(this.height)},t.prototype.isZero=function(){return 0===this.width||0===this.height},t.create=function(e){return new t(e.x,e.y,e.width,e.height)},t.copy=function(t,e){return t.x=e.x,t.y=e.y,t.width=e.width,t.height=e.height,t},t.applyTransform=function(e,n,i){if(i){if(i[1]<1e-5&&i[1]>-1e-5&&i[2]<1e-5&&i[2]>-1e-5){var r=i[0],o=i[3],a=i[4],s=i[5];return e.x=n.x*r+a,e.y=n.y*o+s,e.width=n.width*r,e.height=n.height*o,e.width<0&&(e.x+=e.width,e.width=-e.width),void(e.height<0&&(e.y+=e.height,e.height=-e.height))}wo.x=Co.x=n.x,wo.y=ko.y=n.y,So.x=ko.x=n.x+n.width,So.y=Co.y=n.y+n.height,wo.transform(i),ko.transform(i),So.transform(i),Co.transform(i),e.x=vo(wo.x,So.x,Co.x,ko.x),e.y=vo(wo.y,So.y,Co.y,ko.y);var l=yo(wo.x,So.x,Co.x,ko.x),c=yo(wo.y,So.y,Co.y,ko.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),Po=new Do(0,0,0,0),Lo=new Do(0,0,0,0);function Eo(t,e,n,i,r,o,a,s){var l=_o(e-n),c=_o(i-t),u=vo(l,c),d=bo[r],h=bo[1-r],p=xo[r];e=c||!Mo.bidirectional)&&(To[d]=-c,To[h]=0,Mo.useDir&&Mo.calcDirMTV())))}function No(){var t=0,e=new mo,n=new mo,i={minTv:new mo,maxTv:new mo,useDir:!1,dirMinTv:new mo,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(r,o){i.touchThreshold=0,r&&null!=r.touchThreshold&&(i.touchThreshold=yo(0,r.touchThreshold)),i.negativeSize=!1,o&&(i.minTv.set(1/0,1/0),i.maxTv.set(0,0),i.useDir=!1,r&&null!=r.direction&&(i.useDir=!0,i.dirMinTv.copy(i.minTv),n.copy(i.minTv),t=r.direction,i.bidirectional=null==r.bidirectional||!!r.bidirectional,i.bidirectional||e.set(Math.cos(t),Math.sin(t))))},calcDirMTV:function(){var o=i.minTv,a=i.dirMinTv,s=o.y*o.y+o.x*o.x,l=Math.sin(t),c=Math.cos(t),u=l*o.y+c*o.x;r(u)?r(o.x)&&r(o.y)&&a.set(0,0):(n.x=s*c/u,n.y=s*l/u,r(n.x)&&r(n.y)?a.set(0,0):(i.bidirectional||e.dot(n)>0)&&n.len()=0;c--){var u=i[c];u===n||u.ignore||u.ignoreCoarsePointer||u.parent&&u.parent.ignoreCoarsePointer||(Fo.copy(u.getBoundingRect()),u.transform&&Fo.applyTransform(u.transform),Fo.intersect(l)&&o.push(u))}if(o.length)for(var d=Math.PI/12,h=2*Math.PI,p=0;p=0;o--){var a=t[o],s=void 0;if(a!==r&&!a.ignore&&(s=Vo(a,n,i))&&(!e.topTarget&&(e.topTarget=a),s!==Ro)){e.target=a;break}}}function jo(t,e,n){var i=t.painter;return e<0||e>i.getWidth()||n<0||n>i.getHeight()}ji(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){$o.prototype[t]=function(e){var n,i,r=e.zrX,o=e.zrY,a=jo(this,r,o);if("mouseup"===t&&a||(i=(n=this.findHover(r,o)).target),"mousedown"===t)this._downEl=i,this._downPoint=[e.zrX,e.zrY],this._upEl=i;else if("mouseup"===t)this._upEl=i;else if("click"===t){if(this._downEl!==this._upEl||!this._downPoint||Er(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function qo(t,e,n,i){var r=e+1;if(r===n)return 1;if(i(t[r++],t[e])<0){for(;r=0;)r++;return r-e}function Uo(t,e,n,i,r){for(i===e&&i++;i>>1])<0?l=o:s=o+1;var c=i-s;switch(c){case 3:t[s+3]=t[s+2];case 2:t[s+2]=t[s+1];case 1:t[s+1]=t[s];break;default:for(;c>0;)t[s+c]=t[s+c-1],c--}t[s]=a}}function Go(t,e,n,i,r,o){var a=0,s=0,l=1;if(o(t,e[n+r])>0){for(s=i-r;l0;)a=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),a+=r,l+=r}else{for(s=r+1;ls&&(l=s);var c=a;a=r-l,l=r-c}for(a++;a>>1);o(t,e[n+u])>0?a=u+1:l=u}return l}function Xo(t,e,n,i,r,o){var a=0,s=0,l=1;if(o(t,e[n+r])<0){for(s=r+1;ls&&(l=s);var c=a;a=r-l,l=r-c}else{for(s=i-r;l=0;)a=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),a+=r,l+=r}for(a++;a>>1);o(t,e[n+u])<0?l=u:a=u+1}return l}function Yo(t,e){var n,i,r=7,o=0,a=[];function s(s){var l=n[s],c=i[s],u=n[s+1],d=i[s+1];i[s]=c+d,s===o-3&&(n[s+1]=n[s+2],i[s+1]=i[s+2]),o--;var h=Xo(t[u],t,l,c,0,e);l+=h,0!==(c-=h)&&0!==(d=Go(t[l+c-1],t,u,d,d-1,e))&&(c<=d?function(n,i,o,s){var l=0;for(l=0;l=7||p>=7);if(f)break;g<0&&(g=0),g+=2}if((r=g)<1&&(r=1),1===i){for(l=0;l=0;l--)t[p+l]=t[h+l];return void(t[d]=a[u])}var f=r;for(;;){var g=0,m=0,v=!1;do{if(e(a[u],t[c])<0){if(t[d--]=t[c--],g++,m=0,0===--i){v=!0;break}}else if(t[d--]=a[u--],m++,g=0,1===--s){v=!0;break}}while((g|m)=0;l--)t[p+l]=t[h+l];if(0===i){v=!0;break}}if(t[d--]=a[u--],1===--s){v=!0;break}if(0!==(m=s-Go(t[c],a,0,s,s-1,e))){for(s-=m,p=(d-=m)+1,h=(u-=m)+1,l=0;l=7||m>=7);if(v)break;f<0&&(f=0),f+=2}(r=f)<1&&(r=1);if(1===s){for(p=(d-=i)+1,h=(c-=i)+1,l=i-1;l>=0;l--)t[p+l]=t[h+l];t[d]=a[u]}else{if(0===s)throw new Error;for(h=d-(s-1),l=0;l1;){var t=o-2;if(t>=1&&i[t-1]<=i[t]+i[t+1]||t>=2&&i[t-2]<=i[t]+i[t-1])i[t-1]i[t+1])break;s(t)}},forceMergeRuns:function(){for(;o>1;){var t=o-2;t>0&&i[t-1]=32;)e|=1&t,t>>=1;return t+e}(r);do{if((o=qo(t,n,i,e))s&&(l=s),Uo(t,n,n+l,n+o,e),o=l}a.pushRun(n,o),a.mergeRuns(),r-=o,n+=o}while(0!==r);a.forceMergeRuns()}}}var Ko=!1;function Qo(){Ko||(Ko=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function Jo(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var ta,ea=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=Jo}return t.prototype.traverse=function(t,e){for(var n=0;n=0&&this._roots.splice(i,1)}},t.prototype.delAllRoots=function(){this._roots=[],this._displayList=[],this._displayListLen=0},t.prototype.getRoots=function(){return this._roots},t.prototype.dispose=function(){this._displayList=null,this._roots=null},t}();ta=mi.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(t){return setTimeout(t,16)};var na={linear:function(t){return t},quadraticIn:function(t){return t*t},quadraticOut:function(t){return t*(2-t)},quadraticInOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)},cubicIn:function(t){return t*t*t},cubicOut:function(t){return--t*t*t+1},cubicInOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},quarticIn:function(t){return t*t*t*t},quarticOut:function(t){return 1- --t*t*t*t},quarticInOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)},quinticIn:function(t){return t*t*t*t*t},quinticOut:function(t){return--t*t*t*t*t+1},quinticInOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},sinusoidalIn:function(t){return 1-Math.cos(t*Math.PI/2)},sinusoidalOut:function(t){return Math.sin(t*Math.PI/2)},sinusoidalInOut:function(t){return.5*(1-Math.cos(Math.PI*t))},exponentialIn:function(t){return 0===t?0:Math.pow(1024,t-1)},exponentialOut:function(t){return 1===t?1:1-Math.pow(2,-10*t)},exponentialInOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))},circularIn:function(t){return 1-Math.sqrt(1-t*t)},circularOut:function(t){return Math.sqrt(1- --t*t)},circularInOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},elasticIn:function(t){var e,n=.1;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=.4*Math.asin(1/n)/(2*Math.PI),-n*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},elasticOut:function(t){var e,n=.1;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=.4*Math.asin(1/n)/(2*Math.PI),n*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},elasticInOut:function(t){var e,n=.1,i=.4;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=i*Math.asin(1/n)/(2*Math.PI),(t*=2)<1?n*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/i)*-.5:n*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/i)*.5+1)},backIn:function(t){var e=1.70158;return t*t*((e+1)*t-e)},backOut:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},backInOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)},bounceIn:function(t){return 1-na.bounceOut(1-t)},bounceOut:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},bounceInOut:function(t){return t<.5?.5*na.bounceIn(2*t):.5*na.bounceOut(2*t-1)+.5}},ia=Math.pow,ra=Math.sqrt,oa=1e-8,aa=1e-4,sa=ra(3),la=1/3,ca=Mr(),ua=Mr(),da=Mr();function ha(t){return t>-1e-8&&toa||t<-1e-8}function fa(t,e,n,i,r){var o=1-r;return o*o*(o*t+3*r*e)+r*r*(r*i+3*o*n)}function ga(t,e,n,i,r){var o=1-r;return 3*(((e-t)*o+2*(n-e)*r)*o+(i-n)*r*r)}function ma(t,e,n,i,r,o){var a=i+3*(e-n)-t,s=3*(n-2*e+t),l=3*(e-t),c=t-r,u=s*s-3*a*l,d=s*l-9*a*c,h=l*l-3*s*c,p=0;if(ha(u)&&ha(d)){if(ha(s))o[0]=0;else(C=-l/s)>=0&&C<=1&&(o[p++]=C)}else{var f=d*d-4*u*h;if(ha(f)){var g=d/u,m=-g/2;(C=-s/a+g)>=0&&C<=1&&(o[p++]=C),m>=0&&m<=1&&(o[p++]=m)}else if(f>0){var v=ra(f),y=u*s+1.5*a*(-d+v),_=u*s+1.5*a*(-d-v);(C=(-s-((y=y<0?-ia(-y,la):ia(y,la))+(_=_<0?-ia(-_,la):ia(_,la))))/(3*a))>=0&&C<=1&&(o[p++]=C)}else{var b=(2*u*s-3*a*d)/(2*ra(u*u*u)),x=Math.acos(b)/3,w=ra(u),S=Math.cos(x),C=(-s-2*w*S)/(3*a),k=(m=(-s+w*(S+sa*Math.sin(x)))/(3*a),(-s+w*(S-sa*Math.sin(x)))/(3*a));C>=0&&C<=1&&(o[p++]=C),m>=0&&m<=1&&(o[p++]=m),k>=0&&k<=1&&(o[p++]=k)}}return p}function va(t,e,n,i,r){var o=6*n-12*e+6*t,a=9*e+3*i-3*t-9*n,s=3*e-3*t,l=0;if(ha(a)){if(pa(o))(u=-s/o)>=0&&u<=1&&(r[l++]=u)}else{var c=o*o-4*a*s;if(ha(c))r[0]=-o/(2*a);else if(c>0){var u,d=ra(c),h=(-o-d)/(2*a);(u=(-o+d)/(2*a))>=0&&u<=1&&(r[l++]=u),h>=0&&h<=1&&(r[l++]=h)}}return l}function ya(t,e,n,i,r,o){var a=(e-t)*r+t,s=(n-e)*r+e,l=(i-n)*r+n,c=(s-a)*r+a,u=(l-s)*r+s,d=(u-c)*r+c;o[0]=t,o[1]=a,o[2]=c,o[3]=d,o[4]=d,o[5]=u,o[6]=l,o[7]=i}function _a(t,e,n,i,r,o,a,s,l){for(var c=t,u=e,d=0,h=1/l,p=1;p<=l;p++){var f=p*h,g=fa(t,n,r,a,f),m=fa(e,i,o,s,f),v=g-c,y=m-u;d+=Math.sqrt(v*v+y*y),c=g,u=m}return d}function ba(t,e,n,i){var r=1-i;return r*(r*t+2*i*e)+i*i*n}function xa(t,e,n,i){return 2*((1-i)*(e-t)+i*(n-e))}function wa(t,e,n){var i=t+n-2*e;return 0===i?.5:(t-e)/i}function Sa(t,e,n,i,r){var o=(e-t)*i+t,a=(n-e)*i+e,s=(a-o)*i+o;r[0]=t,r[1]=o,r[2]=s,r[3]=s,r[4]=a,r[5]=n}function Ca(t,e,n,i,r,o,a){for(var s=t,l=e,c=0,u=1/a,d=1;d<=a;d++){var h=d*u,p=ba(t,n,r,h),f=ba(e,i,o,h),g=p-s,m=f-l;c+=Math.sqrt(g*g+m*m),s=p,l=f}return c}var ka=/cubic-bezier\(([0-9,\.e ]+)\)/;function Ma(t){var e=t&&ka.exec(t);if(e){var n=e[1].split(","),i=+fr(n[0]),r=+fr(n[1]),o=+fr(n[2]),a=+fr(n[3]);if(isNaN(i+r+o+a))return;var s=[];return function(t){return t<=0?0:t>=1?1:ma(0,i,o,1,t,s)&&fa(0,r,a,1,s[0])}}}var Ta=function(){function t(t){this._inited=!1,this._startTime=0,this._pausedTime=0,this._paused=!1,this._life=t.life||1e3,this._delay=t.delay||0,this.loop=t.loop||!1,this.onframe=t.onframe||Cr,this.ondestroy=t.ondestroy||Cr,this.onrestart=t.onrestart||Cr,t.easing&&this.setEasing(t.easing)}return t.prototype.step=function(t,e){if(this._inited||(this._startTime=t+this._delay,this._inited=!0),!this._paused){var n=this._life,i=t-this._startTime-this._pausedTime,r=i/n;r<0&&(r=0),r=Math.min(r,1);var o=this.easingFunc,a=o?o(r):r;if(this.onframe(a),1===r){if(!this.loop)return!0;var s=i%n;this._startTime=t-s,this._pausedTime=0,this.onrestart()}return!1}this._pausedTime+=e},t.prototype.pause=function(){this._paused=!0},t.prototype.resume=function(){this._paused=!1},t.prototype.setEasing=function(t){this.easing=t,this.easingFunc=Qi(t)?t:na[t]||Ma(t)},t}(),Aa=function(t){this.value=t},Ia=function(){function t(){this._len=0}return t.prototype.insert=function(t){var e=new Aa(t);return this.insertEntry(e),e},t.prototype.insertEntry=function(t){this.head?(this.tail.next=t,t.prev=this.tail,t.next=null,this.tail=t):this.head=this.tail=t,this._len++},t.prototype.remove=function(t){var e=t.prev,n=t.next;e?e.next=n:this.head=n,n?n.prev=e:this.tail=e,t.next=t.prev=null,this._len--},t.prototype.len=function(){return this._len},t.prototype.clear=function(){this.head=this.tail=null,this._len=0},t}(),Da=function(){function t(t){this._list=new Ia,this._maxSize=10,this._map={},this._maxSize=t}return t.prototype.put=function(t,e){var n=this._list,i=this._map,r=null;if(null==i[t]){var o=n.len(),a=this._lastRemovedEntry;if(o>=this._maxSize&&o>0){var s=n.head;n.remove(s),delete i[s.key],r=s.value,this._lastRemovedEntry=s}a?a.value=e:a=new Aa(e),a.key=t,n.insertEntry(a),i[t]=a}return r},t.prototype.get=function(t){var e=this._map[t],n=this._list;if(null!=e)return e!==n.tail&&(n.remove(e),n.insertEntry(e)),e.value},t.prototype.clear=function(){this._list.clear(),this._map={}},t.prototype.len=function(){return this._list.len()},t}(),Pa={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function La(t){return(t=Math.round(t))<0?0:t>255?255:t}function Ea(t){return t<0?0:t>1?1:t}function Na(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?La(parseFloat(e)/100*255):La(parseInt(e,10))}function Ra(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Ea(parseFloat(e)/100):Ea(parseFloat(e))}function Oa(t,e,n){return n<0?n+=1:n>1&&(n-=1),6*n<1?t+(e-t)*n*6:2*n<1?e:3*n<2?t+(e-t)*(2/3-n)*6:t}function za(t,e,n){return t+(e-t)*n}function Ha(t,e,n,i,r){return t[0]=e,t[1]=n,t[2]=i,t[3]=r,t}function Ba(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}var Fa=new Da(20),$a=null;function Va(t,e){$a&&Ba($a,e),$a=Fa.put(t,$a||e.slice())}function Wa(t,e){if(t){e=e||[];var n=Fa.get(t);if(n)return Ba(e,n);var i=(t+="").replace(/ /g,"").toLowerCase();if(i in Pa)return Ba(e,Pa[i]),Va(t,e),e;var r,o=i.length;if("#"===i.charAt(0))return 4===o||5===o?(r=parseInt(i.slice(1,4),16))>=0&&r<=4095?(Ha(e,(3840&r)>>4|(3840&r)>>8,240&r|(240&r)>>4,15&r|(15&r)<<4,5===o?parseInt(i.slice(4),16)/15:1),Va(t,e),e):void Ha(e,0,0,0,1):7===o||9===o?(r=parseInt(i.slice(1,7),16))>=0&&r<=16777215?(Ha(e,(16711680&r)>>16,(65280&r)>>8,255&r,9===o?parseInt(i.slice(7),16)/255:1),Va(t,e),e):void Ha(e,0,0,0,1):void 0;var a=i.indexOf("("),s=i.indexOf(")");if(-1!==a&&s+1===o){var l=i.substr(0,a),c=i.substr(a+1,s-(a+1)).split(","),u=1;switch(l){case"rgba":if(4!==c.length)return 3===c.length?Ha(e,+c[0],+c[1],+c[2],1):Ha(e,0,0,0,1);u=Ra(c.pop());case"rgb":return c.length>=3?(Ha(e,Na(c[0]),Na(c[1]),Na(c[2]),3===c.length?u:Ra(c[3])),Va(t,e),e):void Ha(e,0,0,0,1);case"hsla":return 4!==c.length?void Ha(e,0,0,0,1):(c[3]=Ra(c[3]),ja(c,e),Va(t,e),e);case"hsl":return 3!==c.length?void Ha(e,0,0,0,1):(ja(c,e),Va(t,e),e);default:return}}Ha(e,0,0,0,1)}}function ja(t,e){var n=(parseFloat(t[0])%360+360)%360/360,i=Ra(t[1]),r=Ra(t[2]),o=r<=.5?r*(i+1):r+i-r*i,a=2*r-o;return Ha(e=e||[],La(255*Oa(a,o,n+1/3)),La(255*Oa(a,o,n)),La(255*Oa(a,o,n-1/3)),1),4===t.length&&(e[3]=t[3]),e}function qa(t,e){var n=Wa(t);if(n){for(var i=0;i<3;i++)n[i]=n[i]*(1-e)|0,n[i]>255?n[i]=255:n[i]<0&&(n[i]=0);return Ga(n,4===n.length?"rgba":"rgb")}}function Ua(t,e,n,i){var r=Wa(t);if(t)return r=function(t){if(t){var e,n,i=t[0]/255,r=t[1]/255,o=t[2]/255,a=Math.min(i,r,o),s=Math.max(i,r,o),l=s-a,c=(s+a)/2;if(0===l)e=0,n=0;else{n=c<.5?l/(s+a):l/(2-s-a);var u=((s-i)/6+l/2)/l,d=((s-r)/6+l/2)/l,h=((s-o)/6+l/2)/l;i===s?e=h-d:r===s?e=1/3+u-h:o===s&&(e=2/3+d-u),e<0&&(e+=1),e>1&&(e-=1)}var p=[360*e,n,c];return null!=t[3]&&p.push(t[3]),p}}(r),null!=n&&(r[1]=Ra(Qi(n)?n(r[1]):n)),null!=i&&(r[2]=Ra(Qi(i)?i(r[2]):i)),Ga(ja(r),"rgba")}function Ga(t,e){if(t&&t.length){var n=t[0]+","+t[1]+","+t[2];return"rgba"!==e&&"hsva"!==e&&"hsla"!==e||(n+=","+t[3]),e+"("+n+")"}}function Xa(t,e){var n=Wa(t);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*e:0}var Ya=new Da(100);function Za(t){if(Ji(t)){var e=Ya.get(t);return e||(e=qa(t,-.1),Ya.put(t,e)),e}if(ar(t)){var n=Bi({},t);return n.colorStops=qi(t.colorStops,function(t){return{offset:t.offset,color:qa(t.color,-.1)}}),n}return t}var Ka=Math.round;function Qa(t){var e;if(t&&"transparent"!==t){if("string"==typeof t&&t.indexOf("rgba")>-1){var n=Wa(t);n&&(t="rgb("+n[0]+","+n[1]+","+n[2]+")",e=n[3])}}else t="none";return{color:t,opacity:null==e?1:e}}var Ja=1e-4;function ts(t){return t-1e-4}function es(t){return Ka(1e3*t)/1e3}function ns(t){return Ka(1e4*t)/1e4}var is={left:"start",right:"end",center:"middle",middle:"middle"};function rs(t){return t&&!!t.image}function os(t){return rs(t)||function(t){return t&&!!t.svgElement}(t)}function as(t){return"linear"===t.type}function ss(t){return"radial"===t.type}function ls(t){return t&&("linear"===t.type||"radial"===t.type)}function cs(t){return"url(#"+t+")"}function us(t){var e=t.getGlobalScale(),n=Math.max(e[0],e[1]);return Math.max(Math.ceil(Math.log(n)/Math.log(10)),1)}function ds(t){var e=t.x||0,n=t.y||0,i=(t.rotation||0)*kr,r=cr(t.scaleX,1),o=cr(t.scaleY,1),a=t.skewX||0,s=t.skewY||0,l=[];return(e||n)&&l.push("translate("+e+"px,"+n+"px)"),i&&l.push("rotate("+i+")"),1===r&&1===o||l.push("scale("+r+","+o+")"),(a||s)&&l.push("skew("+Ka(a*kr)+"deg, "+Ka(s*kr)+"deg)"),l.join(" ")}var hs=mi.hasGlobalWindow&&Qi(window.btoa)?function(t){return window.btoa(unescape(encodeURIComponent(t)))}:"undefined"!=typeof Buffer?function(t){return Buffer.from(t).toString("base64")}:function(t){return null},ps=Array.prototype.slice;function fs(t,e,n){return(e-t)*n+t}function gs(t,e,n,i){for(var r=e.length,o=0;oi?e:t,o=Math.min(n,i),a=r[o-1]||{color:[0,0,0,0],offset:0},s=o;sa)i.length=a;else for(var s=o;s=1},t.prototype.getAdditiveTrack=function(){return this._additiveTrack},t.prototype.addKeyframe=function(t,e,n){this._needsSort=!0;var i=this.keyframes,r=i.length,o=!1,a=6,s=e;if(Wi(e)){var l=function(t){return Wi(t&&t[0])?2:1}(e);a=l,(1===l&&!er(e[0])||2===l&&!er(e[0][0]))&&(o=!0)}else if(er(e)&&!sr(e))a=0;else if(Ji(e))if(isNaN(+e)){var c=Wa(e);c&&(s=c,a=3)}else a=0;else if(ar(e)){var u=Bi({},s);u.colorStops=qi(e.colorStops,function(t){return{offset:t.offset,color:Wa(t.color)}}),as(e)?a=4:ss(e)&&(a=5),s=u}0===r?this.valType=a:a===this.valType&&6!==a||(o=!0),this.discrete=this.discrete||o;var d={time:t,value:s,rawValue:e,percent:0};return n&&(d.easing=n,d.easingFunc=Qi(n)?n:na[n]||Ma(n)),i.push(d),d},t.prototype.prepare=function(t,e){var n=this.keyframes;this._needsSort&&n.sort(function(t,e){return t.time-e.time});for(var i=this.valType,r=n.length,o=n[r-1],a=this.discrete,s=Ss(i),l=ws(i),c=0;c=0&&!(l[n].percent<=e);n--);n=p(n,c-2)}else{for(n=h;ne);n++);n=p(n-1,c-2)}r=l[n+1],i=l[n]}if(i&&r){this._lastFr=n,this._lastFrP=e;var f=r.percent-i.percent,g=0===f?1:p((e-i.percent)/f,1);r.easingFunc&&(g=r.easingFunc(g));var m=o?this._additiveValue:d?Cs:t[u];if(!Ss(s)&&!d||m||(m=this._additiveValue=[]),this.discrete)t[u]=g<1?i.rawValue:r.rawValue;else if(Ss(s))1===s?gs(m,i[a],r[a],g):function(t,e,n,i){for(var r=e.length,o=r&&e[0].length,a=0;a0&&s.addKeyframe(0,bs(l),i),this._trackKeys.push(a)}s.addKeyframe(t,bs(e[a]),i)}return this._maxTime=Math.max(this._maxTime,t),this},t.prototype.pause=function(){this._clip.pause(),this._paused=!0},t.prototype.resume=function(){this._clip.resume(),this._paused=!1},t.prototype.isPaused=function(){return!!this._paused},t.prototype.duration=function(t){return this._maxTime=t,this._force=!0,this},t.prototype._doneCallback=function(){this._setTracksFinished(),this._clip=null;var t=this._doneCbs;if(t)for(var e=t.length,n=0;n0)){this._started=1;for(var e=this,n=[],i=this._maxTime||0,r=0;r1){var a=o.pop();r.addKeyframe(a.time,t[i]),r.prepare(this._maxTime,r.getAdditiveTrack())}}}},t}();function Ts(){return(new Date).getTime()}var As,Is,Ds=function(t){function e(e){var n=t.call(this)||this;return n._running=!1,n._time=0,n._pausedTime=0,n._pauseStart=0,n._paused=!1,e=e||{},n.stage=e.stage||{},n}return S(e,t),e.prototype.addClip=function(t){t.animation&&this.removeClip(t),this._head?(this._tail.next=t,t.prev=this._tail,t.next=null,this._tail=t):this._head=this._tail=t,t.animation=this},e.prototype.addAnimator=function(t){t.animation=this;var e=t.getClip();e&&this.addClip(e)},e.prototype.removeClip=function(t){if(t.animation){var e=t.prev,n=t.next;e?e.next=n:this._head=n,n?n.prev=e:this._tail=e,t.next=t.prev=t.animation=null}},e.prototype.removeAnimator=function(t){var e=t.getClip();e&&this.removeClip(e),t.animation=null},e.prototype.update=function(t){for(var e=Ts()-this._pausedTime,n=e-this._time,i=this._head;i;){var r=i.next;i.step(e,n)?(i.ondestroy(),this.removeClip(i),i=r):i=r}this._time=e,t||(this.trigger("frame",n),this.stage.update&&this.stage.update())},e.prototype._startLoop=function(){var t=this;this._running=!0,ta(function e(){t._running&&(ta(e),!t._paused&&t.update())})},e.prototype.start=function(){this._running||(this._time=Ts(),this._pausedTime=0,this._startLoop())},e.prototype.stop=function(){this._running=!1},e.prototype.pause=function(){this._paused||(this._pauseStart=Ts(),this._paused=!0)},e.prototype.resume=function(){this._paused&&(this._pausedTime+=Ts()-this._pauseStart,this._paused=!1)},e.prototype.clear=function(){for(var t=this._head;t;){var e=t.next;t.prev=t.next=t.animation=null,t=e}this._head=this._tail=null},e.prototype.isFinished=function(){return null==this._head},e.prototype.animate=function(t,e){e=e||{},this.start();var n=new Ms(t,e.loop);return this.addAnimator(n),n},e}(Fr),Ps=mi.domSupported,Ls=(Is={pointerdown:1,pointerup:1,pointermove:1,pointerout:1},{mouse:As=["click","dblclick","mousewheel","wheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],touch:["touchstart","touchend","touchmove"],pointer:qi(As,function(t){var e=t.replace("mouse","pointer");return Is.hasOwnProperty(e)?e:t})}),Es=["mousemove","mouseup"],Ns=["pointermove","pointerup"],Rs=!1;function Os(t){var e=t.pointerType;return"pen"===e||"touch"===e}function zs(t){t&&(t.zrByTouch=!0)}function Hs(t,e){for(var n=e,i=!1;n&&9!==n.nodeType&&!(i=n.domBelongToZr||n!==e&&n===t.painterRoot);)n=n.parentNode;return i}var Bs=function(t,e){this.stopPropagation=Cr,this.stopImmediatePropagation=Cr,this.preventDefault=Cr,this.type=e.type,this.target=this.currentTarget=t.dom,this.pointerType=e.pointerType,this.clientX=e.clientX,this.clientY=e.clientY},Fs={mousedown:function(t){t=io(this.dom,t),this.__mayPointerCapture=[t.zrX,t.zrY],this.trigger("mousedown",t)},mousemove:function(t){t=io(this.dom,t);var e=this.__mayPointerCapture;!e||t.zrX===e[0]&&t.zrY===e[1]||this.__togglePointerCapture(!0),this.trigger("mousemove",t)},mouseup:function(t){t=io(this.dom,t),this.__togglePointerCapture(!1),this.trigger("mouseup",t)},mouseout:function(t){Hs(this,(t=io(this.dom,t)).toElement||t.relatedTarget)||(this.__pointerCapturing&&(t.zrEventControl="no_globalout"),this.trigger("mouseout",t))},wheel:function(t){Rs=!0,t=io(this.dom,t),this.trigger("mousewheel",t)},mousewheel:function(t){Rs||(t=io(this.dom,t),this.trigger("mousewheel",t))},touchstart:function(t){zs(t=io(this.dom,t)),this.__lastTouchMoment=new Date,this.handler.processGesture(t,"start"),Fs.mousemove.call(this,t),Fs.mousedown.call(this,t)},touchmove:function(t){zs(t=io(this.dom,t)),this.handler.processGesture(t,"change"),Fs.mousemove.call(this,t)},touchend:function(t){zs(t=io(this.dom,t)),this.handler.processGesture(t,"end"),Fs.mouseup.call(this,t),+new Date-+this.__lastTouchMoment<300&&Fs.click.call(this,t)},pointerdown:function(t){Fs.mousedown.call(this,t)},pointermove:function(t){Os(t)||Fs.mousemove.call(this,t)},pointerup:function(t){Fs.mouseup.call(this,t)},pointerout:function(t){Os(t)||Fs.mouseout.call(this,t)}};ji(["click","dblclick","contextmenu"],function(t){Fs[t]=function(e){e=io(this.dom,e),this.trigger(t,e)}});var $s={pointermove:function(t){Os(t)||$s.mousemove.call(this,t)},pointerup:function(t){$s.mouseup.call(this,t)},mousemove:function(t){this.trigger("mousemove",t)},mouseup:function(t){var e=this.__pointerCapturing;this.__togglePointerCapture(!1),this.trigger("mouseup",t),e&&(t.zrEventControl="only_globalout",this.trigger("mouseout",t))}};function Vs(t,e){var n=e.domHandlers;mi.pointerEventsSupported?ji(Ls.pointer,function(i){js(e,i,function(e){n[i].call(t,e)})}):(mi.touchEventsSupported&&ji(Ls.touch,function(i){js(e,i,function(r){n[i].call(t,r),function(t){t.touching=!0,null!=t.touchTimer&&(clearTimeout(t.touchTimer),t.touchTimer=null),t.touchTimer=setTimeout(function(){t.touching=!1,t.touchTimer=null},700)}(e)})}),ji(Ls.mouse,function(i){js(e,i,function(r){r=no(r),e.touching||n[i].call(t,r)})}))}function Ws(t,e){function n(n){js(e,n,function(i){i=no(i),Hs(t,i.target)||(i=function(t,e){return io(t.dom,new Bs(t,e),!0)}(t,i),e.domHandlers[n].call(t,i))},{capture:!0})}mi.pointerEventsSupported?ji(Ns,n):mi.touchEventsSupported||ji(Es,n)}function js(t,e,n,i){t.mounted[e]=n,t.listenerOpts[e]=i,function(t,e,n,i){t.addEventListener(e,n,i)}(t.domTarget,e,n,i)}function qs(t){var e=t.mounted;for(var n in e)e.hasOwnProperty(n)&&ro(t.domTarget,n,e[n],t.listenerOpts[n]);t.mounted={}}var Us=function(t,e){this.mounted={},this.listenerOpts={},this.touching=!1,this.domTarget=t,this.domHandlers=e},Gs=function(t){function e(e,n){var i=t.call(this)||this;return i.__pointerCapturing=!1,i.dom=e,i.painterRoot=n,i._localHandlerScope=new Us(e,Fs),Ps&&(i._globalHandlerScope=new Us(document,$s)),Vs(i,i._localHandlerScope),i}return S(e,t),e.prototype.dispose=function(){qs(this._localHandlerScope),Ps&&qs(this._globalHandlerScope)},e.prototype.setCursor=function(t){this.dom.style&&(this.dom.style.cursor=t||"default")},e.prototype.__togglePointerCapture=function(t){if(this.__mayPointerCapture=null,Ps&&+this.__pointerCapturing^+t){this.__pointerCapturing=t;var e=this._globalHandlerScope;t?Ws(this,e):qs(e)}},e}(Fr),Xs=1;mi.hasGlobalWindow&&(Xs=Math.max(window.devicePixelRatio||window.screen&&window.screen.deviceXDPI/window.screen.logicalXDPI||1,1));var Ys=Xs,Zs="#333",Ks="#ccc",Qs=co,Js=5e-5;function tl(t){return t>Js||t<-5e-5}var el,nl=[],il=[],rl=[1,0,0,1,0,0],ol=Math.abs,al=function(){function t(){}var e;return t.prototype.getLocalTransform=function(e){return t.getLocalTransform(this,e)},t.prototype.setPosition=function(t){this.x=t[0],this.y=t[1]},t.prototype.setScale=function(t){this.scaleX=t[0],this.scaleY=t[1]},t.prototype.setSkew=function(t){this.skewX=t[0],this.skewY=t[1]},t.prototype.setOrigin=function(t){this.originX=t[0],this.originY=t[1]},t.prototype.needLocalTransform=function(){return tl(this.rotation)||tl(this.x)||tl(this.y)||tl(this.scaleX-1)||tl(this.scaleY-1)||tl(this.skewX)||tl(this.skewY)},t.prototype.updateTransform=function(){var t=this.parent&&this.parent.transform,e=this.needLocalTransform(),n=this.transform;e||t?(n=n||[1,0,0,1,0,0],e?this.getLocalTransform(n):Qs(n),t&&(e?ho(n,t,n):uo(n,t)),this.transform=n,this._resolveGlobalScaleRatio(n)):n&&(Qs(n),this.invTransform=null)},t.prototype._resolveGlobalScaleRatio=function(t){var e=this.globalScaleRatio;if(null!=e&&1!==e){this.getGlobalScale(nl);var n=nl[0]<0?-1:1,i=nl[1]<0?-1:1,r=((nl[0]-n)*e+n)/nl[0]||0,o=((nl[1]-i)*e+i)/nl[1]||0;t[0]*=r,t[1]*=r,t[2]*=o,t[3]*=o}this.invTransform=this.invTransform||[1,0,0,1,0,0],go(this.invTransform,t)},t.prototype.getComputedTransform=function(){for(var t=this,e=[];t;)e.push(t),t=t.parent;for(;t=e.pop();)t.updateTransform();return this.transform},t.prototype.setLocalTransform=function(t){if(t){var e=t[0]*t[0]+t[1]*t[1],n=t[2]*t[2]+t[3]*t[3],i=Math.atan2(t[1],t[0]),r=Math.PI/2+i-Math.atan2(t[3],t[2]);n=Math.sqrt(n)*Math.cos(r),e=Math.sqrt(e),this.skewX=r,this.skewY=0,this.rotation=-i,this.x=+t[4],this.y=+t[5],this.scaleX=e,this.scaleY=n,this.originX=0,this.originY=0}},t.prototype.decomposeTransform=function(){if(this.transform){var t=this.parent,e=this.transform;t&&t.transform&&(t.invTransform=t.invTransform||[1,0,0,1,0,0],ho(il,t.invTransform,e),e=il);var n=this.originX,i=this.originY;(n||i)&&(rl[4]=n,rl[5]=i,ho(il,e,rl),il[4]-=n,il[5]-=i,e=il),this.setLocalTransform(e)}},t.prototype.getGlobalScale=function(t){var e=this.transform;return t=t||[],e?(t[0]=Math.sqrt(e[0]*e[0]+e[1]*e[1]),t[1]=Math.sqrt(e[2]*e[2]+e[3]*e[3]),e[0]<0&&(t[0]=-t[0]),e[3]<0&&(t[1]=-t[1]),t):(t[0]=1,t[1]=1,t)},t.prototype.transformCoordToLocal=function(t,e){var n=[t,e],i=this.invTransform;return i&&Rr(n,n,i),n},t.prototype.transformCoordToGlobal=function(t,e){var n=[t,e],i=this.transform;return i&&Rr(n,n,i),n},t.prototype.getLineScale=function(){var t=this.transform;return t&&ol(t[0]-1)>1e-10&&ol(t[3]-1)>1e-10?Math.sqrt(ol(t[0]*t[3]-t[2]*t[1])):1},t.prototype.copyTransform=function(t){ll(this,t)},t.getLocalTransform=function(t,e){e=e||[];var n=t.originX||0,i=t.originY||0,r=t.scaleX,o=t.scaleY,a=t.anchorX,s=t.anchorY,l=t.rotation||0,c=t.x,u=t.y,d=t.skewX?Math.tan(t.skewX):0,h=t.skewY?Math.tan(-t.skewY):0;if(n||i||a||s){var p=n+a,f=i+s;e[4]=-p*r-d*f*o,e[5]=-f*o-h*p*r}else e[4]=e[5]=0;return e[0]=r,e[3]=o,e[1]=h*r,e[2]=d*o,l&&fo(e,e,l),e[4]+=n+c,e[5]+=i+u,e},t.initDefaultProps=((e=t.prototype).scaleX=e.scaleY=e.globalScaleRatio=1,void(e.x=e.y=e.originX=e.originY=e.skewX=e.skewY=e.rotation=e.anchorX=e.anchorY=0)),t}(),sl=["x","y","originX","originY","anchorX","anchorY","rotation","scaleX","scaleY","skewX","skewY"];function ll(t,e){for(var n=0;n=dl)){t=t||yi;for(var e=[],n=+new Date,i=0;i<=127;i++)e[i]=wi.measureText(String.fromCharCode(i),t).width;var r=+new Date-n;return r>16?ul=dl:r>2&&ul++,e}}(t.font),t.asciiWidthMapTried=!0),0<=e&&e<=127?null!=t.asciiWidthMap?t.asciiWidthMap[e]:t.asciiCharWidth:t.stWideCharWidth}function pl(t,e){var n=t.strWidthCache,i=n.get(e);return null==i&&(i=wi.measureText(e,t.font).width,n.put(e,i)),i}function fl(t,e,n,i){var r=pl(cl(e),t),o=yl(e),a=ml(0,r,n),s=vl(0,o,i);return new Do(a,s,r,o)}function gl(t,e,n,i){var r=((t||"")+"").split("\n");if(1===r.length)return fl(r[0],e,n,i);for(var o=new Do(0,0,0,0),a=0;a=0?parseFloat(t)/100*e:parseFloat(t):t}function bl(t,e,n){var i=e.position||"inside",r=null!=e.distance?e.distance:5,o=n.height,a=n.width,s=o/2,l=n.x,c=n.y,u="left",d="top";if(i instanceof Array)l+=_l(i[0],n.width),c+=_l(i[1],n.height),u=null,d=null;else switch(i){case"left":l-=r,c+=s,u="right",d="middle";break;case"right":l+=r+a,c+=s,d="middle";break;case"top":l+=a/2,c-=r,u="center",d="bottom";break;case"bottom":l+=a/2,c+=o+r,u="center";break;case"inside":l+=a/2,c+=s,u="center",d="middle";break;case"insideLeft":l+=r,c+=s,d="middle";break;case"insideRight":l+=a-r,c+=s,u="right",d="middle";break;case"insideTop":l+=a/2,c+=r,u="center";break;case"insideBottom":l+=a/2,c+=o-r,u="center",d="bottom";break;case"insideTopLeft":l+=r,c+=r;break;case"insideTopRight":l+=a-r,c+=r,u="right";break;case"insideBottomLeft":l+=r,c+=o-r,d="bottom";break;case"insideBottomRight":l+=a-r,c+=o-r,u="right",d="bottom"}return(t=t||{}).x=l,t.y=c,t.align=u,t.verticalAlign=d,t}var xl="__zr_normal__",wl=sl.concat(["ignore"]),Sl=Ui(sl,function(t,e){return t[e]=!0,t},{ignore:!1}),Cl={},kl=new Do(0,0,0,0),Ml=[],Tl=function(){function t(t){this.id=Ri(),this.animators=[],this.currentStates=[],this.states={},this._init(t)}return t.prototype._init=function(t){this.attr(t)},t.prototype.drift=function(t,e,n){switch(this.draggable){case"horizontal":e=0;break;case"vertical":t=0}var i=this.transform;i||(i=this.transform=[1,0,0,1,0,0]),i[4]+=t,i[5]+=e,this.decomposeTransform(),this.markRedraw()},t.prototype.beforeUpdate=function(){},t.prototype.afterUpdate=function(){},t.prototype.update=function(){this.updateTransform(),this.__dirty&&this.updateInnerText()},t.prototype.updateInnerText=function(t){var e=this._textContent;if(e&&(!e.ignore||t)){this.textConfig||(this.textConfig={});var n=this.textConfig,i=n.local,r=e.innerTransformable,o=void 0,a=void 0,s=!1;r.parent=i?this:null;var l=!1;r.copyTransform(e);var c=null!=n.position,u=n.autoOverflowArea,d=void 0;if((u||c)&&(d=kl,n.layoutRect?d.copy(n.layoutRect):d.copy(this.getBoundingRect()),i||d.applyTransform(this.transform)),c){this.calculateTextPosition?this.calculateTextPosition(Cl,n,d):bl(Cl,n,d),r.x=Cl.x,r.y=Cl.y,o=Cl.align,a=Cl.verticalAlign;var h=n.origin;if(h&&null!=n.rotation){var p=void 0,f=void 0;"center"===h?(p=.5*d.width,f=.5*d.height):(p=_l(h[0],d.width),f=_l(h[1],d.height)),l=!0,r.originX=-r.x+p+(i?0:d.x),r.originY=-r.y+f+(i?0:d.y)}}null!=n.rotation&&(r.rotation=n.rotation);var g=n.offset;g&&(r.x+=g[0],r.y+=g[1],l||(r.originX=-g[0],r.originY=-g[1]));var m=this._innerTextDefaultStyle||(this._innerTextDefaultStyle={});if(u){var v=m.overflowRect=m.overflowRect||new Do(0,0,0,0);r.getLocalTransform(Ml),go(Ml,Ml),Do.copy(v,d),v.applyTransform(Ml)}else m.overflowRect=null;var y=void 0,_=void 0,b=void 0;(null==n.inside?"string"==typeof n.position&&n.position.indexOf("inside")>=0:n.inside)&&this.canBeInsideText()?(y=n.insideFill,_=n.insideStroke,null!=y&&"auto"!==y||(y=this.getInsideTextFill()),null!=_&&"auto"!==_||(_=this.getInsideTextStroke(y),b=!0)):(y=n.outsideFill,_=n.outsideStroke,null!=y&&"auto"!==y||(y=this.getOutsideFill()),null!=_&&"auto"!==_||(_=this.getOutsideStroke(y),b=!0)),(y=y||"#000")===m.fill&&_===m.stroke&&b===m.autoStroke&&o===m.align&&a===m.verticalAlign||(s=!0,m.fill=y,m.stroke=_,m.autoStroke=b,m.align=o,m.verticalAlign=a,e.setDefaultTextStyle(m)),e.__dirty|=1,s&&e.dirtyStyle(!0)}},t.prototype.canBeInsideText=function(){return!0},t.prototype.getInsideTextFill=function(){return"#fff"},t.prototype.getInsideTextStroke=function(t){return"#000"},t.prototype.getOutsideFill=function(){return this.__zr&&this.__zr.isDarkMode()?Ks:Zs},t.prototype.getOutsideStroke=function(t){var e=this.__zr&&this.__zr.getBackgroundColor(),n="string"==typeof e&&Wa(e);n||(n=[255,255,255,1]);for(var i=n[3],r=this.__zr.isDarkMode(),o=0;o<3;o++)n[o]=n[o]*i+(r?0:255)*(1-i);return n[3]=1,Ga(n,"rgba")},t.prototype.traverse=function(t,e){},t.prototype.attrKV=function(t,e){"textConfig"===t?this.setTextConfig(e):"textContent"===t?this.setTextContent(e):"clipPath"===t?this.setClipPath(e):"extra"===t?(this.extra=this.extra||{},Bi(this.extra,e)):this[t]=e},t.prototype.hide=function(){this.ignore=!0,this.markRedraw()},t.prototype.show=function(){this.ignore=!1,this.markRedraw()},t.prototype.attr=function(t,e){if("string"==typeof t)this.attrKV(t,e);else if(nr(t))for(var n=Xi(t),i=0;i0},t.prototype.getState=function(t){return this.states[t]},t.prototype.ensureState=function(t){var e=this.states;return e[t]||(e[t]={}),e[t]},t.prototype.clearStates=function(t){this.useState(xl,!1,t)},t.prototype.useState=function(t,e,n,i){var r=t===xl;if(this.hasState()||!r){var o=this.currentStates,a=this.stateTransition;if(!($i(o,t)>=0)||!e&&1!==o.length){var s;if(this.stateProxy&&!r&&(s=this.stateProxy(t)),s||(s=this.states&&this.states[t]),s||r){r||this.saveCurrentToNormalState(s);var l=!!(s&&s.hoverLayer||i);l&&this._toggleHoverLayerFlag(!0),this._applyStateObj(t,s,this._normalState,e,!n&&!this.__inHover&&a&&a.duration>0,a);var c=this._textContent,u=this._textGuide;return c&&c.useState(t,e,n,l),u&&u.useState(t,e,n,l),r?(this.currentStates=[],this._normalState={}):e?this.currentStates.push(t):this.currentStates=[t],this._updateAnimationTargets(),this.markRedraw(),!l&&this.__inHover&&(this._toggleHoverLayerFlag(!1),this.__dirty&=-2),s}Oi("State "+t+" not exists.")}}},t.prototype.useStates=function(t,e,n){if(t.length){var i=[],r=this.currentStates,o=t.length,a=o===r.length;if(a)for(var s=0;s0,p);var f=this._textContent,g=this._textGuide;f&&f.useStates(t,e,d),g&&g.useStates(t,e,d),this._updateAnimationTargets(),this.currentStates=t.slice(),this.markRedraw(),!d&&this.__inHover&&(this._toggleHoverLayerFlag(!1),this.__dirty&=-2)}else this.clearStates()},t.prototype.isSilent=function(){for(var t=this;t;){if(t.silent)return!0;var e=t.__hostTarget;t=e?t.ignoreHostSilent?null:e:t.parent}return!1},t.prototype._updateAnimationTargets=function(){for(var t=0;t=0){var n=this.currentStates.slice();n.splice(e,1),this.useStates(n)}},t.prototype.replaceState=function(t,e,n){var i=this.currentStates.slice(),r=$i(i,t),o=$i(i,e)>=0;r>=0?o?i.splice(r,1):i[r]=e:n&&!o&&i.push(e),this.useStates(i)},t.prototype.toggleState=function(t,e){e?this.useState(t,!0):this.removeState(t)},t.prototype._mergeStates=function(t){for(var e,n={},i=0;i=0&&e.splice(n,1)}),this.animators.push(t),n&&n.animation.addAnimator(t),n&&n.wakeUp()},t.prototype.updateDuringAnimation=function(t){this.markRedraw()},t.prototype.stopAnimation=function(t,e){for(var n=this.animators,i=n.length,r=[],o=0;o0&&n.during&&o[0].during(function(t,e){n.during(e)});for(var h=0;h0||r.force&&!a.length){var w,S=void 0,C=void 0,k=void 0;if(s){C={},h&&(S={});for(b=0;b<_;b++){C[v=g[b]]=n[v],h?S[v]=i[v]:n[v]=i[v]}}else if(h){k={};for(b=0;b<_;b++){k[v=g[b]]=bs(n[v]),Dl(n,i,v)}}(w=new Ms(n,!1,!1,d?Gi(f,function(t){return t.targetName===e}):null)).targetName=e,r.scope&&(w.scope=r.scope),h&&S&&w.whenWithKeys(0,S,g),k&&w.whenWithKeys(0,k,g),w.whenWithKeys(null==c?500:c,s?C:i,g).delay(u||0),t.addAnimator(w,e),a.push(w)}}Vi(Tl,Fr),Vi(Tl,al);var Ll=function(t){function e(e){var n=t.call(this)||this;return n.isGroup=!0,n._children=[],n.attr(e),n}return S(e,t),e.prototype.childrenRef=function(){return this._children},e.prototype.children=function(){return this._children.slice()},e.prototype.childAt=function(t){return this._children[t]},e.prototype.childOfName=function(t){for(var e=this._children,n=0;n=0&&(n.splice(i,0,t),this._doAdd(t))}return this},e.prototype.replace=function(t,e){var n=$i(this._children,t);return n>=0&&this.replaceAt(e,n),this},e.prototype.replaceAt=function(t,e){var n=this._children,i=n[e];if(t&&t!==this&&t.parent!==this&&t!==i){n[e]=t,i.parent=null;var r=this.__zr;r&&i.removeSelfFromZr(r),this._doAdd(t)}return this},e.prototype._doAdd=function(t){t.parent&&t.parent.remove(t),t.parent=this;var e=this.__zr;e&&e!==t.__zr&&t.addSelfToZr(e),e&&e.refresh()},e.prototype.remove=function(t){var e=this.__zr,n=this._children,i=$i(n,t);return i<0||(n.splice(i,1),t.parent=null,e&&t.removeSelfFromZr(e),e&&e.refresh()),this},e.prototype.removeAll=function(){for(var t=this._children,e=this.__zr,n=0;n0&&(this._stillFrameAccum++,this._stillFrameAccum>this._sleepAfterStill&&this.animation.stop())},t.prototype.setSleepAfterStill=function(t){this._sleepAfterStill=t},t.prototype.wakeUp=function(){this._disposed||(this.animation.start(),this._stillFrameAccum=0)},t.prototype.refreshHover=function(){this._needsRefreshHover=!0},t.prototype.refreshHoverImmediately=function(){this._disposed||(this._needsRefreshHover=!1,this.painter.refreshHover&&"canvas"===this.painter.getType()&&this.painter.refreshHover())},t.prototype.resize=function(t){this._disposed||(t=t||{},this.painter.resize(t.width,t.height),this.handler.resize())},t.prototype.clearAnimation=function(){this._disposed||this.animation.clear()},t.prototype.getWidth=function(){if(!this._disposed)return this.painter.getWidth()},t.prototype.getHeight=function(){if(!this._disposed)return this.painter.getHeight()},t.prototype.setCursorStyle=function(t){this._disposed||this.handler.setCursorStyle(t)},t.prototype.findHover=function(t,e){if(!this._disposed)return this.handler.findHover(t,e)},t.prototype.on=function(t,e,n){return this._disposed||this.handler.on(t,e,n),this},t.prototype.off=function(t,e){this._disposed||this.handler.off(t,e)},t.prototype.trigger=function(t,e){this._disposed||this.handler.trigger(t,e)},t.prototype.clear=function(){if(!this._disposed){for(var t=this.storage.getRoots(),e=0;e0){if(t<=r)return a;if(t>=o)return s}else{if(t>=r)return a;if(t<=o)return s}else{if(t===r)return a;if(t===o)return s}return(t-r)/l*c+a}var ql=function(t,e,n){switch(t){case"center":case"middle":t="50%";break;case"left":case"top":t="0%";break;case"right":case"bottom":t="100%"}return Ul(t,e,n)};function Ul(t,e,n){return er(t)?(i=t,i.replace(/^\s+|\s+$/g,"")).match(/%$/)?parseFloat(t)/100*e+(n||0):parseFloat(t):null==t?NaN:+t;var i}function Gl(t,e,n){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),t=(+t).toFixed(e),n?t:+t}function Xl(t){if(t=+t,isNaN(t))return 0;if(t>1e-14)for(var e=1,n=0;n<15;n++,e*=10)if(Math.round(t*e)/e===t)return n;return function(t){var e=t.toString().toLowerCase(),n=e.indexOf("e"),i=n>0?+e.slice(n+1):0,r=n>0?n:e.length,o=e.indexOf("."),a=o<0?0:r-1-o;return Math.max(0,a-i)}(t)}function Yl(t,e){var n=Math.max(Xl(t),Xl(e)),i=t+e;return n>20?i:Gl(i,n)}function Zl(t){var e=2*Math.PI;return(t%e+e)%e}function Kl(t){return t>-1e-4&&t<$l}var Ql=/^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d{1,2})(?::(\d{1,2})(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/;function Jl(t){if(t instanceof Date)return t;if(er(t)){var e=Ql.exec(t);if(!e)return new Date(NaN);if(e[8]){var n=+e[4]||0;return"Z"!==e[8].toUpperCase()&&(n-=+e[8].slice(0,3)),new Date(Date.UTC(+e[1],+(e[2]||1)-1,+e[3]||1,n,+(e[5]||0),+e[6]||0,e[7]?+e[7].substring(0,3):0))}return new Date(+e[1],+(e[2]||1)-1,+e[3]||1,+e[4]||0,+(e[5]||0),+e[6]||0,e[7]?+e[7].substring(0,3):0)}return null==t?new Date(NaN):new Date(Math.round(t))}function tc(t){if(0===t)return 0;var e=Math.floor(Math.log(t)/Math.LN10);return t/Math.pow(10,e)>=10&&e++,e}function ec(t,e){var n=tc(t),i=Math.pow(10,n),r=t/i;return t=(r<1.5?1:r<2.5?2:r<4?3:r<7?5:10)*i,n>=-20?+t.toFixed(n<0?-n:0):t}function nc(t){var e=parseFloat(t);return e==t&&(0!==e||!er(t)||t.indexOf("x")<=0)?e:NaN}function ic(){return Math.round(9*Math.random())}function rc(t,e){return 0===e?t:rc(e,t%e)}function oc(t,e){return null==t?e:null==e?t:t*e/rc(t,e)}var ac="undefined"!=typeof console&&console.warn&&console.log;function sc(t,e){!function(t,e){ac&&console[t]("[ECharts] "+e)}("error",t)}function lc(t){throw new Error(t)}function cc(t,e,n){return(e-t)*n+t}var uc="series\0";function dc(t){return t instanceof Array?t:null==t?[]:[t]}function hc(t,e,n){if(t){t[e]=t[e]||{},t.emphasis=t.emphasis||{},t.emphasis[e]=t.emphasis[e]||{};for(var i=0,r=n.length;i=0||r&&Wi(r,s)<0)){var l=n.getShallow(s,e);null!=l&&(o[t[a][0]]=l)}}return o}}var $c=Bc([["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]]),Fc=function(){function t(){}return t.prototype.getAreaStyle=function(t,e){return $c(this,t,e)},t}(),Vc=new La(50);function Wc(t){if("string"==typeof t){var e=Vc.get(t);return e&&e.image}return t}function jc(t,e,n,i,r){if(t){if("string"==typeof t){if(e&&e.__zrImageSrc===t||!n)return e;var o=Vc.get(t),a={hostEl:n,cb:i,cbPayload:r};return o?!Uc(e=o.image)&&o.pending.push(a):((e=Ci.loadImage(t,qc,qc)).__zrImageSrc=t,Vc.put(t,e.__cachedImgObj={image:e,pending:[a]})),e}return t}return e}function qc(){var t=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var e=0;e=s;c++)l-=s;var u=gl(a,n);return u>l&&(n="",u=0),l=t-u,r.ellipsis=n,r.ellipsisWidth=u,r.contentWidth=l,r.containerWidth=t,r}function Zc(t,e,n){var i=n.containerWidth,r=n.contentWidth,o=n.fontMeasureInfo;if(!i)return t.textLine="",void(t.isTruncated=!1);var a=gl(o,e);if(a<=i)return t.textLine=e,void(t.isTruncated=!1);for(var s=0;;s++){if(a<=r||s>=n.maxIterations){e+=n.ellipsis;break}var l=0===s?Kc(e,r,o):a>0?Math.floor(e.length*r/a):0;a=gl(o,e=e.substr(0,l))}""===e&&(e=n.placeholder),t.textLine=e,t.isTruncated=!0}function Kc(t,e,n){for(var i=0,r=0,o=t.length;r0&&f+i.accumWidth>i.width&&(o=e.split("\n"),d=!0),i.accumWidth=f}else{var g=ru(e,u,i.width,i.breakAll,i.accumWidth);i.accumWidth=g.accumWidth+p,a=g.linesWidths,o=g.lines}}o||(o=e.split("\n"));for(var m=dl(u),v=0;v=32&&e<=591||e>=880&&e<=4351||e>=4608&&e<=5119||e>=7680&&e<=8303}(t)||!!nu[t]}function ru(t,e,n,i,r){for(var o=[],a=[],s="",l="",c=0,u=0,d=dl(e),h=0;hn:r+u+f>n)?u?(s||l)&&(g?(s||(s=l,l="",u=c=0),o.push(s),a.push(u-c),l+=p,s="",u=c+=f):(l&&(s+=l,l="",c=0),o.push(s),a.push(u),s=p,u=f)):g?(o.push(l),a.push(c),l=p,c=f):(o.push(p),a.push(f)):(u+=f,g?(l+=p,c+=f):(l&&(s+=l,l="",c=0),s+=p))}else l&&(s+=l,u+=c),o.push(s),a.push(u),s="",l="",c=0,u=0}return l&&(s+=l),s&&(o.push(s),a.push(u)),1===o.length&&(u+=r),{accumWidth:u,lines:o,linesWidths:a}}function ou(t,e,n,i,r,o){if(t.baseX=n,t.baseY=i,t.outerWidth=t.outerHeight=null,e){var a=2*e.width,s=2*e.height;Lo.set(au,yl(n,a,r),_l(i,s,o),a,s),Lo.intersect(e,au,null,su);var l=su.outIntersectRect;t.outerWidth=l.width,t.outerHeight=l.height,t.baseX=yl(l.x,l.width,r,!0),t.baseY=_l(l.y,l.height,o,!0)}}var au=new Lo(0,0,0,0),su={outIntersectRect:{},clamp:!0};function lu(t){return null!=t?t+="":t=""}function cu(t,e,n,i){var r=new Lo(yl(t.x||0,e,t.textAlign),_l(t.y||0,n,t.textBaseline),e,n),o=null!=i?i:uu(t)?t.lineWidth:0;return o>0&&(r.x-=o/2,r.y-=o/2,r.width+=o,r.height+=o),r}function uu(t){var e=t.stroke;return null!=e&&"none"!==e&&t.lineWidth>0}var du="__zr_style_"+Math.round(10*Math.random()),hu={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},pu={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};hu[du]=!0;var fu=["z","z2","invisible"],gu=["invisible"],mu=function(t){function e(e){return t.call(this,e)||this}var n;return S(e,t),e.prototype._init=function(e){for(var n=Zi(e),i=0;i1e-4)return s[0]=t-n,s[1]=e-i,l[0]=t+n,void(l[1]=e+i);if(Cu[0]=wu(r)*n+t,Cu[1]=xu(r)*i+e,ku[0]=wu(o)*n+t,ku[1]=xu(o)*i+e,c(s,Cu,ku),u(l,Cu,ku),(r%=Su)<0&&(r+=Su),(o%=Su)<0&&(o+=Su),r>o&&!a?o+=Su:rr&&(Mu[0]=wu(p)*n+t,Mu[1]=xu(p)*i+e,c(s,Mu,s),u(l,Mu,l))}var Eu={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},Nu=[],Ru=[],Ou=[],zu=[],Hu=[],Bu=[],$u=Math.min,Fu=Math.max,Vu=Math.cos,Wu=Math.sin,ju=Math.abs,qu=Math.PI,Uu=2*qu,Gu="undefined"!=typeof Float32Array,Xu=[];function Yu(t){return Math.round(t/qu*1e8)/1e8%2*qu}var Zu=function(){function t(t){this.dpr=1,this._xi=0,this._yi=0,this._x0=0,this._y0=0,this._len=0,t&&(this._saveData=!1),this._saveData&&(this.data=[])}var e;return t.prototype.increaseVersion=function(){this._version++},t.prototype.getVersion=function(){return this._version},t.prototype.setScale=function(t,e,n){(n=n||0)>0&&(this._ux=ju(n/Ks/t)||0,this._uy=ju(n/Ks/e)||0)},t.prototype.setDPR=function(t){this.dpr=t},t.prototype.setContext=function(t){this._ctx=t},t.prototype.getContext=function(){return this._ctx},t.prototype.beginPath=function(){return this._ctx&&this._ctx.beginPath(),this.reset(),this},t.prototype.reset=function(){this._saveData&&(this._len=0),this._pathSegLen&&(this._pathSegLen=null,this._pathLen=0),this._version++},t.prototype.moveTo=function(t,e){return this._drawPendingPt(),this.addData(Eu.M,t,e),this._ctx&&this._ctx.moveTo(t,e),this._x0=t,this._y0=e,this._xi=t,this._yi=e,this},t.prototype.lineTo=function(t,e){var n=ju(t-this._xi),i=ju(e-this._yi),r=n>this._ux||i>this._uy;if(this.addData(Eu.L,t,e),this._ctx&&r&&this._ctx.lineTo(t,e),r)this._xi=t,this._yi=e,this._pendingPtDist=0;else{var o=n*n+i*i;o>this._pendingPtDist&&(this._pendingPtX=t,this._pendingPtY=e,this._pendingPtDist=o)}return this},t.prototype.bezierCurveTo=function(t,e,n,i,r,o){return this._drawPendingPt(),this.addData(Eu.C,t,e,n,i,r,o),this._ctx&&this._ctx.bezierCurveTo(t,e,n,i,r,o),this._xi=r,this._yi=o,this},t.prototype.quadraticCurveTo=function(t,e,n,i){return this._drawPendingPt(),this.addData(Eu.Q,t,e,n,i),this._ctx&&this._ctx.quadraticCurveTo(t,e,n,i),this._xi=n,this._yi=i,this},t.prototype.arc=function(t,e,n,i,r,o){this._drawPendingPt(),Xu[0]=i,Xu[1]=r,function(t,e){var n=Yu(t[0]);n<0&&(n+=Uu);var i=n-t[0],r=t[1];r+=i,!e&&r-n>=Uu?r=n+Uu:e&&n-r>=Uu?r=n-Uu:!e&&n>r?r=n+(Uu-Yu(n-r)):e&&n0&&o))for(var a=0;ac.length&&(this._expandData(),c=this.data);for(var u=0;u0&&(this._ctx&&this._ctx.lineTo(this._pendingPtX,this._pendingPtY),this._pendingPtDist=0)},t.prototype._expandData=function(){if(!(this.data instanceof Array)){for(var t=[],e=0;e11&&(this.data=new Float32Array(t)))}},t.prototype.getBoundingRect=function(){Ou[0]=Ou[1]=Hu[0]=Hu[1]=Number.MAX_VALUE,zu[0]=zu[1]=Bu[0]=Bu[1]=-Number.MAX_VALUE;var t,e=this.data,n=0,i=0,r=0,o=0;for(t=0;tn||ju(m)>i||d===e-1)&&(f=Math.sqrt(I*I+m*m),r=g,o=_);break;case Eu.C:var v=t[d++],y=t[d++],_=(g=t[d++],t[d++]),b=t[d++],x=t[d++];f=xa(r,o,v,y,g,_,b,x,10),r=b,o=x;break;case Eu.Q:f=Ma(r,o,v=t[d++],y=t[d++],g=t[d++],_=t[d++],10),r=g,o=_;break;case Eu.A:var w=t[d++],S=t[d++],C=t[d++],k=t[d++],M=t[d++],T=t[d++],A=T+M;d+=1,p&&(a=Vu(M)*C+w,s=Wu(M)*k+S),f=Fu(C,k)*$u(Uu,Math.abs(T)),r=Vu(A)*C+w,o=Wu(A)*k+S;break;case Eu.R:a=r=t[d++],s=o=t[d++],f=2*t[d++]+2*t[d++];break;case Eu.Z:var I=a-r;m=s-o;f=Math.sqrt(I*I+m*m),r=a,o=s}f>=0&&(l[u++]=f,c+=f)}return this._pathLen=c,c},t.prototype.rebuildPath=function(t,e){var n,i,r,o,a,s,l,c,u,d,h=this.data,p=this._ux,f=this._uy,g=this._len,m=e<1,v=0,y=0,_=0;if(!m||(this._pathSegLen||this._calculateLength(),l=this._pathSegLen,c=e*this._pathLen))t:for(var b=0;b0&&(t.lineTo(u,d),_=0),x){case Eu.M:n=r=h[b++],i=o=h[b++],t.moveTo(r,o);break;case Eu.L:a=h[b++],s=h[b++];var S=ju(a-r),C=ju(s-o);if(S>p||C>f){if(m){if(v+(X=l[y++])>c){var k=(c-v)/X;t.lineTo(r*(1-k)+a*k,o*(1-k)+s*k);break t}v+=X}t.lineTo(a,s),r=a,o=s,_=0}else{var M=S*S+C*C;M>_&&(u=a,d=s,_=M)}break;case Eu.C:var T=h[b++],A=h[b++],I=h[b++],D=h[b++],P=h[b++],L=h[b++];if(m){if(v+(X=l[y++])>c){ba(r,T,I,P,k=(c-v)/X,Nu),ba(o,A,D,L,k,Ru),t.bezierCurveTo(Nu[1],Ru[1],Nu[2],Ru[2],Nu[3],Ru[3]);break t}v+=X}t.bezierCurveTo(T,A,I,D,P,L),r=P,o=L;break;case Eu.Q:T=h[b++],A=h[b++],I=h[b++],D=h[b++];if(m){if(v+(X=l[y++])>c){ka(r,T,I,k=(c-v)/X,Nu),ka(o,A,D,k,Ru),t.quadraticCurveTo(Nu[1],Ru[1],Nu[2],Ru[2]);break t}v+=X}t.quadraticCurveTo(T,A,I,D),r=I,o=D;break;case Eu.A:var E=h[b++],N=h[b++],R=h[b++],O=h[b++],z=h[b++],H=h[b++],B=h[b++],$=!h[b++],F=R>O?R:O,V=ju(R-O)>.001,W=z+H,j=!1;if(m)v+(X=l[y++])>c&&(W=z+H*(c-v)/X,j=!0),v+=X;if(V&&t.ellipse?t.ellipse(E,N,R,O,B,z,W,$):t.arc(E,N,F,z,W,$),j)break t;w&&(n=Vu(z)*R+E,i=Wu(z)*O+N),r=Vu(W)*R+E,o=Wu(W)*O+N;break;case Eu.R:n=r=h[b],i=o=h[b+1],a=h[b++],s=h[b++];var q=h[b++],U=h[b++];if(m){if(v+(X=l[y++])>c){var G=c-v;t.moveTo(a,s),t.lineTo(a+$u(G,q),s),(G-=q)>0&&t.lineTo(a+q,s+$u(G,U)),(G-=U)>0&&t.lineTo(a+Fu(q-G,0),s+U),(G-=q)>0&&t.lineTo(a,s+Fu(U-G,0));break t}v+=X}t.rect(a,s,q,U);break;case Eu.Z:if(m){var X;if(v+(X=l[y++])>c){k=(c-v)/X;t.lineTo(r*(1-k)+n*k,o*(1-k)+i*k);break t}v+=X}t.closePath(),r=n,o=i}}},t.prototype.clone=function(){var e=new t,n=this.data;return e.data=n.slice?n.slice():Array.prototype.slice.call(n),e._len=this._len,e},t.prototype.canSave=function(){return!!this._saveData},t.CMD=Eu,t.initDefaultProps=((e=t.prototype)._saveData=!0,e._ux=0,e._uy=0,e._pendingPtDist=0,void(e._version=0)),t}();function Ku(t,e,n,i,r,o,a){if(0===r)return!1;var s=r,l=0;if(a>e+s&&a>i+s||at+s&&o>n+s||oe+d&&u>i+d&&u>o+d&&u>s+d||ut+d&&c>n+d&&c>r+d&&c>a+d||c=0&&pe+c&&l>i+c&&l>o+c||lt+c&&s>n+c&&s>r+c||s=0&&gn||u+cr&&(r+=nd);var h=Math.atan2(l,s);return h<0&&(h+=nd),h>=i&&h<=r||h+nd>=i&&h+nd<=r}function rd(t,e,n,i,r,o){if(o>e&&o>i||or?s:0}var od=Zu.CMD,ad=2*Math.PI;var sd=[-1,-1,-1],ld=[-1,-1];function cd(){var t=ld[0];ld[0]=ld[1],ld[1]=t}function ud(t,e,n,i,r,o,a,s,l,c){if(c>e&&c>i&&c>o&&c>s||c1&&cd(),p=ma(e,i,o,s,ld[0]),h>1&&(f=ma(e,i,o,s,ld[1]))),2===h?me&&s>i&&s>o||s=0&&u<=1&&(r[l++]=u);else{var c=a*a-4*o*s;if(fa(c))(u=-a/(2*o))>=0&&u<=1&&(r[l++]=u);else if(c>0){var u,d=aa(c),h=(-a-d)/(2*o);(u=(-a+d)/(2*o))>=0&&u<=1&&(r[l++]=u),h>=0&&h<=1&&(r[l++]=h)}}return l}(e,i,o,s,sd);if(0===l)return 0;var c=Ca(e,i,o);if(c>=0&&c<=1){for(var u=0,d=wa(e,i,o,c),h=0;hn||s<-n)return 0;var l=Math.sqrt(n*n-s*s);sd[0]=-l,sd[1]=l;var c=Math.abs(i-r);if(c<1e-4)return 0;if(c>=ad-1e-4){i=0,r=ad;var u=o?1:-1;return a>=sd[0]+t&&a<=sd[1]+t?u:0}if(i>r){var d=i;i=r,r=d}i<0&&(i+=ad,r+=ad);for(var h=0,p=0;p<2;p++){var f=sd[p];if(f+t>a){var g=Math.atan2(s,f);u=o?1:-1;g<0&&(g=ad+g),(g>=i&&g<=r||g+ad>=i&&g+ad<=r)&&(g>Math.PI/2&&g<1.5*Math.PI&&(u=-u),h+=u)}}return h}function pd(t,e,n,i,r){for(var o,a,s=t.data,l=t.len(),c=0,u=0,d=0,h=0,p=0,f=0;f1&&(n||(c+=rd(u,d,h,p,i,r))),m&&(h=u=s[f],p=d=s[f+1]),g){case od.M:u=h=s[f++],d=p=s[f++];break;case od.L:if(n){if(Ku(u,d,s[f],s[f+1],e,i,r))return!0}else c+=rd(u,d,s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case od.C:if(n){if(Qu(u,d,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=ud(u,d,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case od.Q:if(n){if(Ju(u,d,s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=dd(u,d,s[f++],s[f++],s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case od.A:var v=s[f++],y=s[f++],_=s[f++],b=s[f++],x=s[f++],w=s[f++];f+=1;var S=!!(1-s[f++]);o=Math.cos(x)*_+v,a=Math.sin(x)*b+y,m?(h=o,p=a):c+=rd(u,d,o,a,i,r);var C=(i-v)*b/_+v;if(n){if(id(v,y,b,x,x+w,S,e,C,r))return!0}else c+=hd(v,y,b,x,x+w,S,C,r);u=Math.cos(x+w)*_+v,d=Math.sin(x+w)*b+y;break;case od.R:if(h=u=s[f++],p=d=s[f++],o=h+s[f++],a=p+s[f++],n){if(Ku(h,p,o,p,e,i,r)||Ku(o,p,o,a,e,i,r)||Ku(o,a,h,a,e,i,r)||Ku(h,a,h,p,e,i,r))return!0}else c+=rd(o,p,o,a,i,r),c+=rd(h,a,h,p,i,r);break;case od.Z:if(n){if(Ku(u,d,h,p,e,i,r))return!0}else c+=rd(u,d,h,p,i,r);u=h,d=p}}return n||function(t,e){return Math.abs(t-e)<1e-4}(d,p)||(c+=rd(u,d,h,p,i,r)||0),0!==c}var fd=Vi({fill:"#000",stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:"butt",miterLimit:10,strokeNoScale:!1,strokeFirst:!1},hu),gd={style:Vi({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},pu.style)},md=cl.concat(["invisible","culling","z","z2","zlevel","parent"]),vd=function(t){function e(e){return t.call(this,e)||this}var n;return S(e,t),e.prototype.update=function(){var n=this;t.prototype.update.call(this);var i=this.style;if(i.decal){var r=this._decalEl=this._decalEl||new e;r.buildPath===e.prototype.buildPath&&(r.buildPath=function(t){n.buildPath(t,n.shape)}),r.silent=!0;var o=r.style;for(var a in i)o[a]!==i[a]&&(o[a]=i[a]);o.fill=i.fill?i.decal:null,o.decal=null,o.shadowColor=null,i.strokeFirst&&(o.stroke=null);for(var s=0;s.5?Qs:e>.2?"#eee":Js}if(t)return Js}return Qs},e.prototype.getInsideTextStroke=function(t){var e=this.style.fill;if(er(e)){var n=this.__zr;if(!(!n||!n.isDarkMode())===Za(t,0)<.4)return e}},e.prototype.buildPath=function(t,e,n){},e.prototype.pathUpdated=function(){this.__dirty&=-5},e.prototype.getUpdatedPathProxy=function(t){return!this.path&&this.createPathProxy(),this.path.beginPath(),this.buildPath(this.path,this.shape,t),this.path},e.prototype.createPathProxy=function(){this.path=new Zu(!1)},e.prototype.hasStroke=function(){var t=this.style,e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))},e.prototype.hasFill=function(){var t=this.style.fill;return null!=t&&"none"!==t},e.prototype.getBoundingRect=function(){var t=this._rect,e=this.style,n=!t;if(n){var i=!1;this.path||(i=!0,this.createPathProxy());var r=this.path;(i||4&this.__dirty)&&(r.beginPath(),this.buildPath(r,this.shape,!1),this.pathUpdated()),t=r.getBoundingRect()}if(this._rect=t,this.hasStroke()&&this.path&&this.path.len()>0){var o=this._rectStroke||(this._rectStroke=t.clone());if(this.__dirty||n){o.copy(t);var a=e.strokeNoScale?this.getLineScale():1,s=e.lineWidth;if(!this.hasFill()){var l=this.strokeContainThreshold;s=Math.max(s,null==l?4:l)}a>1e-10&&(o.width+=s/a,o.height+=s/a,o.x-=s/a/2,o.y-=s/a/2)}return o}return t},e.prototype.contain=function(t,e){var n=this.transformCoordToLocal(t,e),i=this.getBoundingRect(),r=this.style;if(t=n[0],e=n[1],i.contain(t,e)){var o=this.path;if(this.hasStroke()){var a=r.lineWidth,s=r.strokeNoScale?this.getLineScale():1;if(s>1e-10&&(this.hasFill()||(a=Math.max(a,this.strokeContainThreshold)),function(t,e,n,i){return pd(t,e,!0,n,i)}(o,a/s,t,e)))return!0}if(this.hasFill())return function(t,e,n){return pd(t,0,!1,e,n)}(o,t,e)}return!1},e.prototype.dirtyShape=function(){this.__dirty|=4,this._rect&&(this._rect=null),this._decalEl&&this._decalEl.dirtyShape(),this.markRedraw()},e.prototype.dirty=function(){this.dirtyStyle(),this.dirtyShape()},e.prototype.animateShape=function(t){return this.animate("shape",t)},e.prototype.updateDuringAnimation=function(t){"style"===t?this.dirtyStyle():"shape"===t?this.dirtyShape():this.markRedraw()},e.prototype.attrKV=function(e,n){"shape"===e?this.setShape(n):t.prototype.attrKV.call(this,e,n)},e.prototype.setShape=function(t,e){var n=this.shape;return n||(n=this.shape={}),"string"==typeof t?n[t]=e:Fi(n,t),this.dirtyShape(),this},e.prototype.shapeChanged=function(){return!!(4&this.__dirty)},e.prototype.createStyle=function(t){return Cr(fd,t)},e.prototype._innerSaveToNormal=function(e){t.prototype._innerSaveToNormal.call(this,e);var n=this._normalState;e.shape&&!n.shape&&(n.shape=Fi({},this.shape))},e.prototype._applyStateObj=function(e,n,i,r,o,a){t.prototype._applyStateObj.call(this,e,n,i,r,o,a);var s,l=!(n&&r);if(n&&n.shape?o?r?s=n.shape:(s=Fi({},i.shape),Fi(s,n.shape)):(s=Fi({},r?this.shape:i.shape),Fi(s,n.shape)):l&&(s=i.shape),s)if(o){this.shape=Fi({},this.shape);for(var c={},u=Zi(s),d=0;dc&&(n*=c/(a=n+i),i*=c/a),r+o>c&&(r*=c/(a=r+o),o*=c/a),i+r>u&&(i*=u/(a=i+r),r*=u/a),n+o>u&&(n*=u/(a=n+o),o*=u/a),t.moveTo(s+n,l),t.lineTo(s+c-i,l),0!==i&&t.arc(s+c-i,l+i,i,-Math.PI/2,0),t.lineTo(s+c,l+u-r),0!==r&&t.arc(s+c-r,l+u-r,r,0,Math.PI/2),t.lineTo(s+o,l+u),0!==o&&t.arc(s+o,l+u-o,o,Math.PI/2,Math.PI),t.lineTo(s,l+n),0!==n&&t.arc(s+n,l+n,n,Math.PI,1.5*Math.PI)}(t,e):t.rect(n,i,r,o)},e.prototype.isZeroArea=function(){return!this.shape.width||!this.shape.height},e}(vd);Id.prototype.type="rect";var Dd={fill:"#000"},Pd={},Ld={style:Vi({fill:!0,stroke:!0,fillOpacity:!0,strokeOpacity:!0,lineWidth:!0,fontSize:!0,lineHeight:!0,width:!0,height:!0,textShadowColor:!0,textShadowBlur:!0,textShadowOffsetX:!0,textShadowOffsetY:!0,backgroundColor:!0,padding:!0,borderColor:!0,borderWidth:!0,borderRadius:!0},pu.style)},Ed=function(t){function e(e){var n=t.call(this)||this;return n.type="text",n._children=[],n._defaultStyle=Dd,n.attr(e),n}return S(e,t),e.prototype.childrenRef=function(){return this._children},e.prototype.update=function(){t.prototype.update.call(this),this.styleChanged()&&this._updateSubTexts();for(var e=0;ev&&p){var _=Math.floor(v/h);f=f||m.length>_,y=(m=m.slice(0,_)).length*h}if(r&&u&&null!=g)for(var b=Yc(g,c,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),x={},w=0;w0,k=0;kg&&eu(o,a.substring(g,m),e,f),eu(o,h[2],e,f,h[1]),g=Gc.lastIndex}gd){var N=o.lines.length;A>0?(k.tokens=k.tokens.slice(0,A),S(k,T,M),o.lines=o.lines.slice(0,C+1)):o.lines=o.lines.slice(0,C),o.isTruncated=o.isTruncated||o.lines.length=0&&"right"===(T=_[M]).align;)this._placeToken(T,t,x,f,k,"right",m),w-=T.width,k-=T.width,M--;for(C+=(s-(C-p)-(g-k)-w)/2;S<=M;)T=_[S],this._placeToken(T,t,x,f,C+T.width/2,"center",m),C+=T.width,S++;f+=x}},e.prototype._placeToken=function(t,e,n,i,r,o,a){var s=e.rich[t.styleName]||{};s.text=t.text;var l=t.verticalAlign,c=i+n/2;"top"===l?c=i+t.height/2:"bottom"===l&&(c=i+n-t.height/2),!t.isLineHolder&&qd(s)&&this._renderBackground(s,e,"right"===o?r-t.width:"center"===o?r-t.width/2:r,c-t.height/2,t.width,t.height);var u=!!s.backgroundColor,d=t.textPadding;d&&(r=Wd(r,o,d),c-=t.height/2-d[0]-t.innerHeight/2);var h=this._getOrCreateChild(_d),p=h.createStyle();h.useStyle(p);var f=this._defaultStyle,g=!1,m=0,v=!1,y=Vd("fill"in s?s.fill:"fill"in e?e.fill:(g=!0,f.fill)),_=Fd("stroke"in s?s.stroke:"stroke"in e?e.stroke:u||a||f.autoStroke&&!g?null:(m=2,v=!0,f.stroke)),b=s.textShadowBlur>0||e.textShadowBlur>0;p.text=t.text,p.x=r,p.y=c,b&&(p.shadowBlur=s.textShadowBlur||e.textShadowBlur||0,p.shadowColor=s.textShadowColor||e.textShadowColor||"transparent",p.shadowOffsetX=s.textShadowOffsetX||e.textShadowOffsetX||0,p.shadowOffsetY=s.textShadowOffsetY||e.textShadowOffsetY||0),p.textAlign=o,p.textBaseline="middle",p.font=t.font||bi,p.opacity=hr(s.opacity,e.opacity,1),Hd(p,s),_&&(p.lineWidth=hr(s.lineWidth,e.lineWidth,m),p.lineDash=dr(s.lineDash,e.lineDash),p.lineDashOffset=e.lineDashOffset||0,p.stroke=_),y&&(p.fill=y),h.setBoundingRect(cu(p,t.contentWidth,t.contentHeight,v?0:null))},e.prototype._renderBackground=function(t,e,n,i,r,o){var a,s,l,c=t.backgroundColor,u=t.borderWidth,d=t.borderColor,h=c&&c.image,p=c&&!h,f=t.borderRadius,g=this;if(p||t.lineHeight||u&&d){(a=this._getOrCreateChild(Id)).useStyle(a.createStyle()),a.style.fill=null;var m=a.shape;m.x=n,m.y=i,m.width=r,m.height=o,m.r=f,a.dirtyShape()}if(p)(l=a.style).fill=c||null,l.fillOpacity=dr(t.fillOpacity,1);else if(h){(s=this._getOrCreateChild(wd)).onload=function(){g.dirtyStyle()};var v=s.style;v.image=c.image,v.x=n,v.y=i,v.width=r,v.height=o}u&&d&&((l=a.style).lineWidth=u,l.stroke=d,l.strokeOpacity=dr(t.strokeOpacity,1),l.lineDash=t.borderDash,l.lineDashOffset=t.borderDashOffset||0,a.strokeContainThreshold=0,a.hasFill()&&a.hasStroke()&&(l.strokeFirst=!0,l.lineWidth*=2));var y=(a||s).style;y.shadowBlur=t.shadowBlur||0,y.shadowColor=t.shadowColor||"transparent",y.shadowOffsetX=t.shadowOffsetX||0,y.shadowOffsetY=t.shadowOffsetY||0,y.opacity=hr(t.opacity,e.opacity,1)},e.makeFont=function(t){var e="";return Bd(t)&&(e=[t.fontStyle,t.fontWeight,zd(t.fontSize),t.fontFamily||"sans-serif"].join(" ")),e&&mr(e)||t.textFont||t.font},e}(mu),Nd={left:!0,right:1,center:1},Rd={top:1,bottom:1,middle:1},Od=["fontStyle","fontWeight","fontSize","fontFamily"];function zd(t){return"string"!=typeof t||-1===t.indexOf("px")&&-1===t.indexOf("rem")&&-1===t.indexOf("em")?isNaN(+t)?"12px":t+"px":t}function Hd(t,e){for(var n=0;n=0,o=!1;if(t instanceof vd){var a=Yd(t),s=r&&a.selectFill||a.normalFill,l=r&&a.selectStroke||a.normalStroke;if(oh(s)||oh(l)){var c=(i=i||{}).style||{};"inherit"===c.fill?(o=!0,i=Fi({},i),(c=Fi({},c)).fill=s):!oh(c.fill)&&oh(s)?(o=!0,i=Fi({},i),(c=Fi({},c)).fill=Qa(s)):!oh(c.stroke)&&oh(l)&&(o||(i=Fi({},i),c=Fi({},c)),c.stroke=Qa(l)),i.style=c}}if(i&&null==i.z2){o||(i=Fi({},i));var u=t.z2EmphasisLift;i.z2=t.z2+(null!=u?u:10)}return i}(this,0,e,n);if("blur"===t)return function(t,e,n){var i=Wi(t.currentStates,e)>=0,r=t.style.opacity,o=i?null:function(t,e,n,i){for(var r=t.style,o={},a=0;a0){var o={dataIndex:r,seriesIndex:t.seriesIndex};null!=i&&(o.dataType=i),e.push(o)}})}),e}function Lh(t,e,n){zh(t,!0),fh(t,vh),function(t,e,n){var i=Ud(t);null!=e?(i.focus=e,i.blurScope=n):i.focus&&(i.focus=null)}(t,e,n)}function Eh(t,e,n,i){i?function(t){zh(t,!1)}(t):Lh(t,e,n)}var Nh=["emphasis","blur","select"],Rh={itemStyle:"getItemStyle",lineStyle:"getLineStyle",areaStyle:"getAreaStyle"};function Oh(t,e,n,i){n=n||"itemStyle";for(var r=0;r1&&(a*=qh(f),s*=qh(f));var g=(r===o?-1:1)*qh((a*a*(s*s)-a*a*(p*p)-s*s*(h*h))/(a*a*(p*p)+s*s*(h*h)))||0,m=g*a*p/s,v=g*-s*h/a,y=(t+n)/2+Gh(d)*m-Uh(d)*v,_=(e+i)/2+Uh(d)*m+Gh(d)*v,b=Kh([1,0],[(h-m)/a,(p-v)/s]),x=[(h-m)/a,(p-v)/s],w=[(-1*h-m)/a,(-1*p-v)/s],S=Kh(x,w);if(Zh(x,w)<=-1&&(S=Xh),Zh(x,w)>=1&&(S=0),S<0){var C=Math.round(S/Xh*1e6)/1e6;S=2*Xh+C%2*Xh}u.addData(c,y,_,a,s,b,S,d,o)}var Jh=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,tp=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;var ep=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e.prototype.applyTransform=function(t){},e}(vd);function np(t){return null!=t.setData}function ip(t,e){var n=function(t){var e=new Zu;if(!t)return e;var n,i=0,r=0,o=i,a=r,s=Zu.CMD,l=t.match(Jh);if(!l)return e;for(var c=0;cD*D+P*P&&(C=M,k=T),{cx:C,cy:k,x0:-u,y0:-d,x1:C*(r/x-1),y1:k*(r/x-1)}}function bp(t,e){var n,i=mp(e.r,0),r=mp(e.r0||0,0),o=i>0;if(o||r>0){if(o||(i=r,r=0),r>i){var a=i;i=r,r=a}var s=e.startAngle,l=e.endAngle;if(!isNaN(s)&&!isNaN(l)){var c=e.cx,u=e.cy,d=!!e.clockwise,h=fp(l-s),p=h>cp&&h%cp;if(p>yp&&(h=p),i>yp)if(h>cp-yp)t.moveTo(c+i*dp(s),u+i*up(s)),t.arc(c,u,i,s,l,!d),r>yp&&(t.moveTo(c+r*dp(l),u+r*up(l)),t.arc(c,u,r,l,s,d));else{var f=void 0,g=void 0,m=void 0,v=void 0,y=void 0,_=void 0,b=void 0,x=void 0,w=void 0,S=void 0,C=void 0,k=void 0,M=void 0,T=void 0,A=void 0,I=void 0,D=i*dp(s),P=i*up(s),L=r*dp(l),E=r*up(l),N=h>yp;if(N){var R=e.cornerRadius;R&&(n=function(t){var e;if(Ji(t)){var n=t.length;if(!n)return t;e=1===n?[t[0],t[0],0,0]:2===n?[t[0],t[0],t[1],t[1]]:3===n?t.concat(t[2]):t}else e=[t,t,t,t];return e}(R),f=n[0],g=n[1],m=n[2],v=n[3]);var O=fp(i-r)/2;if(y=vp(O,m),_=vp(O,v),b=vp(O,f),x=vp(O,g),C=w=mp(y,_),k=S=mp(b,x),(w>yp||S>yp)&&(M=i*dp(l),T=i*up(l),A=r*dp(s),I=r*up(s),hyp){var j=vp(m,C),q=vp(v,C),U=_p(A,I,D,P,i,j,d),G=_p(M,T,L,E,i,q,d);t.moveTo(c+U.cx+U.x0,u+U.cy+U.y0),C0&&t.arc(c+U.cx,u+U.cy,j,pp(U.y0,U.x0),pp(U.y1,U.x1),!d),t.arc(c,u,i,pp(U.cy+U.y1,U.cx+U.x1),pp(G.cy+G.y1,G.cx+G.x1),!d),q>0&&t.arc(c+G.cx,u+G.cy,q,pp(G.y1,G.x1),pp(G.y0,G.x0),!d))}else t.moveTo(c+D,u+P),t.arc(c,u,i,s,l,!d);else t.moveTo(c+D,u+P);if(r>yp&&N)if(k>yp){j=vp(f,k),U=_p(L,E,M,T,r,-(q=vp(g,k)),d),G=_p(D,P,A,I,r,-j,d);t.lineTo(c+U.cx+U.x0,u+U.cy+U.y0),k0&&t.arc(c+U.cx,u+U.cy,q,pp(U.y0,U.x0),pp(U.y1,U.x1),!d),t.arc(c,u,r,pp(U.cy+U.y1,U.cx+U.x1),pp(G.cy+G.y1,G.cx+G.x1),d),j>0&&t.arc(c+G.cx,u+G.cy,j,pp(G.y1,G.x1),pp(G.y0,G.x0),!d))}else t.lineTo(c+L,u+E),t.arc(c,u,r,l,s,d);else t.lineTo(c+L,u+E)}else t.moveTo(c,u);t.closePath()}}}var xp=function(){this.cx=0,this.cy=0,this.r0=0,this.r=0,this.startAngle=0,this.endAngle=2*Math.PI,this.clockwise=!0,this.cornerRadius=0},wp=function(t){function e(e){return t.call(this,e)||this}return S(e,t),e.prototype.getDefaultShape=function(){return new xp},e.prototype.buildPath=function(t,e){bp(t,e)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(vd);wp.prototype.type="sector";var Sp=function(){this.cx=0,this.cy=0,this.r=0,this.r0=0},Cp=function(t){function e(e){return t.call(this,e)||this}return S(e,t),e.prototype.getDefaultShape=function(){return new Sp},e.prototype.buildPath=function(t,e){var n=e.cx,i=e.cy,r=2*Math.PI;t.moveTo(n+e.r,i),t.arc(n,i,e.r,0,r,!1),t.moveTo(n+e.r0,i),t.arc(n,i,e.r0,0,r,!0)},e}(vd);function kp(t,e,n){var i=e.smooth,r=e.points;if(r&&r.length>=2){if(i){var o=function(t,e,n,i){var r,o,a,s,l=[],c=[],u=[],d=[];if(i){a=[1/0,1/0],s=[-1/0,-1/0];for(var h=0,p=t.length;hGp[1]){if(r=!1,Xp.negativeSize||n)return r;var s=qp(Gp[0]-Up[1]),l=qp(Up[0]-Gp[1]);Wp(s,l)>Zp.len()&&(s=l||!Xp.bidirectional)&&(yo.scale(Yp,a,-l*i),Xp.useDir&&Xp.calcDirMTV()))}}return r},t.prototype._getProjMinMaxOnAxis=function(t,e,n){for(var i=this._axes[t],r=this._origin,o=e[0].dot(i)+r[t],a=o,s=o,l=1;l0){var d={duration:u.duration,delay:u.delay||0,easing:u.easing,done:o,force:!!o||!!a,setToFinal:!c,scope:t,during:a};l?e.animateFrom(n,d):e.animateTo(n,d)}else e.stopAnimation(),!l&&e.attr(n),a&&a(1),o&&o()}function nf(t,e,n,i,r,o){ef("update",t,e,n,i,r,o)}function rf(t,e,n,i,r,o){ef("enter",t,e,n,i,r,o)}function of(t){if(!t.__zr)return!0;for(var e=0;e=-1e-6)return!1;var f=t-r,g=e-o,m=kf(f,g,c,u)/p;if(m<0||m>1)return!1;var v=kf(f,g,d,h)/p;return!(v<0||v>1)}function kf(t,e,n,i){return t*i-n*e}function Mf(t,e,n,i,r){return null==e||(ir(e)?Tf[0]=Tf[1]=Tf[2]=Tf[3]=e:(Tf[0]=e[0],Tf[1]=e[1],Tf[2]=e[2],Tf[3]=e[3]),i&&(Tf[0]=Vl(0,Tf[0]),Tf[1]=Vl(0,Tf[1]),Tf[2]=Vl(0,Tf[2]),Tf[3]=Vl(0,Tf[3])),n&&(Tf[0]=-Tf[0],Tf[1]=-Tf[1],Tf[2]=-Tf[2],Tf[3]=-Tf[3]),Af(t,Tf,"x","width",3,1,r&&r[0]||0),Af(t,Tf,"y","height",0,2,r&&r[1]||0)),t}var Tf=[0,0,0,0];function Af(t,e,n,i,r,o,a){var s=e[o]+e[r],l=t[i];t[i]+=s,a=Vl(0,Fl(a,l)),t[i]=0?-e[r]:e[o]>=0?l+e[o]:Wl(s)>1e-8?(l-a)*e[r]/s:0):t[n]-=e[r]}function If(t){var e=t.itemTooltipOption,n=t.componentModel,i=t.itemName,r=er(e)?{formatter:e}:e,o=n.mainType,a=n.componentIndex,s={componentType:o,name:i,$vars:["name"]};s[o+"Index"]=a;var l=t.formatterParamsExtra;l&&Ui(Zi(l),function(t){kr(s,t)||(s[t]=l[t],s.$vars.push(t))});var c=Ud(t.el);c.componentMainType=o,c.componentIndex=a,c.tooltipConfig={name:i,option:Vi({content:i,encodeHTMLContent:!0,formatterParams:s},r)}}function Df(t,e){var n;t.isGroup&&(n=e(t)),n||t.traverse(e)}function Pf(t,e){if(t)if(Ji(t))for(var n=0;ne&&(e=i),ie&&(n=e=0),{min:n,max:e}},clipPointsByRect:function(t,e){return Gi(t,function(t){var n=t[0];n=Vl(n,e.x),n=Fl(n,e.x+e.width);var i=t[1];return i=Vl(i,e.y),[n,i=Fl(i,e.y+e.height)]})},clipRectByRect:function(t,e){var n=Vl(t.x,e.x),i=Fl(t.x+t.width,e.x+e.width),r=Vl(t.y,e.y),o=Fl(t.y+t.height,e.y+e.height);if(i>=n&&o>=r)return{x:n,y:r,width:i-n,height:o-r}},createIcon:Sf,ensureCopyRect:Nf,ensureCopyTransform:Rf,expandOrShrinkRect:Mf,extendPath:function(t,e){return df(t,e)},extendShape:function(t){return vd.extend(t)},getShapeClass:function(t){if(lf.hasOwnProperty(t))return lf[t]},getTransform:function(t,e){for(var n=ho([]);t&&t!==e;)fo(n,t.getLocalTransform(),n),t=t.parent;return n},groupTransition:wf,initProps:rf,isBoundingRectAxisAligned:Lf,isElementRemoved:of,lineLineIntersect:Cf,linePolygonIntersect:function(t,e,n,i,r){for(var o=0,a=r[r.length-1];oWl(o[1])?o[0]>0?"right":"left":o[1]>0?"bottom":"top"},traverseElements:Pf,traverseUpdateZ:zf,updateProps:nf}),$f={};function Ff(t,e,n){var i,r=t.labelFetcher,o=t.labelDataIndex,a=t.labelDimIndex,s=e.normal;r&&(i=r.getFormattedLabel(o,"normal",null,a,s&&s.get("formatter"),null!=n?{interpolatedValue:n}:null)),null==i&&(i=tr(t.defaultText)?t.defaultText(o,t,n):t.defaultText);for(var l={normal:i},c=0;c-1?pg:gg;function _g(t,e){t=t.toUpperCase(),vg[t]=new ug(e),mg[t]=e}_g(fg,{time:{month:["January","February","March","April","May","June","July","August","September","October","November","December"],monthAbbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayOfWeekAbbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},legend:{selector:{all:"All",inverse:"Inv"}},toolbox:{brush:{title:{rect:"Box Select",polygon:"Lasso Select",lineX:"Horizontally Select",lineY:"Vertically Select",keep:"Keep Selections",clear:"Clear Selections"}},dataView:{title:"Data View",lang:["Data View","Close","Refresh"]},dataZoom:{title:{zoom:"Zoom",back:"Zoom Reset"}},magicType:{title:{line:"Switch to Line Chart",bar:"Switch to Bar Chart",stack:"Stack",tiled:"Tile"}},restore:{title:"Restore"},saveAsImage:{title:"Save as Image",lang:["Right Click to Save Image"]}},series:{typeNames:{pie:"Pie chart",bar:"Bar chart",line:"Line chart",scatter:"Scatter plot",effectScatter:"Ripple scatter plot",radar:"Radar chart",tree:"Tree",treemap:"Treemap",boxplot:"Boxplot",candlestick:"Candlestick",k:"K line chart",heatmap:"Heat map",map:"Map",parallel:"Parallel coordinate map",lines:"Line graph",graph:"Relationship graph",sankey:"Sankey diagram",funnel:"Funnel chart",gauge:"Gauge",pictorialBar:"Pictorial bar",themeRiver:"Theme River Map",sunburst:"Sunburst",custom:"Custom chart",chart:"Chart"}},aria:{general:{withTitle:'This is a chart about "{title}"',withoutTitle:"This is a chart"},series:{single:{prefix:"",withName:" with type {seriesType} named {seriesName}.",withoutName:" with type {seriesType}."},multiple:{prefix:". It consists of {seriesCount} series count.",withName:" The {seriesId} series is a {seriesType} representing {seriesName}.",withoutName:" The {seriesId} series is a {seriesType}.",separator:{middle:"",end:""}}},data:{allData:"The data is as follows: ",partialData:"The first {displayCnt} items are: ",withName:"the data for {name} is {value}",withoutName:"{value}",separator:{middle:", ",end:". "}}}}),_g(pg,{time:{month:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],monthAbbr:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],dayOfWeek:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],dayOfWeekAbbr:["日","一","二","三","四","五","六"]},legend:{selector:{all:"全选",inverse:"反选"}},toolbox:{brush:{title:{rect:"矩形选择",polygon:"圈选",lineX:"横向选择",lineY:"纵向选择",keep:"保持选择",clear:"清除选择"}},dataView:{title:"数据视图",lang:["数据视图","关闭","刷新"]},dataZoom:{title:{zoom:"区域缩放",back:"区域缩放还原"}},magicType:{title:{line:"切换为折线图",bar:"切换为柱状图",stack:"切换为堆叠",tiled:"切换为平铺"}},restore:{title:"还原"},saveAsImage:{title:"保存为图片",lang:["右键另存为图片"]}},series:{typeNames:{pie:"饼图",bar:"柱状图",line:"折线图",scatter:"散点图",effectScatter:"涟漪散点图",radar:"雷达图",tree:"树图",treemap:"矩形树图",boxplot:"箱型图",candlestick:"K线图",k:"K线图",heatmap:"热力图",map:"地图",parallel:"平行坐标图",lines:"线图",graph:"关系图",sankey:"桑基图",funnel:"漏斗图",gauge:"仪表盘图",pictorialBar:"象形柱图",themeRiver:"主题河流图",sunburst:"旭日图",custom:"自定义图表",chart:"图表"}},aria:{general:{withTitle:"这是一个关于“{title}”的图表。",withoutTitle:"这是一个图表,"},series:{single:{prefix:"",withName:"图表类型是{seriesType},表示{seriesName}。",withoutName:"图表类型是{seriesType}。"},multiple:{prefix:"它由{seriesCount}个图表系列组成。",withName:"第{seriesId}个系列是一个表示{seriesName}的{seriesType},",withoutName:"第{seriesId}个系列是一个{seriesType},",separator:{middle:";",end:"。"}}},data:{allData:"其数据是——",partialData:"其中,前{displayCnt}项是——",withName:"{name}的数据是{value}",withoutName:"{value}",separator:{middle:",",end:""}}}});function bg(){return null}var xg=1e3,wg=6e4,Sg=36e5,Cg=864e5,kg=31536e6,Mg={year:/({yyyy}|{yy})/,month:/({MMMM}|{MMM}|{MM}|{M})/,day:/({dd}|{d})/,hour:/({HH}|{H}|{hh}|{h})/,minute:/({mm}|{m})/,second:/({ss}|{s})/,millisecond:/({SSS}|{S})/},Tg={year:"{yyyy}",month:"{MMM}",day:"{d}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{HH}:{mm}:{ss} {SSS}"},Ag="{yyyy}-{MM}-{dd}",Ig={year:"{yyyy}",month:"{yyyy}-{MM}",day:Ag,hour:Ag+" "+Tg.hour,minute:Ag+" "+Tg.minute,second:Ag+" "+Tg.second,millisecond:"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}"},Dg=["year","month","day","hour","minute","second","millisecond"],Pg=["year","half-year","quarter","month","week","half-week","day","half-day","quarter-day","hour","minute","second","millisecond"];function Lg(t){return er(t)||tr(t)?t:function(t){t=t||{};var e={},n=!0;return Ui(Dg,function(e){n&&(n=null==t[e])}),Ui(Dg,function(i,r){var o=t[i];e[i]={};for(var a=null,s=r;s>=0;s--){var l=Dg[s],c=rr(o)&&!Ji(o)?o[l]:o,u=void 0;Ji(c)?a=(u=c.slice())[0]||"":er(c)?u=[a=c]:(null==a?a=Tg[i]:Mg[l].test(a)||(a=e[l][l][0]+" "+a),u=[a],n&&(u[1]="{primary|"+a+"}")),e[i][l]=u}}),e}(t)}function Eg(t,e){return"0000".substr(0,e-(t+="").length)+t}function Ng(t){switch(t){case"half-year":case"quarter":return"month";case"week":case"half-week":return"day";case"half-day":case"quarter-day":return"hour";default:return t}}function Rg(t){return t===Ng(t)}function Og(t,e,n,i){var r=Jl(t),o=r[Bg(n)](),a=r[$g(n)]()+1,s=Math.floor((a-1)/3)+1,l=r[Fg(n)](),c=r["get"+(n?"UTC":"")+"Day"](),u=r[Vg(n)](),d=(u-1)%12+1,h=r[Wg(n)](),p=r[jg(n)](),f=r[qg(n)](),g=u>=12?"pm":"am",m=g.toUpperCase(),v=i instanceof ug?i:function(t){return vg[t]}(i||yg)||vg[gg],y=v.getModel("time"),_=y.get("month"),b=y.get("monthAbbr"),x=y.get("dayOfWeek"),w=y.get("dayOfWeekAbbr");return(e||"").replace(/{a}/g,g+"").replace(/{A}/g,m+"").replace(/{yyyy}/g,o+"").replace(/{yy}/g,Eg(o%100+"",2)).replace(/{Q}/g,s+"").replace(/{MMMM}/g,_[a-1]).replace(/{MMM}/g,b[a-1]).replace(/{MM}/g,Eg(a,2)).replace(/{M}/g,a+"").replace(/{dd}/g,Eg(l,2)).replace(/{d}/g,l+"").replace(/{eeee}/g,x[c]).replace(/{ee}/g,w[c]).replace(/{e}/g,c+"").replace(/{HH}/g,Eg(u,2)).replace(/{H}/g,u+"").replace(/{hh}/g,Eg(d+"",2)).replace(/{h}/g,d+"").replace(/{mm}/g,Eg(h,2)).replace(/{m}/g,h+"").replace(/{ss}/g,Eg(p,2)).replace(/{s}/g,p+"").replace(/{SSS}/g,Eg(f,3)).replace(/{S}/g,f+"")}function zg(t,e){var n=Jl(t),i=n[$g(e)]()+1,r=n[Fg(e)](),o=n[Vg(e)](),a=n[Wg(e)](),s=n[jg(e)](),l=0===n[qg(e)](),c=l&&0===s,u=c&&0===a,d=u&&0===o,h=d&&1===r;return h&&1===i?"year":h?"month":d?"day":u?"hour":c?"minute":l?"second":"millisecond"}function Hg(t,e,n){switch(e){case"year":t[Gg(n)](0);case"month":t[Xg(n)](1);case"day":t[Yg(n)](0);case"hour":t[Zg(n)](0);case"minute":t[Kg(n)](0);case"second":t[Qg(n)](0)}return t}function Bg(t){return t?"getUTCFullYear":"getFullYear"}function $g(t){return t?"getUTCMonth":"getMonth"}function Fg(t){return t?"getUTCDate":"getDate"}function Vg(t){return t?"getUTCHours":"getHours"}function Wg(t){return t?"getUTCMinutes":"getMinutes"}function jg(t){return t?"getUTCSeconds":"getSeconds"}function qg(t){return t?"getUTCMilliseconds":"getMilliseconds"}function Ug(t){return t?"setUTCFullYear":"setFullYear"}function Gg(t){return t?"setUTCMonth":"setMonth"}function Xg(t){return t?"setUTCDate":"setDate"}function Yg(t){return t?"setUTCHours":"setHours"}function Zg(t){return t?"setUTCMinutes":"setMinutes"}function Kg(t){return t?"setUTCSeconds":"setSeconds"}function Qg(t){return t?"setUTCMilliseconds":"setMilliseconds"}function Jg(t){if(isNaN(nc(t)))return er(t)?t:"-";var e=(t+"").split(".");return e[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(e.length>1?"."+e[1]:"")}function tm(t,e){return t=(t||"").toLowerCase().replace(/-(.)/g,function(t,e){return e.toUpperCase()}),e&&t&&(t=t.charAt(0).toUpperCase()+t.slice(1)),t}var em=fr;function nm(t,e,n){function i(t){return t&&mr(t)?t:"-"}function r(t){return!(null==t||isNaN(t)||!isFinite(t))}var o="time"===e,a=t instanceof Date;if(o||a){var s=o?Jl(t):t;if(!isNaN(+s))return Og(s,"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}",n);if(a)return"-"}if("ordinal"===e)return nr(t)?i(t):ir(t)&&r(t)?t+"":"-";var l=nc(t);return r(l)?Jg(l):nr(t)?i(t):"boolean"==typeof t?t+"":"-"}var im=["a","b","c","d","e","f","g"],rm=function(t,e){return"{"+t+(null==e?"":e)+"}"};function om(t,e,n){Ji(e)||(e=[e]);var i=e.length;if(!i)return"";for(var r=e[0].$vars||[],o=0;oi||l.newline?(o=0,u=g,a+=s+n,s=h.height):s=Math.max(s,h.height)}else{var m=h.height+(f?-f.y+h.y:0);(d=a+m)>r||l.newline?(o+=s+n,a=0,d=m,s=h.width):s=Math.max(s,h.width)}l.newline||(l.x=o,l.y=a,l.markRedraw(),"horizontal"===t?o=u+n:a=d+n)})}function xm(t,e,n){n=em(n||0);var i=e.width,r=e.height,o=ql(t.left,i),a=ql(t.top,r),s=ql(t.right,i),l=ql(t.bottom,r),c=ql(t.width,i),u=ql(t.height,r),d=n[2]+n[0],h=n[1]+n[3],p=t.aspect;switch(isNaN(c)&&(c=i-s-h-o),isNaN(u)&&(u=r-l-d-a),null!=p&&(isNaN(c)&&isNaN(u)&&(p>i/r?c=.8*i:u=.8*r),isNaN(c)&&(c=p*u),isNaN(u)&&(u=c/p)),isNaN(o)&&(o=i-s-c-h),isNaN(a)&&(a=r-l-u-d),t.left||t.right){case"center":o=i/2-c/2-n[3];break;case"right":o=i-c-h}switch(t.top||t.bottom){case"middle":case"center":a=r/2-u/2-n[0];break;case"bottom":a=r-u-d}o=o||0,a=a||0,isNaN(c)&&(c=i-h-o-(s||0)),isNaN(u)&&(u=r-d-a-(l||0));var f=new Lo((e.x||0)+o+n[3],(e.y||0)+a+n[0],c,u);return f.margin=n,f}Qi(bm,"vertical"),Qi(bm,"horizontal");var wm=1;function Sm(t,e,n){var i,r,o,a,s=t.boxCoordinateSystem;if(s){var l=function(t){var e=t.getShallow("coord",!0),n=um;if(null==e){var i=hm.get(t.type);i&&i.getCoord2&&(n=dm,e=i.getCoord2(t))}return{coord:e,from:n}}(t),c=l.coord,u=l.from;if(s.dataToLayout){o=wm,a=u;var d=s.dataToLayout(c);i=d.contentRect||d.rect}}return null==o&&(o=wm),o===wm&&(i||(i={x:0,y:0,width:e.getWidth(),height:e.getHeight()}),r=[i.x+i.width/2,i.y+i.height/2]),{type:o,refContainer:i,refPoint:r,boxCoordFrom:a}}function Cm(t){var e=t.layoutMode||t.constructor.layoutMode;return rr(e)?e:e?{type:e}:null}function km(t,e,n){var i=n&&n.ignoreSize;!Ji(i)&&(i=[i,i]);var r=a(_m[0],0),o=a(_m[1],1);function a(n,r){var o={},a=0,l={},c=0;if(vm(n,function(e){l[e]=t[e]}),vm(n,function(t){kr(e,t)&&(o[t]=l[t]=e[t]),s(o,t)&&a++,s(l,t)&&c++}),i[r])return s(e,n[1])?l[n[2]]=null:s(e,n[2])&&(l[n[1]]=null),l;if(2!==c&&a){if(a>=2)return o;for(var u=0;u=0;a--)o=$i(o,n[a],!0);e.defaultOption=o}return e.defaultOption},e.prototype.getReferringComponents=function(t,e){var n=t+"Index",i=t+"Id";return Ac(this.ecModel,t,{index:this.get(n,!0),id:this.get(i,!0)},e)},e.prototype.getBoxLayoutParams=function(){return e=!1,{left:(t=this).getShallow("left",e),top:t.getShallow("top",e),right:t.getShallow("right",e),bottom:t.getShallow("bottom",e),width:t.getShallow("width",e),height:t.getShallow("height",e)};var t,e},e.prototype.getZLevelKey=function(){return""},e.prototype.setZLevel=function(t){this.option.zlevel=t},e.protoInitialize=((n=e.prototype).type="component",n.id="",n.name="",n.mainType="",n.subType="",void(n.componentIndex=0)),e}(ug);Nc(Am,ug),Hc(Am),function(t){var e={};t.registerSubTypeDefaulter=function(t,n){var i=Lc(t);e[i.main]=n},t.determineSubType=function(n,i){var r=i.type;if(!r){var o=Lc(n).main;t.hasSubTypes(n)&&e[o]&&(r=e[o](i))}return r}}(Am),function(t,e){function n(t,e){return t[e]||(t[e]={predecessor:[],successor:[]}),t[e]}t.topologicalTravel=function(t,i,r,o){if(t.length){var a=function(t){var i={},r=[];return Ui(t,function(o){var a=n(i,o),s=function(t,e){var n=[];return Ui(t,function(t){Wi(e,t)>=0&&n.push(t)}),n}(a.originalDeps=e(o),t);a.entryCount=s.length,0===a.entryCount&&r.push(o),Ui(s,function(t){Wi(a.predecessor,t)<0&&a.predecessor.push(t);var e=n(i,t);Wi(e.successor,t)<0&&e.successor.push(o)})}),{graph:i,noEntryList:r}}(i),s=a.graph,l=a.noEntryList,c={};for(Ui(t,function(t){c[t]=!0});l.length;){var u=l.pop(),d=s[u],h=!!c[u];h&&(r.call(o,u,d.originalDeps.slice()),delete c[u]),Ui(d.successor,h?f:p)}Ui(c,function(){throw new Error("")})}function p(t){s[t].entryCount--,0===s[t].entryCount&&l.push(t)}function f(t){c[t]=!0,p(t)}}}(Am,function(t){var e=[];Ui(Am.getClassesByMainType(t),function(t){e=e.concat(t.dependencies||t.prototype.dependencies||[])}),e=Gi(e,function(t){return Lc(t).main}),"dataset"!==t&&Wi(e,"dataset")<=0&&e.unshift("dataset");return e});var Im={color:{},darkColor:{},size:{}},Dm=Im.color={theme:["#5070dd","#b6d634","#505372","#ff994d","#0ca8df","#ffd10a","#fb628b","#785db0","#3fbe95"],neutral00:"#fff",neutral05:"#f4f7fd",neutral10:"#e8ebf0",neutral15:"#dbdee4",neutral20:"#cfd2d7",neutral25:"#c3c5cb",neutral30:"#b7b9be",neutral35:"#aaacb2",neutral40:"#9ea0a5",neutral45:"#929399",neutral50:"#86878c",neutral55:"#797b7f",neutral60:"#6d6e73",neutral65:"#616266",neutral70:"#54555a",neutral75:"#48494d",neutral80:"#3c3c41",neutral85:"#303034",neutral90:"#232328",neutral95:"#17171b",neutral99:"#000",accent05:"#eff1f9",accent10:"#e0e4f2",accent15:"#d0d6ec",accent20:"#c0c9e6",accent25:"#b1bbdf",accent30:"#a1aed9",accent35:"#91a0d3",accent40:"#8292cc",accent45:"#7285c6",accent50:"#6578ba",accent55:"#5c6da9",accent60:"#536298",accent65:"#4a5787",accent70:"#404c76",accent75:"#374165",accent80:"#2e3654",accent85:"#252b43",accent90:"#1b2032",accent95:"#121521",transparent:"rgba(0,0,0,0)",highlight:"rgba(255,231,130,0.8)"};for(var Pm in Fi(Dm,{primary:Dm.neutral80,secondary:Dm.neutral70,tertiary:Dm.neutral60,quaternary:Dm.neutral50,disabled:Dm.neutral20,border:Dm.neutral30,borderTint:Dm.neutral20,borderShade:Dm.neutral40,background:Dm.neutral05,backgroundTint:"rgba(234,237,245,0.5)",backgroundTransparent:"rgba(255,255,255,0)",backgroundShade:Dm.neutral10,shadow:"rgba(0,0,0,0.2)",shadowTint:"rgba(129,130,136,0.2)",axisLine:Dm.neutral70,axisLineTint:Dm.neutral40,axisTick:Dm.neutral70,axisTickMinor:Dm.neutral60,axisLabel:Dm.neutral70,axisSplitLine:Dm.neutral15,axisMinorSplitLine:Dm.neutral05}),Dm)if(Dm.hasOwnProperty(Pm)){var Lm=Dm[Pm];"theme"===Pm?Im.darkColor.theme=Dm.theme.slice():"highlight"===Pm?Im.darkColor.highlight="rgba(255,231,130,0.4)":0===Pm.indexOf("accent")?Im.darkColor[Pm]=Xa(Lm,0,function(t){return.5*t},function(t){return Math.min(1,1.3-t)}):Im.darkColor[Pm]=Xa(Lm,0,function(t){return.9*t},function(t){return 1-Math.pow(t,1.5)})}Im.size={xxs:2,xs:5,s:10,m:15,l:20,xl:30,xxl:40,xxxl:50};var Em="";"undefined"!=typeof navigator&&(Em=navigator.platform||"");var Nm="rgba(0, 0, 0, 0.2)",Rm=Im.color.theme[0],Om=Xa(Rm,0,null,.9),zm={darkMode:"auto",colorBy:"series",color:Im.color.theme,gradientColor:[Om,Rm],aria:{decal:{decals:[{color:Nm,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:Nm,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:Nm,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:Nm,dashArrayX:[[6,6],[0,6,6,0]],dashArrayY:[6,0]},{color:Nm,dashArrayX:[[1,0],[1,6]],dashArrayY:[1,0,6,0],rotation:Math.PI/4},{color:Nm,symbol:"triangle",dashArrayX:[[9,9],[0,9,9,0]],dashArrayY:[7,2],symbolSize:.75}]}},textStyle:{fontFamily:Em.match(/^Win/)?"Microsoft YaHei":"sans-serif",fontSize:12,fontStyle:"normal",fontWeight:"normal"},blendMode:null,stateAnimation:{duration:300,easing:"cubicOut"},animation:"auto",animationDuration:1e3,animationDurationUpdate:500,animationEasing:"cubicInOut",animationEasingUpdate:"cubicInOut",animationThreshold:2e3,progressiveThreshold:3e3,progressive:400,hoverLayerThreshold:3e3,useUTC:!1},Hm=Sr(["tooltip","label","itemName","itemId","itemGroupId","itemChildGroupId","seriesName"]),Bm="original",$m="arrayRows",Fm="objectRows",Vm="keyedColumns",Wm="typedArray",jm="unknown",qm="column",Um="row",Gm=1,Xm=2,Ym=3,Zm=Sc();function Km(t,e,n){var i={},r=Qm(e);if(!r||!t)return i;var o,a,s=[],l=[],c=e.ecModel,u=Zm(c).datasetMap,d=r.uid+"_"+n.seriesLayoutBy;Ui(t=t.slice(),function(e,n){var r=rr(e)?e:t[n]={name:e};"ordinal"===r.type&&null==o&&(o=n,a=f(r)),i[r.name]=[]});var h=u.get(d)||u.set(d,{categoryWayDim:a,valueWayDim:0});function p(t,e,n){for(var i=0;ie)return t[i];return t[n-1]}(i,a):n;if(u=u||n,!u||!u.length)return;var d=u[l];r&&(c[r]=d);return s.paletteIdx=(l+1)%u.length,d}(this,ev,i,r,t,e,n)},t.prototype.clearColorPalette=function(){!function(t,e){e(t).paletteIdx=0,e(t).paletteNameMap={}}(this,ev)},t}();var av="\0_ec_inner",sv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e.prototype.init=function(t,e,n,i,r,o){i=i||{},this.option=null,this._theme=new ug(i),this._locale=new ug(r),this._optionManager=o},e.prototype.setOption=function(t,e,n){var i=uv(e);this._optionManager.setOption(t,n,i),this._resetOption(null,i)},e.prototype.resetOption=function(t,e){return this._resetOption(t,uv(e))},e.prototype._resetOption=function(t,e){var n=!1,i=this._optionManager;if(!t||"recreate"===t){var r=i.mountOption("recreate"===t);this.option&&"recreate"!==t?(this.restoreData(),this._mergeOption(r,e)):rv(this,r),n=!0}if("timeline"!==t&&"media"!==t||this.restoreData(),!t||"recreate"===t||"timeline"===t){var o=i.getTimelineOption(this);o&&(n=!0,this._mergeOption(o,e))}if(!t||"recreate"===t||"media"===t){var a=i.getMediaOption(this);a.length&&Ui(a,function(t){n=!0,this._mergeOption(t,e)},this)}return n},e.prototype.mergeOption=function(t){this._mergeOption(t,null)},e.prototype._mergeOption=function(t,e){var n=this.option,i=this._componentsMap,r=this._componentsCount,o=[],a=Sr(),s=e&&e.replaceMergeMainTypeMap;Zm(this).datasetMap=Sr(),Ui(t,function(t,e){null!=t&&(Am.hasClass(e)?e&&(o.push(e),a.set(e,!0)):n[e]=null==n[e]?Bi(t):$i(n[e],t,!0))}),s&&s.each(function(t,e){Am.hasClass(e)&&!a.get(e)&&(o.push(e),a.set(e,!0))}),Am.topologicalTravel(o,Am.getAllClassMainTypes(),function(e){var o=function(t,e,n){var i=tv.get(e);if(!i)return n;var r=i(t);return r?n.concat(r):n}(this,e,dc(t[e])),a=i.get(e),l=a?s&&s.get(e)?"replaceMerge":"normalMerge":"replaceAll",c=mc(a,o,l);(function(t,e,n){Ui(t,function(t){var i=t.newOption;rr(i)&&(t.keyInfo.mainType=e,t.keyInfo.subType=function(t,e,n,i){return e.type?e.type:n?n.subType:i.determineSubType(t,e)}(e,i,t.existing,n))})})(c,e,Am),n[e]=null,i.set(e,null),r.set(e,0);var u,d=[],h=[],p=0;Ui(c,function(t,n){var i=t.existing,r=t.newOption;if(r){var o="series"===e,a=Am.getClass(e,t.keyInfo.subType,!o);if(!a)return;if("tooltip"===e){if(u)return;u=!0}if(i&&i.constructor===a)i.name=t.keyInfo.name,i.mergeOption(r,this),i.optionUpdated(r,!1);else{var s=Fi({componentIndex:n},t.keyInfo);Fi(i=new a(r,this,this,s),s),t.brandNew&&(i.__requireNewView=!0),i.init(r,this,this),i.optionUpdated(null,!0)}}else i&&(i.mergeOption({},this),i.optionUpdated({},!1));i?(d.push(i.option),h.push(i),p++):(d.push(void 0),h.push(void 0))},this),n[e]=d,i.set(e,h),r.set(e,p),"series"===e&&nv(this)},this),this._seriesIndices||nv(this)},e.prototype.getOption=function(){var t=Bi(this.option);return Ui(t,function(e,n){if(Am.hasClass(n)){for(var i=dc(e),r=i.length,o=!1,a=r-1;a>=0;a--)i[a]&&!xc(i[a])?o=!0:(i[a]=null,!o&&r--);i.length=r,t[n]=i}}),delete t[av],t},e.prototype.setTheme=function(t){this._theme=new ug(t),this._resetOption("recreate",null)},e.prototype.getTheme=function(){return this._theme},e.prototype.getLocaleModel=function(){return this._locale},e.prototype.setUpdatePayload=function(t){this._payload=t},e.prototype.getUpdatePayload=function(){return this._payload},e.prototype.getComponent=function(t,e){var n=this._componentsMap.get(t);if(n){var i=n[e||0];if(i)return i;if(null==e)for(var r=0;r=e:"max"===n?t<=e:t===e})(i[a],t,o)||(r=!1)}}),r}var mv=Ui,vv=rr,yv=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"];function _v(t){var e=t&&t.itemStyle;if(e)for(var n=0,i=yv.length;nc&&(c=p)}s[0]=l,s[1]=c}},i=function(){return this._data?this._data.length/this._dimSize:0};function r(t){for(var e=0;e=0&&(s=o.interpolatedValue[l])}return null!=s?s+"":""}):void 0},t.prototype.getRawValue=function(t,e){return ly(this.getData(e),t)},t.prototype.formatTooltip=function(t,e,n){},t}();function dy(t){var e,n;return rr(t)?t.type&&(n=t):e=t,{text:e,frag:n}}function hy(t){return new py(t)}var py=function(){function t(t){t=t||{},this._reset=t.reset,this._plan=t.plan,this._count=t.count,this._onDirty=t.onDirty,this._dirty=!0}return t.prototype.perform=function(t){var e,n=this._upstream,i=t&&t.skip;if(this._dirty&&n){var r=this.context;r.data=r.outputData=n.context.outputData}this.__pipeline&&(this.__pipeline.currentTask=this),this._plan&&!i&&(e=this._plan(this.context));var o,a=u(this._modBy),s=this._modDataCount||0,l=u(t&&t.modBy),c=t&&t.modDataCount||0;function u(t){return!(t>=1)&&(t=1),t}a===l&&s===c||(e="reset"),(this._dirty||"reset"===e)&&(this._dirty=!1,o=this._doReset(i)),this._modBy=l,this._modDataCount=c;var d=t&&t.step;if(this._dueEnd=n?n._outputDueEnd:this._count?this._count(this.context):1/0,this._progress){var h=this._dueIndex,p=Math.min(null!=d?this._dueIndex+d:1/0,this._dueEnd);if(!i&&(o||h1&&i>0?s:a}};return o;function a(){return e=t?null:oi?-this._resultLT:0},t}(),vy=function(){function t(){}return t.prototype.getRawData=function(){throw new Error("not supported")},t.prototype.getRawDataItem=function(t){throw new Error("not supported")},t.prototype.cloneRawData=function(){},t.prototype.getDimensionInfo=function(t){},t.prototype.cloneAllDimensionInfo=function(){},t.prototype.count=function(){},t.prototype.retrieveValue=function(t,e){},t.prototype.retrieveValueFromItem=function(t,e){},t.prototype.convertValue=function(t,e){return gy(t,e)},t}();function yy(t){if(!Cy(t.sourceFormat)){lc("")}return t.data}function _y(t){var e=t.sourceFormat,n=t.data;if(!Cy(e)){lc("")}if(e===$m){for(var i=[],r=0,o=n.length;r65535?Ty:Ay}function Ey(){return[1/0,-1/0]}function Ny(t){var e=t.constructor;return e===Array?t.slice():new e(t)}function Ry(t,e,n,i,r){var o=Py[n||"float"];if(r){var a=t[e],s=a&&a.length;if(s!==i){for(var l=new o(i),c=0;cg[1]&&(g[1]=f)}return this._rawCount=this._count=s,{start:a,end:s}},t.prototype._initDataFromProvider=function(t,e,n){for(var i=this._provider,r=this._chunks,o=this._dimensions,a=o.length,s=this._rawExtent,l=Gi(o,function(t){return t.property}),c=0;cm[1]&&(m[1]=g)}}!i.persistent&&i.clean&&i.clean(),this._rawCount=this._count=e,this._extent=[]},t.prototype.count=function(){return this._count},t.prototype.get=function(t,e){if(!(e>=0&&e=0&&e=this._rawCount||t<0)return-1;if(!this._indices)return t;var e=this._indices,n=e[t];if(null!=n&&nt))return o;r=o-1}}return-1},t.prototype.getIndices=function(){var t,e=this._indices;if(e){var n=e.constructor,i=this._count;if(n===Array){t=new n(i);for(var r=0;r=c&&_<=u||isNaN(_))&&(a[s++]=p),p++}h=!0}else if(2===r){f=d[i[0]];var m=d[i[1]],v=t[i[1]][0],y=t[i[1]][1];for(g=0;g=c&&_<=u||isNaN(_))&&(b>=v&&b<=y||isNaN(b))&&(a[s++]=p),p++}h=!0}}if(!h)if(1===r)for(g=0;g=c&&_<=u||isNaN(_))&&(a[s++]=x)}else for(g=0;gt[C][1])&&(w=!1)}w&&(a[s++]=e.getRawIndex(g))}return sm[1]&&(m[1]=g)}}}},t.prototype.lttbDownSample=function(t,e){var n,i,r,o=this.clone([t],!0),a=o._chunks[t],s=this.count(),l=0,c=Math.floor(1/e),u=this.getRawIndex(0),d=new(Ly(this._rawCount))(Math.min(2*(Math.ceil(s/c)+2),s));d[l++]=u;for(var h=1;hn&&(n=i,r=k)}C>0&&Ca&&(f=a-c);for(var g=0;gp&&(p=m,h=c+g)}var v=this.getRawIndex(u),y=this.getRawIndex(h);uc-p&&(s=c-p,a.length=s);for(var f=0;fu[1]&&(u[1]=m),d[h++]=v}return r._count=h,r._indices=d,r._updateGetRawIdx(),r},t.prototype.each=function(t,e){if(this._count)for(var n=t.length,i=this._chunks,r=0,o=this.count();ra&&(a=l)}return i=[o,a],this._extent[t]=i,i},t.prototype.getRawDataItem=function(t){var e=this.getRawIndex(t);if(this._provider.persistent)return this._provider.getItem(e);for(var n=[],i=this._chunks,r=0;r=0?this._indices[t]:-1},t.prototype._updateGetRawIdx=function(){this.getRawIndex=this._indices?this._getRawIdx:this._getRawIdxIdentity},t.internalField=function(){function t(t,e,n,i){return gy(t[i],this._dimensions[i])}ky={arrayRows:t,objectRows:function(t,e,n,i){return gy(t[e],this._dimensions[i])},keyedColumns:t,original:function(t,e,n,i){var r=t&&(null==t.value?t:t.value);return gy(r instanceof Array?r[i]:r,this._dimensions[i])},typedArray:function(t,e,n,i){return t[i]}}}(),t}(),zy=function(){function t(t){this._sourceList=[],this._storeList=[],this._upstreamSignList=[],this._versionSignBase=0,this._dirty=!0,this._sourceHost=t}return t.prototype.dirty=function(){this._setLocalSource([],[]),this._storeList=[],this._dirty=!0},t.prototype._setLocalSource=function(t,e){this._sourceList=t,this._upstreamSignList=e,this._versionSignBase++,this._versionSignBase>9e10&&(this._versionSignBase=0)},t.prototype._getVersionSign=function(){return this._sourceHost.uid+"_"+this._versionSignBase},t.prototype.prepareSource=function(){this._isDirty()&&(this._createSource(),this._dirty=!1)},t.prototype._createSource=function(){this._setLocalSource([],[]);var t,e,n=this._sourceHost,i=this._getUpstreamSourceManagers(),r=!!i.length;if(Hy(n)){var o=n,a=void 0,s=void 0,l=void 0;if(r){var c=i[0];c.prepareSource(),a=(l=c.getSource()).data,s=l.sourceFormat,e=[c._getVersionSign()]}else s=ar(a=o.get("data",!0))?Wm:Bm,e=[];var u=this._getSourceMetaRawOption()||{},d=l&&l.metaRawOption||{},h=dr(u.seriesLayoutBy,d.seriesLayoutBy)||null,p=dr(u.sourceHeader,d.sourceHeader),f=dr(u.dimensions,d.dimensions);t=h!==d.seriesLayoutBy||!!p!=!!d.sourceHeader||f?[jv(a,{seriesLayoutBy:h,sourceHeader:p,dimensions:f},s)]:[]}else{var g=n;if(r){var m=this._applyTransform(i);t=m.sourceList,e=m.upstreamSignList}else{t=[jv(g.get("source",!0),this._getSourceMetaRawOption(),null)],e=[]}}this._setLocalSource(t,e)},t.prototype._applyTransform=function(t){var e,n=this._sourceHost,i=n.get("transform",!0),r=n.get("fromTransformResult",!0);if(null!=r){1!==t.length&&By("")}var o,a=[],s=[];return Ui(t,function(t){t.prepareSource();var e=t.getSource(r||0);null==r||e||By(""),a.push(e),s.push(t._getVersionSign())}),i?e=function(t,e){var n=dc(t),i=n.length;i||lc("");for(var r=0,o=i;r1||n>0&&!t.noHeader;return Ui(t.blocks,function(t){var n=Gy(t);n>=e&&(e=n+ +(i&&(!n||qy(t)&&!t.noHeader)))}),e}return 0}function Xy(t,e,n,i){var r,o=e.noHeader,a=(r=Gy(e),{html:Vy[r],richText:Wy[r]}),s=[],l=e.blocks||[];gr(!l||Ji(l)),l=l||[];var c=t.orderMode;if(e.sortBlocks&&c){l=l.slice();var u={valueAsc:"asc",valueDesc:"desc"};if(kr(u,c)){var d=new my(u[c],null);l.sort(function(t,e){return d.evaluate(t.sortParam,e.sortParam)})}else"seriesDesc"===c&&l.reverse()}Ui(l,function(n,r){var o=e.valueFormatter,l=Uy(n)(o?Fi(Fi({},t),{valueFormatter:o}):t,n,r>0?a.html:0,i);null!=l&&s.push(l)});var h="richText"===t.renderMode?s.join(a.richText):Ky(i,s.join(""),o?n:a.html);if(o)return h;var p=nm(e.header,"ordinal",t.useUTC),f=Fy(i,t.renderMode).nameStyle,g=$y(i);return"richText"===t.renderMode?Qy(t,p,f)+a.richText+h:Ky(i,'
'+Qr(p)+"
"+h,n)}function Yy(t,e,n,i){var r=t.renderMode,o=e.noName,a=e.noValue,s=!e.markerType,l=e.name,c=t.useUTC,u=e.valueFormatter||t.valueFormatter||function(t){return Gi(t=Ji(t)?t:[t],function(t,e){return nm(t,Ji(p)?p[e]:p,c)})};if(!o||!a){var d=s?"":t.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||Im.color.secondary,r),h=o?"":nm(l,"ordinal",c),p=e.valueType,f=a?[]:u(e.value,e.dataIndex),g=!s||!o,m=!s&&o,v=Fy(i,r),y=v.nameStyle,_=v.valueStyle;return"richText"===r?(s?"":d)+(o?"":Qy(t,h,y))+(a?"":function(t,e,n,i,r){var o=[r],a=i?10:20;return n&&o.push({padding:[0,0,0,a],align:"right"}),t.markupStyleCreator.wrapRichTextStyle(Ji(e)?e.join(" "):e,o)}(t,f,g,m,_)):Ky(i,(s?"":d)+(o?"":function(t,e,n){return''+Qr(t)+""}(h,!s,y))+(a?"":function(t,e,n,i){var r=n?"10px":"20px",o=e?"float:right;margin-left:"+r:"";return t=Ji(t)?t:[t],''+Gi(t,function(t){return Qr(t)}).join("  ")+""}(f,g,m,_)),n)}}function Zy(t,e,n,i,r,o){if(t)return Uy(t)({useUTC:r,renderMode:n,orderMode:i,markupStyleCreator:e,valueFormatter:t.valueFormatter},t,0,o)}function Ky(t,e,n){return'
'+e+'
'}function Qy(t,e,n){return t.markupStyleCreator.wrapRichTextStyle(e,n)}function Jy(t,e){var n=t.get("padding");return null!=n?n:"richText"===e?[8,10]:10}var t_=function(){function t(){this.richTextStyles={},this._nextStyleNameId=ic()}return t.prototype._generateStyleName=function(){return"__EC_aUTo_"+this._nextStyleNameId++},t.prototype.makeTooltipMarker=function(t,e,n){var i="richText"===n?this._generateStyleName():null,r=function(t,e){var n=er(t)?{color:t,extraCssText:e}:t||{},i=n.color,r=n.type;e=n.extraCssText;var o=n.renderMode||"html";return i?"html"===o?"subItem"===r?'':'':{renderMode:o,content:"{"+(n.markerId||"markerX")+"|} ",style:"subItem"===r?{width:4,height:4,borderRadius:2,backgroundColor:i}:{width:10,height:10,borderRadius:5,backgroundColor:i}}:""}({color:e,type:t,renderMode:n,markerId:i});return er(r)?r:(this.richTextStyles[i]=r.style,r.content)},t.prototype.wrapRichTextStyle=function(t,e){var n={};Ji(e)?Ui(e,function(t){return Fi(n,t)}):Fi(n,e);var i=this._generateStyleName();return this.richTextStyles[i]=n,"{"+i+"|"+t+"}"},t}();function e_(t){var e,n,i,r,o=t.series,a=t.dataIndex,s=t.multipleSeries,l=o.getData(),c=l.mapDimensionsAll("defaultedTooltip"),u=c.length,d=o.getRawValue(a),h=Ji(d),p=function(t,e){return am(t.getData().getItemVisual(e,"style")[t.visualDrawType])}(o,a);if(u>1||h&&!u){var f=function(t,e,n,i,r){var o=e.getData(),a=Xi(t,function(t,e,n){var i=o.getDimensionInfo(n);return t||i&&!1!==i.tooltip&&null!=i.displayName},!1),s=[],l=[],c=[];function u(t,e){var n=o.getDimensionInfo(e);n&&!1!==n.otherDims.tooltip&&(a?c.push(jy("nameValue",{markerType:"subItem",markerColor:r,name:n.displayName,value:t,valueType:n.type})):(s.push(t),l.push(n.type)))}return i.length?Ui(i,function(t){u(ly(o,n,t),t)}):Ui(t,u),{inlineValues:s,inlineValueTypes:l,blocks:c}}(d,o,a,c,p);e=f.inlineValues,n=f.inlineValueTypes,i=f.blocks,r=f.inlineValues[0]}else if(u){var g=l.getDimensionInfo(c[0]);r=e=ly(l,a,c[0]),n=g.type}else r=e=h?d[0]:d;var m=bc(o),v=m&&o.name||"",y=l.getName(a),_=s?v:y;return jy("section",{header:v,noHeader:s||!m,sortParam:r,blocks:[jy("nameValue",{markerType:"item",markerColor:p,name:_,noName:!mr(_),value:e,valueType:n,dataIndex:a})].concat(i||[])})}var n_=Sc();function i_(t,e){return t.getName(e)||t.getId(e)}var r_=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._selectedDataIndicesMap={},e}var n;return S(e,t),e.prototype.init=function(t,e,n){this.seriesIndex=this.componentIndex,this.dataTask=hy({count:a_,reset:s_}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n),(n_(this).sourceManager=new zy(this)).prepareSource();var i=this.getInitialData(t,n);c_(i,this),this.dataTask.context.data=i,n_(this).dataBeforeProcessed=i,o_(this),this._initSelectedMapFromData(i)},e.prototype.mergeDefaultAndTheme=function(t,e){var n=Cm(this),i=n?Mm(t):{},r=this.subType;Am.hasClass(r)&&(r+="Series"),$i(t,e.getTheme().get(this.subType)),$i(t,this.getDefaultOption()),hc(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&km(t,i,n)},e.prototype.mergeOption=function(t,e){t=$i(this.option,t,!0),this.fillDataTextStyle(t.data);var n=Cm(this);n&&km(this.option,t,n);var i=n_(this).sourceManager;i.dirty(),i.prepareSource();var r=this.getInitialData(t,e);c_(r,this),this.dataTask.dirty(),this.dataTask.context.data=r,n_(this).dataBeforeProcessed=r,o_(this),this._initSelectedMapFromData(r)},e.prototype.fillDataTextStyle=function(t){if(t&&!ar(t))for(var e=["show"],n=0;n=0&&u<0)&&(c=o,u=r,d=0),r===u&&(l[d++]=e))}),l.length=d,l},e.prototype.formatTooltip=function(t,e,n){return e_({series:this,dataIndex:t,multipleSeries:e})},e.prototype.isAnimationEnabled=function(){var t=this.ecModel;if(yi.node&&(!t||!t.ssr))return!1;var e=this.getShallow("animation");return e&&this.getData().count()>this.getShallow("animationThreshold")&&(e=!1),!!e},e.prototype.restoreData=function(){this.dataTask.dirty()},e.prototype.getColorFromPalette=function(t,e,n){var i=this.ecModel,r=ov.prototype.getColorFromPalette.call(this,t,e,n);return r||(r=i.getColorFromPalette(t,e,n)),r},e.prototype.coordDimToDataDim=function(t){return this.getRawData().mapDimensionsAll(t)},e.prototype.getProgressive=function(){return this.get("progressive")},e.prototype.getProgressiveThreshold=function(){return this.get("progressiveThreshold")},e.prototype.select=function(t,e){this._innerSelect(this.getData(e),t)},e.prototype.unselect=function(t,e){var n=this.option.selectedMap;if(n){var i=this.option.selectedMode,r=this.getData(e);if("series"===i||"all"===n)return this.option.selectedMap={},void(this._selectedDataIndicesMap={});for(var o=0;o=0&&n.push(r)}return n},e.prototype.isSelected=function(t,e){var n=this.option.selectedMap;if(!n)return!1;var i=this.getData(e);return("all"===n||n[i_(i,t)])&&!i.getItemModel(t).get(["select","disabled"])},e.prototype.isUniversalTransitionEnabled=function(){if(this.__universalTransitionEnabled)return!0;var t=this.option.universalTransition;return!!t&&(!0===t||t&&t.enabled)},e.prototype._innerSelect=function(t,e){var n,i,r=this.option,o=r.selectedMode,a=e.length;if(o&&a)if("series"===o)r.selectedMap="all";else if("multiple"===o){rr(r.selectedMap)||(r.selectedMap={});for(var s=r.selectedMap,l=0;l0&&this._innerSelect(t,e)}},e.registerClass=function(t){return Am.registerClass(t)},e.protoInitialize=((n=e.prototype).type="series.__base__",n.seriesIndex=0,n.ignoreStyleOnData=!1,n.hasSymbolVisual=!1,n.defaultSymbol="circle",n.visualStyleAccessPath="itemStyle",void(n.visualDrawType="fill")),e}(Am);function o_(t){var e=t.name;bc(t)||(t.name=function(t){var e=t.getRawData(),n=e.mapDimensionsAll("seriesName"),i=[];return Ui(n,function(t){var n=e.getDimensionInfo(t);n.displayName&&i.push(n.displayName)}),i.join(" ")}(t)||e)}function a_(t){return t.model.getRawData().count()}function s_(t){var e=t.model;return e.setData(e.getRawData().cloneShallow()),l_}function l_(t,e){e.outputData&&t.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function c_(t,e){Ui(function(t,e){for(var n=new t.constructor(t.length+e.length),i=0;i=0?d():u=setTimeout(d,-r),l=i};return h.clear=function(){u&&(clearTimeout(u),u=null)},h.debounceNextCall=function(t){s=t},h}function M_(t,e,n,i){var r=t[e];if(r){var o=r[w_]||r,a=r[C_];if(r[S_]!==n||a!==i){if(null==n||!i)return t[e]=o;(r=t[e]=k_(o,n,"debounce"===i))[w_]=o,r[C_]=i,r[S_]=n}return r}}function T_(t,e){var n=t[e];n&&n[w_]&&(n.clear&&n.clear(),t[e]=n[w_])}var A_=Sc(),I_={itemStyle:Bc(sg,!0),lineStyle:Bc(rg,!0)},D_={lineStyle:"stroke",itemStyle:"fill"};function P_(t,e){var n=t.visualStyleMapper||I_[e];return n||(console.warn("Unknown style type '"+e+"'."),I_.itemStyle)}function L_(t,e){var n=t.visualDrawType||D_[e];return n||(console.warn("Unknown style type '"+e+"'."),"fill")}var E_={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=t.getModel(i),o=P_(t,i)(r),a=r.getShallow("decal");a&&(n.setVisual("decal",a),a.dirty=!0);var s=L_(t,i),l=o[s],c=tr(l)?l:null,u="auto"===o.fill||"auto"===o.stroke;if(!o[s]||c||u){var d=t.getColorFromPalette(t.name,null,e.getSeriesCount());o[s]||(o[s]=d,n.setVisual("colorFromPalette",!0)),o.fill="auto"===o.fill||tr(o.fill)?d:o.fill,o.stroke="auto"===o.stroke||tr(o.stroke)?d:o.stroke}if(n.setVisual("style",o),n.setVisual("drawType",s),!e.isSeriesFiltered(t)&&c)return n.setVisual("colorFromPalette",!1),{dataEach:function(e,n){var i=t.getDataParams(n),r=Fi({},o);r[s]=c(i),e.setItemVisual(n,"style",r)}}}},N_=new ug,R_={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){if(!t.ignoreStyleOnData&&!e.isSeriesFiltered(t)){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=P_(t,i),o=n.getVisual("drawType");return{dataEach:n.hasItemOption?function(t,e){var n=t.getRawDataItem(e);if(n&&n[i]){N_.option=n[i];var a=r(N_);Fi(t.ensureUniqueItemVisual(e,"style"),a),N_.option.decal&&(t.setItemVisual(e,"decal",N_.option.decal),N_.option.decal.dirty=!0),o in a&&t.setItemVisual(e,"colorFromPalette",!1)}}:null}}}},O_={performRawSeries:!0,overallReset:function(t){var e=Sr();t.eachSeries(function(t){var n=t.getColorBy();if(!t.isColorBySeries()){var i=t.type+"-"+n,r=e.get(i);r||(r={},e.set(i,r)),A_(t).scope=r}}),t.eachSeries(function(e){if(!e.isColorBySeries()&&!t.isSeriesFiltered(e)){var n=e.getRawData(),i={},r=e.getData(),o=A_(e).scope,a=e.visualStyleAccessPath||"itemStyle",s=L_(e,a);r.each(function(t){var e=r.getRawIndex(t);i[e]=t}),n.each(function(t){var a=i[t];if(r.getItemVisual(a,"colorFromPalette")){var l=r.ensureUniqueItemVisual(a,"style"),c=n.getName(t)||t+"",u=n.count();l[s]=e.getColorFromPalette(c,o,u)}})}})}},z_=Math.PI;var H_=function(){function t(t,e,n,i){this._stageTaskMap=Sr(),this.ecInstance=t,this.api=e,n=this._dataProcessorHandlers=n.slice(),i=this._visualHandlers=i.slice(),this._allHandlers=n.concat(i)}return t.prototype.restoreData=function(t,e){t.restoreData(e),this._stageTaskMap.each(function(t){var e=t.overallTask;e&&e.dirty()})},t.prototype.getPerformArgs=function(t,e){if(t.__pipeline){var n=this._pipelineMap.get(t.__pipeline.id),i=n.context,r=!e&&n.progressiveEnabled&&(!i||i.progressiveRender)&&t.__idxInPipeline>n.blockIndex?n.step:null,o=i&&i.modDataCount;return{step:r,modBy:null!=o?Math.ceil(o/r):null,modDataCount:o}}},t.prototype.getPipeline=function(t){return this._pipelineMap.get(t)},t.prototype.updateStreamModes=function(t,e){var n=this._pipelineMap.get(t.uid),i=t.getData().count(),r=n.progressiveEnabled&&e.incrementalPrepareRender&&i>=n.threshold,o=t.get("large")&&i>=t.get("largeThreshold"),a="mod"===t.get("progressiveChunkMode")?i:null;t.pipelineContext=n.context={progressiveRender:r,modDataCount:a,large:o}},t.prototype.restorePipelines=function(t){var e=this,n=e._pipelineMap=Sr();t.eachSeries(function(t){var i=t.getProgressive(),r=t.uid;n.set(r,{id:r,head:null,tail:null,threshold:t.getProgressiveThreshold(),progressiveEnabled:i&&!(t.preventIncremental&&t.preventIncremental()),blockIndex:-1,step:Math.round(i||700),count:0}),e._pipe(t,t.dataTask)})},t.prototype.prepareStageTasks=function(){var t=this._stageTaskMap,e=this.api.getModel(),n=this.api;Ui(this._allHandlers,function(i){var r=t.get(i.uid)||t.set(i.uid,{});gr(!(i.reset&&i.overallReset),""),i.reset&&this._createSeriesStageTask(i,r,e,n),i.overallReset&&this._createOverallStageTask(i,r,e,n)},this)},t.prototype.prepareView=function(t,e,n,i){var r=t.renderTask,o=r.context;o.model=e,o.ecModel=n,o.api=i,r.__block=!t.incrementalPrepareRender,this._pipe(e,r)},t.prototype.performDataProcessorTasks=function(t,e){this._performStageTasks(this._dataProcessorHandlers,t,e,{block:!0})},t.prototype.performVisualTasks=function(t,e,n){this._performStageTasks(this._visualHandlers,t,e,n)},t.prototype._performStageTasks=function(t,e,n,i){i=i||{};var r=!1,o=this;function a(t,e){return t.setDirty&&(!t.dirtyMap||t.dirtyMap.get(e.__pipeline.id))}Ui(t,function(t,s){if(!i.visualType||i.visualType===t.visualType){var l=o._stageTaskMap.get(t.uid),c=l.seriesTaskMap,u=l.overallTask;if(u){var d,h=u.agentStubMap;h.each(function(t){a(i,t)&&(t.dirty(),d=!0)}),d&&u.dirty(),o.updatePayload(u,n);var p=o.getPerformArgs(u,i.block);h.each(function(t){t.perform(p)}),u.perform(p)&&(r=!0)}else c&&c.each(function(s,l){a(i,s)&&s.dirty();var c=o.getPerformArgs(s,i.block);c.skip=!t.performRawSeries&&e.isSeriesFiltered(s.context.model),o.updatePayload(s,n),s.perform(c)&&(r=!0)})}}),this.unfinished=r||this.unfinished},t.prototype.performSeriesTasks=function(t){var e;t.eachSeries(function(t){e=t.dataTask.perform()||e}),this.unfinished=e||this.unfinished},t.prototype.plan=function(){this._pipelineMap.each(function(t){var e=t.tail;do{if(e.__block){t.blockIndex=e.__idxInPipeline;break}e=e.getUpstream()}while(e)})},t.prototype.updatePayload=function(t,e){"remain"!==e&&(t.context.payload=e)},t.prototype._createSeriesStageTask=function(t,e,n,i){var r=this,o=e.seriesTaskMap,a=e.seriesTaskMap=Sr(),s=t.seriesType,l=t.getTargetSeries;function c(e){var s=e.uid,l=a.set(s,o&&o.get(s)||hy({plan:W_,reset:j_,count:G_}));l.context={model:e,ecModel:n,api:i,useClearVisual:t.isVisual&&!t.isLayout,plan:t.plan,reset:t.reset,scheduler:r},r._pipe(e,l)}t.createOnAllSeries?n.eachRawSeries(c):s?n.eachRawSeriesByType(s,c):l&&l(n,i).each(c)},t.prototype._createOverallStageTask=function(t,e,n,i){var r=this,o=e.overallTask=e.overallTask||hy({reset:B_});o.context={ecModel:n,api:i,overallReset:t.overallReset,scheduler:r};var a=o.agentStubMap,s=o.agentStubMap=Sr(),l=t.seriesType,c=t.getTargetSeries,u=!0,d=!1;function h(t){var e=t.uid,n=s.set(e,a&&a.get(e)||(d=!0,hy({reset:$_,onDirty:V_})));n.context={model:t,overallProgress:u},n.agent=o,n.__block=u,r._pipe(t,n)}gr(!t.createOnAllSeries,""),l?n.eachRawSeriesByType(l,h):c?c(n,i).each(h):(u=!1,Ui(n.getSeries(),h)),d&&o.dirty()},t.prototype._pipe=function(t,e){var n=t.uid,i=this._pipelineMap.get(n);!i.head&&(i.head=e),i.tail&&i.tail.pipe(e),i.tail=e,e.__idxInPipeline=i.count++,e.__pipeline=i},t.wrapStageHandler=function(t,e){return tr(t)&&(t={overallReset:t,seriesType:X_(t)}),t.uid=hg("stageHandler"),e&&(t.visualType=e),t},t}();function B_(t){t.overallReset(t.ecModel,t.api,t.payload)}function $_(t){return t.overallProgress&&F_}function F_(){this.agent.dirty(),this.getDownstream().dirty()}function V_(){this.agent&&this.agent.dirty()}function W_(t){return t.plan?t.plan(t.model,t.ecModel,t.api,t.payload):null}function j_(t){t.useClearVisual&&t.data.clearAllVisual();var e=t.resetDefines=dc(t.reset(t.model,t.ecModel,t.api,t.payload));return e.length>1?Gi(e,function(t,e){return U_(e)}):q_}var q_=U_(0);function U_(t){return function(e,n){var i=n.data,r=n.resetDefines[t];if(r&&r.dataEach)for(var o=e.start;o0&&u===r.length-c.length){var d=r.slice(0,u);"data"!==d&&(e.mainType=d,e[c.toLowerCase()]=t,s=!0)}}a.hasOwnProperty(r)&&(n[r]=t,s=!0),s||(i[r]=t)})}return{cptQuery:e,dataQuery:n,otherQuery:i}},t.prototype.filter=function(t,e){var n=this.eventInfo;if(!n)return!0;var i=n.targetEl,r=n.packedEvent,o=n.model,a=n.view;if(!o||!a)return!0;var s=e.cptQuery,l=e.dataQuery;return c(s,o,"mainType")&&c(s,o,"subType")&&c(s,o,"index","componentIndex")&&c(s,o,"name")&&c(s,o,"id")&&c(l,r,"name")&&c(l,r,"dataIndex")&&c(l,r,"dataType")&&(!a.filterForExposedEvent||a.filterForExposedEvent(t,e.otherQuery,i,r));function c(t,e,n,i){return null==t[n]||e[i||n]===t[n]}},t.prototype.afterTrigger=function(){this.eventInfo=null},t}(),ab=["symbol","symbolSize","symbolRotate","symbolOffset"],sb=ab.concat(["symbolKeepAspect"]),lb={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData();if(t.legendIcon&&n.setVisual("legendIcon",t.legendIcon),t.hasSymbolVisual){for(var i={},r={},o=!1,a=0;a=0&&kb(l)?l:.5,t.createRadialGradient(a,s,0,a,s,l)}(t,e,n):function(t,e,n){var i=null==e.x?0:e.x,r=null==e.x2?1:e.x2,o=null==e.y?0:e.y,a=null==e.y2?0:e.y2;return e.global||(i=i*n.width+n.x,r=r*n.width+n.x,o=o*n.height+n.y,a=a*n.height+n.y),i=kb(i)?i:0,r=kb(r)?r:1,o=kb(o)?o:0,a=kb(a)?a:0,t.createLinearGradient(i,o,r,a)}(t,e,n),r=e.colorStops,o=0;o0&&(e=i.lineDash,n=i.lineWidth,e&&"solid"!==e&&n>0?"dashed"===e?[4*n,2*n]:"dotted"===e?[n]:ir(e)?[e]:Ji(e)?e:null:null),o=i.lineDashOffset;if(r){var a=i.strokeNoScale&&t.getLineScale?t.getLineScale():1;a&&1!==a&&(r=Gi(r,function(t){return t/a}),o/=a)}return[r,o]}var Db=new Zu(!0);function Pb(t){var e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))}function Lb(t){return"string"==typeof t&&"none"!==t}function Eb(t){var e=t.fill;return null!=e&&"none"!==e}function Nb(t,e){if(null!=e.fillOpacity&&1!==e.fillOpacity){var n=t.globalAlpha;t.globalAlpha=e.fillOpacity*e.opacity,t.fill(),t.globalAlpha=n}else t.fill()}function Rb(t,e){if(null!=e.strokeOpacity&&1!==e.strokeOpacity){var n=t.globalAlpha;t.globalAlpha=e.strokeOpacity*e.opacity,t.stroke(),t.globalAlpha=n}else t.stroke()}function Ob(t,e,n){var i=jc(e.image,e.__image,n);if(Uc(i)){var r=t.createPattern(i,e.repeat||"repeat");if("function"==typeof DOMMatrix&&r&&r.setTransform){var o=new DOMMatrix;o.translateSelf(e.x||0,e.y||0),o.rotateSelf(0,0,(e.rotation||0)*Tr),o.scaleSelf(e.scaleX||1,e.scaleY||1),r.setTransform(o)}return r}}var zb=["shadowBlur","shadowOffsetX","shadowOffsetY"],Hb=[["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]];function Bb(t,e,n,i,r){var o=!1;if(!i&&e===(n=n||{}))return!1;if(i||e.opacity!==n.opacity){Vb(t,r),o=!0;var a=Math.max(Math.min(e.opacity,1),0);t.globalAlpha=isNaN(a)?hu.opacity:a}(i||e.blend!==n.blend)&&(o||(Vb(t,r),o=!0),t.globalCompositeOperation=e.blend||hu.blend);for(var s=0;s0&&t.unfinished);t.unfinished||this._zr.flush()}}},e.prototype.getDom=function(){return this._dom},e.prototype.getId=function(){return this.id},e.prototype.getZr=function(){return this._zr},e.prototype.isSSR=function(){return this._ssr},e.prototype.setOption=function(t,e,n){if(!this[ix])if(this._disposed)this.id;else{var i,r,o;if(rr(e)&&(n=e.lazyUpdate,i=e.silent,r=e.replaceMerge,o=e.transition,e=e.notMerge),this[ix]=!0,Px(this),!this._model||e){var a=new fv(this._api),s=this._theme,l=this._model=new sv;l.scheduler=this._scheduler,l.ssr=this._ssr,l.init(null,null,null,s,this._locale,a)}this._model.setOption(t,{replaceMerge:r},Fx);var c={seriesTransition:o,optionChanged:!0};if(n)this[ox]={silent:i,updateParams:c},this[ix]=!1,this.getZr().wakeUp();else{try{hx(this),gx.update.call(this,null,c)}catch(t){throw this[ox]=null,this[ix]=!1,t}this._ssr||this._zr.flush(),this[ox]=null,this[ix]=!1,_x.call(this,i),bx.call(this,i)}}},e.prototype.setTheme=function(t,e){if(!this[ix])if(this._disposed)this.id;else{var n=this._model;if(n){var i=e&&e.silent,r=null;this[ox]&&(null==i&&(i=this[ox].silent),r=this[ox].updateParams,this[ox]=null),this[ix]=!0,Px(this);try{this._updateTheme(t),n.setTheme(this._theme),hx(this),gx.update.call(this,{type:"setTheme"},r)}catch(t){throw this[ix]=!1,t}this[ix]=!1,_x.call(this,i),bx.call(this,i)}}},e.prototype._updateTheme=function(t){er(t)&&(t=Wx[t]),t&&((t=Bi(t))&&Rv(t,!0),this._theme=t)},e.prototype.getModel=function(){return this._model},e.prototype.getOption=function(){return this._model&&this._model.getOption()},e.prototype.getWidth=function(){return this._zr.getWidth()},e.prototype.getHeight=function(){return this._zr.getHeight()},e.prototype.getDevicePixelRatio=function(){return this._zr.painter.dpr||yi.hasGlobalWindow&&window.devicePixelRatio||1},e.prototype.getRenderedCanvas=function(t){return this.renderToCanvas(t)},e.prototype.renderToCanvas=function(t){return t=t||{},this._zr.painter.getRenderedCanvas({backgroundColor:t.backgroundColor||this._model.get("backgroundColor"),pixelRatio:t.pixelRatio||this.getDevicePixelRatio()})},e.prototype.renderToSVGString=function(t){return t=t||{},this._zr.painter.renderToString({useViewBox:t.useViewBox})},e.prototype.getSvgDataURL=function(){var t=this._zr;return Ui(t.storage.getDisplayList(),function(t){t.stopAnimation(null,!0)}),t.painter.toDataURL()},e.prototype.getDataURL=function(t){if(!this._disposed){var e=(t=t||{}).excludeComponents,n=this._model,i=[],r=this;Ui(e,function(t){n.eachComponent({mainType:t},function(t){var e=r._componentsMap[t.__viewId];e.group.ignore||(i.push(e),e.group.ignore=!0)})});var o="svg"===this._zr.painter.getType()?this.getSvgDataURL():this.renderToCanvas(t).toDataURL("image/"+(t&&t.type||"png"));return Ui(i,function(t){t.group.ignore=!1}),o}this.id},e.prototype.getConnectedDataURL=function(t){if(!this._disposed){var e="svg"===t.type,n=this.group,i=Math.min,r=Math.max,o=1/0;if(Ux[n]){var a=o,s=o,l=-1/0,c=-1/0,u=[],d=t&&t.pixelRatio||this.getDevicePixelRatio();Ui(qx,function(o,d){if(o.group===n){var h=e?o.getZr().painter.getSvgDom().innerHTML:o.renderToCanvas(Bi(t)),p=o.getDom().getBoundingClientRect();a=i(p.left,a),s=i(p.top,s),l=r(p.right,l),c=r(p.bottom,c),u.push({dom:h,left:p.left,top:p.top})}});var h=(l*=d)-(a*=d),p=(c*=d)-(s*=d),f=Ci.createCanvas(),g=Bl(f,{renderer:e?"svg":"canvas"});if(g.resize({width:h,height:p}),e){var m="";return Ui(u,function(t){var e=t.left-a,n=t.top-s;m+=''+t.dom+""}),g.painter.getSvgRoot().innerHTML=m,t.connectedBackgroundColor&&g.painter.setBackgroundColor(t.connectedBackgroundColor),g.refreshImmediately(),g.painter.toDataURL()}return t.connectedBackgroundColor&&g.add(new Id({shape:{x:0,y:0,width:h,height:p},style:{fill:t.connectedBackgroundColor}})),Ui(u,function(t){var e=new wd({style:{x:t.left*d-a,y:t.top*d-s,image:t.dom}});g.add(e)}),g.refreshImmediately(),f.toDataURL("image/"+(t&&t.type||"png"))}return this.getDataURL(t)}this.id},e.prototype.convertToPixel=function(t,e,n){return mx(this,"convertToPixel",t,e,n)},e.prototype.convertToLayout=function(t,e,n){return mx(this,"convertToLayout",t,e,n)},e.prototype.convertFromPixel=function(t,e,n){return mx(this,"convertFromPixel",t,e,n)},e.prototype.containPixel=function(t,e){var n;if(!this._disposed)return Ui(kc(this._model,t),function(t,i){i.indexOf("Models")>=0&&Ui(t,function(t){var r=t.coordinateSystem;if(r&&r.containPoint)n=n||!!r.containPoint(e);else if("seriesModels"===i){var o=this._chartsMap[t.__viewId];o&&o.containPoint&&(n=n||o.containPoint(e,t))}},this)},this),!!n;this.id},e.prototype.getVisual=function(t,e){var n=kc(this._model,t,{defaultMainType:"series"}),i=n.seriesModel.getData(),r=n.hasOwnProperty("dataIndexInside")?n.dataIndexInside:n.hasOwnProperty("dataIndex")?i.indexOfRawIndex(n.dataIndex):null;return null!=r?function(t,e,n){switch(n){case"color":return t.getItemVisual(e,"style")[t.getVisual("drawType")];case"opacity":return t.getItemVisual(e,"style").opacity;case"symbol":case"symbolSize":case"liftZ":return t.getItemVisual(e,n)}}(i,r,e):function(t,e){switch(e){case"color":return t.getVisual("style")[t.getVisual("drawType")];case"opacity":return t.getVisual("style").opacity;case"symbol":case"symbolSize":case"liftZ":return t.getVisual(e)}}(i,e)},e.prototype.getViewOfComponentModel=function(t){return this._componentsMap[t.__viewId]},e.prototype.getViewOfSeriesModel=function(t){return this._chartsMap[t.__viewId]},e.prototype._initEvents=function(){var t=this;Ui(Ox,function(e){var n=function(n){var i,r=t.getModel(),o=n.target;if("globalout"===e?i={}:o&&db(o,function(t){var e=Ud(t);if(e&&null!=e.dataIndex){var n=e.dataModel||r.getSeriesByIndex(e.seriesIndex);return i=n&&n.getDataParams(e.dataIndex,e.dataType,o)||{},!0}if(e.eventData)return i=Fi({},e.eventData),!0},!0),i){var a=i.componentType,s=i.componentIndex;"markLine"!==a&&"markPoint"!==a&&"markArea"!==a||(a="series",s=i.seriesIndex);var l=a&&null!=s&&r.getComponent(a,s),c=l&&t["series"===l.mainType?"_chartsMap":"_componentsMap"][l.__viewId];i.event=n,i.type=e,t._$eventProcessor.eventInfo={targetEl:o,packedEvent:i,model:l,view:c},t.trigger(e,i)}};n.zrEventfulCallAtLast=!0,t._zr.on(e,n,t)});var e=this._messageCenter;Ui(Bx,function(n,i){e.on(i,function(e){t.trigger(i,e)})}),function(t,e,n){t.on("selectchanged",function(t){var i=n.getModel();t.isFromClick?(ub("map","selectchanged",e,i,t),ub("pie","selectchanged",e,i,t)):"select"===t.fromAction?(ub("map","selected",e,i,t),ub("pie","selected",e,i,t)):"unselect"===t.fromAction&&(ub("map","unselected",e,i,t),ub("pie","unselected",e,i,t))})}(e,this,this._api)},e.prototype.isDisposed=function(){return this._disposed},e.prototype.clear=function(){this._disposed?this.id:this.setOption({series:[]},!0)},e.prototype.dispose=function(){if(this._disposed)this.id;else{this._disposed=!0,this.getDom()&&Ic(this.getDom(),Xx,"");var t=this,e=t._api,n=t._model;Ui(t._componentsViews,function(t){t.dispose(n,e)}),Ui(t._chartsViews,function(t){t.dispose(n,e)}),t._zr.dispose(),t._dom=t._model=t._chartsMap=t._componentsMap=t._chartsViews=t._componentsViews=t._scheduler=t._api=t._zr=t._throttledZrFlush=t._theme=t._coordSysMgr=t._messageCenter=null,delete qx[t.id]}},e.prototype.resize=function(t){if(!this[ix])if(this._disposed)this.id;else{this._zr.resize(t);var e=this._model;if(this._loadingFX&&this._loadingFX.resize(),e){var n=e.resetOption("media"),i=t&&t.silent;this[ox]&&(null==i&&(i=this[ox].silent),n=!0,this[ox]=null),this[ix]=!0,Px(this);try{n&&hx(this),gx.update.call(this,{type:"resize",animation:Fi({duration:0},t&&t.animation)})}catch(t){throw this[ix]=!1,t}this[ix]=!1,_x.call(this,i),bx.call(this,i)}}},e.prototype.showLoading=function(t,e){if(this._disposed)this.id;else if(rr(t)&&(e=t,t=""),t=t||"default",this.hideLoading(),jx[t]){var n=jx[t](this._api,e),i=this._zr;this._loadingFX=n,i.add(n)}},e.prototype.hideLoading=function(){this._disposed?this.id:(this._loadingFX&&this._zr.remove(this._loadingFX),this._loadingFX=null)},e.prototype.makeActionFromEvent=function(t){var e=Fi({},t);return e.type=Hx[t.type],e},e.prototype.dispatchAction=function(t,e){if(this._disposed)this.id;else if(rr(e)||(e={silent:!!e}),zx[t.type]&&this._model)if(this[ix])this._pendingActions.push(t);else{var n=e.silent;yx.call(this,t,n);var i=e.flush;i?this._zr.flush():!1!==i&&yi.browser.weChat&&this._throttledZrFlush(),_x.call(this,n),bx.call(this,n)}},e.prototype.updateLabelLayout=function(){Qb.trigger("series:layoutlabels",this._model,this._api,{updatedSeries:[]})},e.prototype.appendData=function(t){if(this._disposed)this.id;else{var e=t.seriesIndex;this.getModel().getSeriesByIndex(e).appendData(t),this._scheduler.unfinished=!0,this.getZr().wakeUp()}},e.internalField=function(){function t(t){t.clearColorPalette(),t.eachSeries(function(t){t.clearColorPalette()})}function e(t){for(var e=[],n=t.currentStates,i=0;i0?{duration:o,delay:i.get("delay"),easing:i.get("easing")}:null;n.eachRendered(function(t){if(t.states&&t.states.emphasis){if(of(t))return;if(t instanceof vd&&function(t){var e=Yd(t);e.normalFill=t.style.fill,e.normalStroke=t.style.stroke;var n=t.states.select||{};e.selectFill=n.style&&n.style.fill||null,e.selectStroke=n.style&&n.style.stroke||null}(t),t.__dirty){var n=t.prevStates;n&&t.useStates(n)}if(r){t.stateTransition=a;var i=t.getTextContent(),o=t.getTextGuideLine();i&&(i.stateTransition=a),o&&(o.stateTransition=a)}t.__dirty&&e(t)}})}hx=function(t){var e=t._scheduler;e.restorePipelines(t._model),e.prepareStageTasks(),px(t,!0),px(t,!1),e.plan()},px=function(t,e){for(var n=t._model,i=t._scheduler,r=e?t._componentsViews:t._chartsViews,o=e?t._componentsMap:t._chartsMap,a=t._zr,s=t._api,l=0;le.get("hoverLayerThreshold")&&!yi.node&&!yi.worker&&e.eachSeries(function(e){if(!e.preventUsingHoverLayer){var n=t._chartsMap[e.__viewId];n.__alive&&n.eachRendered(function(t){t.states.emphasis&&(t.states.emphasis.hoverLayer=!0)})}})}(t,e),Qb.trigger("series:afterupdate",e,o,s)},Ix=function(t){t[ax]=!0,t.getZr().wakeUp()},Px=function(t){t[rx]=(t[rx]+1)%1e3},Dx=function(t){t[ax]&&(t.getZr().storage.traverse(function(t){of(t)||e(t)}),t[ax]=!1)},Tx=function(t){return new(function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return S(n,e),n.prototype.getCoordinateSystems=function(){return t._coordSysMgr.getCoordinateSystems()},n.prototype.getComponentByElement=function(e){for(;e;){var n=e.__ecComponentInfo;if(null!=n)return t._model.getComponent(n.mainType,n.index);e=e.parent}},n.prototype.enterEmphasis=function(e,n){bh(e,n),Ix(t)},n.prototype.leaveEmphasis=function(e,n){xh(e,n),Ix(t)},n.prototype.enterBlur=function(e){!function(t){fh(t,ch)}(e),Ix(t)},n.prototype.leaveBlur=function(e){wh(e),Ix(t)},n.prototype.enterSelect=function(e){Sh(e),Ix(t)},n.prototype.leaveSelect=function(e){Ch(e),Ix(t)},n.prototype.getModel=function(){return t.getModel()},n.prototype.getViewOfComponentModel=function(e){return t.getViewOfComponentModel(e)},n.prototype.getViewOfSeriesModel=function(e){return t.getViewOfSeriesModel(e)},n.prototype.getMainProcessVersion=function(){return t[rx]},n}(hv))(t)},Ax=function(t){function e(t,e){for(var n=0;n=0)){nw.push(n);var o=H_.wrapStageHandler(n,r);o.__prio=e,o.__raw=n,t.push(o)}}function rw(t,e){jx[t]=e}var ow=function(t){var e=(t=Bi(t)).type;e||lc("");var n=e.split(":");2!==n.length&&lc("");var i=!1;"echarts"===n[0]&&(e=n[1],i=!0),t.__isBuiltIn=i,wy.set(e,t)};function aw(t,e,n,i){return{eventContent:{selected:Ph(n),isFromClick:e.isFromClick||!1}}}function sw(t){return null==t?0:t.length||1}function lw(t){return t}ew(tx,E_),ew(ex,R_),ew(ex,O_),ew(tx,lb),ew(ex,cb),ew(7e3,function(t,e){t.eachRawSeries(function(n){if(!t.isSeriesFiltered(n)){var i=n.getData();i.hasItemVisual()&&i.each(function(t){var n=i.getItemVisual(t,"decal");n&&(i.ensureUniqueItemVisual(t,"style").decal=Xb(n,e))});var r=i.getVisual("decal");if(r)i.getVisual("style").decal=Xb(r,e)}})}),Kx(Rv),Qx(900,function(t){var e=Sr();t.eachSeries(function(t){var n=t.get("stack");if(n){var i=e.get(n)||e.set(n,[]),r=t.getData(),o={stackResultDimension:r.getCalculationInfo("stackResultDimension"),stackedOverDimension:r.getCalculationInfo("stackedOverDimension"),stackedDimension:r.getCalculationInfo("stackedDimension"),stackedByDimension:r.getCalculationInfo("stackedByDimension"),isStackedByIndex:r.getCalculationInfo("isStackedByIndex"),data:r,seriesModel:t};if(!o.stackedDimension||!o.isStackedByIndex&&!o.stackedByDimension)return;i.push(o)}}),e.each(function(t){0!==t.length&&("seriesDesc"===(t[0].seriesModel.get("stackOrder")||"seriesAsc")&&t.reverse(),Ui(t,function(e,n){e.data.setCalculationInfo("stackedOnSeries",n>0?t[n-1].seriesModel:null)}),function(t){Ui(t,function(e,n){var i=[],r=[NaN,NaN],o=[e.stackResultDimension,e.stackedOverDimension],a=e.data,s=e.isStackedByIndex,l=e.seriesModel.get("stackStrategy")||"samesign";a.modify(o,function(o,c,u){var d,h,p=a.get(e.stackedDimension,u);if(isNaN(p))return r;s?h=a.getRawIndex(u):d=a.get(e.stackedByDimension,u);for(var f=NaN,g=n-1;g>=0;g--){var m=t[g];if(s||(h=m.data.rawIndexOf(m.stackedByDimension,d)),h>=0){var v=m.data.getByRawIndex(m.stackResultDimension,h);if("all"===l||"positive"===l&&v>0||"negative"===l&&v<0||"samesign"===l&&p>=0&&v>0||"samesign"===l&&p<=0&&v<0){p=Yl(p,v),f=v;break}}}return i[0]=p,i[1]=f,i})})}(t))})}),rw("default",function(t,e){Vi(e=e||{},{text:"loading",textColor:Im.color.primary,fontSize:12,fontWeight:"normal",fontStyle:"normal",fontFamily:"sans-serif",maskColor:"rgba(255,255,255,0.8)",showSpinner:!0,color:Im.color.theme[0],spinnerRadius:10,lineWidth:5,zlevel:0});var n=new Nl,i=new Id({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4});n.add(i);var r,o=new Ed({style:{text:e.text,fill:e.textColor,fontSize:e.fontSize,fontWeight:e.fontWeight,fontStyle:e.fontStyle,fontFamily:e.fontFamily},zlevel:e.zlevel,z:10001}),a=new Id({style:{fill:"none"},textContent:o,textConfig:{position:"right",distance:10},zlevel:e.zlevel,z:10001});return n.add(a),e.showSpinner&&((r=new Hp({shape:{startAngle:-z_/2,endAngle:-z_/2+.1,r:e.spinnerRadius},style:{stroke:e.color,lineCap:"round",lineWidth:e.lineWidth},zlevel:e.zlevel,z:10001})).animateShape(!0).when(1e3,{endAngle:3*z_/2}).start("circularInOut"),r.animateShape(!0).when(1e3,{startAngle:3*z_/2}).delay(300).start("circularInOut"),n.add(r)),n.resize=function(){var n=o.getBoundingRect().width,s=e.showSpinner?e.spinnerRadius:0,l=(t.getWidth()-2*s-(e.showSpinner&&n?10:0)-n)/2-(e.showSpinner&&n?0:5+n/2)+(e.showSpinner?0:n/2)+(n?0:s),c=t.getHeight()/2;e.showSpinner&&r.setShape({cx:l,cy:c}),a.setShape({x:l-s,y:c-s,width:2*s,height:2*s}),i.setShape({x:0,y:0,width:t.getWidth(),height:t.getHeight()})},n.resize(),n}),tw({type:Jd,event:Jd,update:Jd},Mr),tw({type:th,event:th,update:th},Mr),tw({type:eh,event:rh,update:eh,action:Mr,refineEvent:aw,publishNonRefinedEvent:!0}),tw({type:nh,event:rh,update:nh,action:Mr,refineEvent:aw,publishNonRefinedEvent:!0}),tw({type:ih,event:rh,update:ih,action:Mr,refineEvent:aw,publishNonRefinedEvent:!0}),Zx("default",{}),Zx("dark",rb);var cw=function(){function t(t,e,n,i,r,o){this._old=t,this._new=e,this._oldKeyGetter=n||lw,this._newKeyGetter=i||lw,this.context=r,this._diffModeMultiple="multiple"===o}return t.prototype.add=function(t){return this._add=t,this},t.prototype.update=function(t){return this._update=t,this},t.prototype.updateManyToOne=function(t){return this._updateManyToOne=t,this},t.prototype.updateOneToMany=function(t){return this._updateOneToMany=t,this},t.prototype.updateManyToMany=function(t){return this._updateManyToMany=t,this},t.prototype.remove=function(t){return this._remove=t,this},t.prototype.execute=function(){this[this._diffModeMultiple?"_executeMultiple":"_executeOneToOne"]()},t.prototype._executeOneToOne=function(){var t=this._old,e=this._new,n={},i=new Array(t.length),r=new Array(e.length);this._initIndexMap(t,null,i,"_oldKeyGetter"),this._initIndexMap(e,n,r,"_newKeyGetter");for(var o=0;o1){var c=s.shift();1===s.length&&(n[a]=s[0]),this._update&&this._update(c,o)}else 1===l?(n[a]=null,this._update&&this._update(s,o)):this._remove&&this._remove(o)}this._performRestAdd(r,n)},t.prototype._executeMultiple=function(){var t=this._old,e=this._new,n={},i={},r=[],o=[];this._initIndexMap(t,n,r,"_oldKeyGetter"),this._initIndexMap(e,i,o,"_newKeyGetter");for(var a=0;a1&&1===d)this._updateManyToOne&&this._updateManyToOne(c,l),i[s]=null;else if(1===u&&d>1)this._updateOneToMany&&this._updateOneToMany(c,l),i[s]=null;else if(1===u&&1===d)this._update&&this._update(c,l),i[s]=null;else if(u>1&&d>1)this._updateManyToMany&&this._updateManyToMany(c,l),i[s]=null;else if(u>1)for(var h=0;h1)for(var a=0;a30}var bw,xw,ww,Sw,Cw,kw,Mw,Tw=rr,Aw=Gi,Iw="undefined"==typeof Int32Array?Array:Int32Array,Dw=["hasItemOption","_nameList","_idList","_invertedIndicesMap","_dimSummary","userOutput","_rawData","_dimValueGetter","_nameDimIdx","_idDimIdx","_nameRepeatCount"],Pw=["_approximateExtent"],Lw=function(){function t(t,e){var n;this.type="list",this._dimOmitted=!1,this._nameList=[],this._idList=[],this._visual={},this._layout={},this._itemVisuals=[],this._itemLayouts=[],this._graphicEls=[],this._approximateExtent={},this._calculationInfo={},this.hasItemOption=!1,this.TRANSFERABLE_METHODS=["cloneShallow","downSample","minmaxDownSample","lttbDownSample","map"],this.CHANGABLE_METHODS=["filterSelf","selectRange"],this.DOWNSAMPLE_METHODS=["downSample","minmaxDownSample","lttbDownSample"];var i=!1;mw(t)?(n=t.dimensions,this._dimOmitted=t.isDimensionOmitted(),this._schema=t):(i=!0,n=t),n=n||["x","y"];for(var r={},o=[],a={},s=!1,l={},c=0;c=e)){var n=this._store.getProvider();this._updateOrdinalMeta();var i=this._nameList,r=this._idList;if(n.getSource().sourceFormat===Bm&&!n.pure)for(var o=[],a=t;a0},t.prototype.ensureUniqueItemVisual=function(t,e){var n=this._itemVisuals,i=n[t];i||(i=n[t]={});var r=i[e];return null==r&&(Ji(r=this.getVisual(e))?r=r.slice():Tw(r)&&(r=Fi({},r)),i[e]=r),r},t.prototype.setItemVisual=function(t,e,n){var i=this._itemVisuals[t]||{};this._itemVisuals[t]=i,Tw(e)?Fi(i,e):i[e]=n},t.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},t.prototype.setLayout=function(t,e){Tw(t)?Fi(this._layout,t):this._layout[t]=e},t.prototype.getLayout=function(t){return this._layout[t]},t.prototype.getItemLayout=function(t){return this._itemLayouts[t]},t.prototype.setItemLayout=function(t,e,n){this._itemLayouts[t]=n?Fi(this._itemLayouts[t]||{},e):e},t.prototype.clearItemLayouts=function(){this._itemLayouts.length=0},t.prototype.setItemGraphicEl=function(t,e){!function(t,e,n,i){if(i){var r=Ud(i);r.dataIndex=n,r.dataType=e,r.seriesIndex=t,r.ssrType="chart","group"===i.type&&i.traverse(function(i){var r=Ud(i);r.seriesIndex=t,r.dataIndex=n,r.dataType=e,r.ssrType="chart"})}}(this.hostModel&&this.hostModel.seriesIndex,this.dataType,t,e),this._graphicEls[t]=e},t.prototype.getItemGraphicEl=function(t){return this._graphicEls[t]},t.prototype.eachItemGraphicEl=function(t,e){Ui(this._graphicEls,function(n,i){n&&t&&t.call(e,n,i)})},t.prototype.cloneShallow=function(e){return e||(e=new t(this._schema?this._schema:Aw(this.dimensions,this._getDimInfo,this),this.hostModel)),Cw(e,this),e._store=this._store,e},t.prototype.wrapMethod=function(t,e){var n=this[t];tr(n)&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(t),this[t]=function(){var t=n.apply(this,arguments);return e.apply(this,[t].concat(pr(arguments)))})},t.internalField=(bw=function(t){var e=t._invertedIndicesMap;Ui(e,function(n,i){var r=t._dimInfos[i],o=r.ordinalMeta,a=t._store;if(o){n=e[i]=new Iw(o.categories.length);for(var s=0;s1&&(s+="__ec__"+c),i[e]=s}})),t}();function Ew(t,e){Wv(t)||(t=qv(t));var n=(e=e||{}).coordDimensions||[],i=e.dimensionsDefine||t.dimensionsDefine||[],r=Sr(),o=[],a=function(t,e,n,i){var r=Math.max(t.dimensionsDetectedCount||1,e.length,n.length,i||0);return Ui(e,function(t){var e;rr(t)&&(e=t.dimsDef)&&(r=Math.max(r,e.length))}),r}(t,n,i,e.dimensionsCount),s=e.canOmitUnusedDimensions&&_w(a),l=i===t.dimensionsDefine,c=l?yw(t):vw(i),u=e.encodeDefine;!u&&e.encodeDefaulter&&(u=e.encodeDefaulter(t,a));for(var d=Sr(u),h=new Iy(a),p=0;p0&&(i.name=r+(o-1)),o++,e.set(r,o)}}(o),new gw({source:t,dimensions:o,fullDimensionCount:a,dimensionOmitted:s})}function Nw(t,e,n){if(n||e.hasKey(t)){for(var i=0;e.hasKey(t+i);)i++;t+=i}return e.set(t,!0),t}var Rw=function(t){this.coordSysDims=[],this.axisMap=Sr(),this.categoryAxisMap=Sr(),this.coordSysName=t};var Ow={cartesian2d:function(t,e,n,i){var r=t.getReferringComponents("xAxis",Tc).models[0],o=t.getReferringComponents("yAxis",Tc).models[0];e.coordSysDims=["x","y"],n.set("x",r),n.set("y",o),zw(r)&&(i.set("x",r),e.firstCategoryDimIndex=0),zw(o)&&(i.set("y",o),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},singleAxis:function(t,e,n,i){var r=t.getReferringComponents("singleAxis",Tc).models[0];e.coordSysDims=["single"],n.set("single",r),zw(r)&&(i.set("single",r),e.firstCategoryDimIndex=0)},polar:function(t,e,n,i){var r=t.getReferringComponents("polar",Tc).models[0],o=r.findAxisModel("radiusAxis"),a=r.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],n.set("radius",o),n.set("angle",a),zw(o)&&(i.set("radius",o),e.firstCategoryDimIndex=0),zw(a)&&(i.set("angle",a),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},geo:function(t,e,n,i){e.coordSysDims=["lng","lat"]},parallel:function(t,e,n,i){var r=t.ecModel,o=r.getComponent("parallel",t.get("parallelIndex")),a=e.coordSysDims=o.dimensions.slice();Ui(o.parallelAxisIndex,function(t,o){var s=r.getComponent("parallelAxis",t),l=a[o];n.set(l,s),zw(s)&&(i.set(l,s),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=o))})},matrix:function(t,e,n,i){var r=t.getReferringComponents("matrix",Tc).models[0];e.coordSysDims=["x","y"];var o=r.getDimensionModel("x"),a=r.getDimensionModel("y");n.set("x",o),n.set("y",a),i.set("x",o),i.set("y",a)}};function zw(t){return"category"===t.get("type")}function Hw(t,e,n){var i,r,o,a=(n=n||{}).byIndex,s=n.stackedCoordDimension;!function(t){return!mw(t.schema)}(e)?(r=e.schema,i=r.dimensions,o=e.store):i=e;var l,c,u,d,h=!(!t||!t.get("stack"));if(Ui(i,function(t,e){er(t)&&(i[e]=t={name:t}),h&&!t.isExtraCoord&&(a||l||!t.ordinalMeta||(l=t),c||"ordinal"===t.type||"time"===t.type||s&&s!==t.coordDim||(c=t))}),!c||a||l||(a=!0),c){u="__\0ecstackresult_"+t.id,d="__\0ecstackedover_"+t.id,l&&(l.createInvertedIndices=!0);var p=c.coordDim,f=c.type,g=0;Ui(i,function(t){t.coordDim===p&&g++});var m={name:u,coordDim:p,coordDimIndex:g,type:f,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length},v={name:d,coordDim:d,coordDimIndex:g+1,type:f,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length+1};r?(o&&(m.storeDimIndex=o.ensureCalculationDimension(d,f),v.storeDimIndex=o.ensureCalculationDimension(u,f)),r.appendCalculationDimension(m),r.appendCalculationDimension(v)):(i.push(m),i.push(v))}return{stackedDimension:c&&c.name,stackedByDimension:l&&l.name,isStackedByIndex:a,stackedOverDimension:d,stackResultDimension:u}}function Bw(t,e){return!!e&&e===t.getCalculationInfo("stackedDimension")}function $w(t,e,n){n=n||{};var i,r,o=e.getSourceManager();r=(i=o.getSource()).sourceFormat===Bm;var a=function(t){var e=t.get("coordinateSystem"),n=new Rw(e),i=Ow[e];if(i)return i(t,n,n.axisMap,n.categoryAxisMap),n}(e),s=function(t,e){var n,i=t.get("coordinateSystem"),r=cm.get(i);return e&&e.coordSysDims&&(n=Gi(e.coordSysDims,function(t){var n={name:t},i=e.axisMap.get(t);if(i){var r=i.get("type");n.type=function(t){return"category"===t?"ordinal":"time"===t?"time":"float"}(r)}return n})),n||(n=r&&(r.getDimensionsInfo?r.getDimensionsInfo():r.dimensions.slice())||["x","y"]),n}(e,a),l=n.useEncodeDefaulter,c=tr(l)?l:l?Qi(Km,s,e):null,u=Ew(i,{coordDimensions:s,generateCoord:n.generateCoord,encodeDefine:e.getEncode(),encodeDefaulter:c,canOmitUnusedDimensions:!r}),d=function(t,e,n){var i,r;return n&&Ui(t,function(t,o){var a=t.coordDim,s=n.categoryAxisMap.get(a);s&&(null==i&&(i=o),t.ordinalMeta=s.getOrdinalMeta(),e&&(t.createInvertedIndices=!0)),null!=t.otherDims.itemName&&(r=!0)}),r||null==i||(t[i].otherDims.itemName=0),i}(u.dimensions,n.createInvertedIndices,a),h=r?null:o.getSharedDataStore(u),p=Hw(e,{schema:u,store:h}),f=new Lw(u,e);f.setCalculationInfo(p);var g=null!=d&&function(t){if(t.sourceFormat===Bm){var e=function(t){var e=0;for(;er&&(a=o.interval=r);var s=o.intervalPrecision=jw(a);return function(t,e){!isFinite(t[0])&&(t[0]=e[0]),!isFinite(t[1])&&(t[1]=e[1]),qw(t,0,e),qw(t,1,e),t[0]>t[1]&&(t[0]=t[1])}(o.niceTickExtent=[Gl(Math.ceil(t[0]/a)*a,s),Gl(Math.floor(t[1]/a)*a,s)],t),o}function Ww(t){var e=Math.pow(10,tc(t)),n=t/e;return n?2===n?n=3:3===n?n=5:n*=2:n=1,Gl(n*e)}function jw(t){return Xl(t)+2}function qw(t,e,n){t[e]=Math.max(Math.min(t[e],n[1]),n[0])}function Uw(t,e){return t>=e[0]&&t<=e[1]}var Gw=function(){function t(){this.normalize=Xw,this.scale=Yw}return t.prototype.updateMethods=function(t){t.hasBreaks()?(this.normalize=Ki(t.normalize,t),this.scale=Ki(t.scale,t)):(this.normalize=Xw,this.scale=Yw)},t}();function Xw(t,e){return e[1]===e[0]?.5:(t-e[0])/(e[1]-e[0])}function Yw(t,e){return t*(e[1]-e[0])+e[0]}function Zw(t,e,n){var i=Math.log(t);return[Math.log(n?e[0]:Math.max(0,e[0]))/i,Math.log(n?e[1]:Math.max(0,e[1]))/i]}var Kw=function(){function t(t){this._calculator=new Gw,this._setting=t||{},this._extent=[1/0,-1/0]}return t.prototype.getSetting=function(t){return this._setting[t]},t.prototype._innerUnionExtent=function(t){var e=this._extent;this._innerSetExtent(t[0]e[1]?t[1]:e[1])},t.prototype.unionExtentFromData=function(t,e){this._innerUnionExtent(t.getApproximateExtent(e))},t.prototype.getExtent=function(){return this._extent.slice()},t.prototype.setExtent=function(t,e){this._innerSetExtent(t,e)},t.prototype._innerSetExtent=function(t,e){var n=this._extent;isNaN(t)||(n[0]=t),isNaN(e)||(n[1]=e),this._brkCtx&&this._brkCtx.update(n)},t.prototype.setBreaksFromOption=function(t){},t.prototype._innerSetBreak=function(t){this._brkCtx&&(this._brkCtx.setBreaks(t),this._calculator.updateMethods(this._brkCtx),this._brkCtx.update(this._extent))},t.prototype._innerGetBreaks=function(){return this._brkCtx?this._brkCtx.breaks:[]},t.prototype.hasBreaks=function(){return!!this._brkCtx&&this._brkCtx.hasBreaks()},t.prototype._getExtentSpanWithBreaks=function(){return this._brkCtx&&this._brkCtx.hasBreaks()?this._brkCtx.getExtentSpan():this._extent[1]-this._extent[0]},t.prototype.isInExtentRange=function(t){return this._extent[0]<=t&&this._extent[1]>=t},t.prototype.isBlank=function(){return this._isBlank},t.prototype.setBlank=function(t){this._isBlank=t},t}();Hc(Kw);var Qw=0,Jw=function(){function t(t){this.categories=t.categories||[],this._needCollect=t.needCollect,this._deduplication=t.deduplication,this.uid=++Qw,this._onCollect=t.onCollect}return t.createByAxisModel=function(e){var n=e.option,i=n.data,r=i&&Gi(i,tS);return new t({categories:r,needCollect:!r,deduplication:!1!==n.dedplication})},t.prototype.getOrdinal=function(t){return this._getOrCreateMap().get(t)},t.prototype.parseAndCollect=function(t){var e,n=this._needCollect;if(!er(t)&&!n)return t;if(n&&!this._deduplication)return e=this.categories.length,this.categories[e]=t,this._onCollect&&this._onCollect(t,e),e;var i=this._getOrCreateMap();return null==(e=i.get(t))&&(n?(e=this.categories.length,this.categories[e]=t,i.set(t,e),this._onCollect&&this._onCollect(t,e)):e=NaN),e},t.prototype._getOrCreateMap=function(){return this._map||(this._map=Sr(this.categories))},t}();function tS(t){return rr(t)&&null!=t.value?t.value:t+""}var eS=function(t){function e(e){var n=t.call(this,e)||this;n.type="ordinal";var i=n.getSetting("ordinalMeta");return i||(i=new Jw({})),Ji(i)&&(i=new Jw({categories:Gi(i,function(t){return rr(t)?t.value:t})})),n._ordinalMeta=i,n._extent=n.getSetting("extent")||[0,i.categories.length-1],n}return S(e,t),e.prototype.parse=function(t){return null==t?NaN:er(t)?this._ordinalMeta.getOrdinal(t):Math.round(t)},e.prototype.contain=function(t){return Uw(t,this._extent)&&t>=0&&t=0&&t=0&&t=t},e.prototype.getOrdinalMeta=function(){return this._ordinalMeta},e.prototype.calcNiceTicks=function(){},e.prototype.calcNiceExtent=function(){},e.type="ordinal",e}(Kw);Kw.registerClass(eS);var nS=Gl,iS=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="interval",e._interval=0,e._intervalPrecision=2,e}return S(e,t),e.prototype.parse=function(t){return null==t||""===t?NaN:Number(t)},e.prototype.contain=function(t){return Uw(t,this._extent)},e.prototype.normalize=function(t){return this._calculator.normalize(t,this._extent)},e.prototype.scale=function(t){return this._calculator.scale(t,this._extent)},e.prototype.getInterval=function(){return this._interval},e.prototype.setInterval=function(t){this._interval=t,this._niceExtent=this._extent.slice(),this._intervalPrecision=jw(t)},e.prototype.getTicks=function(t){t=t||{};var e=this._interval,n=this._extent,i=this._niceExtent,r=this._intervalPrecision,o=[];if(!e)return o;t.breakTicks;n[0]=0&&(s=nS(s+l*e,r))}if(o.length>0&&s===o[o.length-1].value)break;if(o.length>1e4)return[]}var c=o.length?o[o.length-1].value:i[1];return n[1]>c&&(t.expandToNicedExtent?o.push({value:nS(c+e,r)}):o.push({value:n[1]})),t.breakTicks,o},e.prototype.getMinorTicks=function(t){for(var e=this.getTicks({expandToNicedExtent:!0}),n=[],i=this.getExtent(),r=1;ri[0]&&d0&&(o=null===o?s:Math.min(o,s))}n[i]=o}}return n}(t),n=[];return Ui(t,function(t){var i,r=t.coordinateSystem.getBaseAxis(),o=r.getExtent();if("category"===r.type)i=r.getBandWidth();else if("value"===r.type||"time"===r.type){var a=r.dim+"_"+r.index,s=e[a],l=Math.abs(o[1]-o[0]),c=r.scale.getExtent(),u=Math.abs(c[1]-c[0]);i=s?l/u*s:l}else{var d=t.getData();i=Math.abs(o[1]-o[0])/d.count()}var h=ql(t.get("barWidth"),i),p=ql(t.get("barMaxWidth"),i),f=ql(t.get("barMinWidth")||(function(t){return t.pipelineContext&&t.pipelineContext.large}(t)?.5:1),i),g=t.get("barGap"),m=t.get("barCategoryGap"),v=t.get("defaultBarGap");n.push({bandWidth:i,barWidth:h,barMaxWidth:p,barMinWidth:f,barGap:g,barCategoryGap:m,defaultBarGap:v,axisKey:lS(r),stackId:sS(t)})}),function(t){var e={};Ui(t,function(t,n){var i=t.axisKey,r=t.bandWidth,o=e[i]||{bandWidth:r,remainedWidth:r,autoWidthCount:0,categoryGap:null,gap:t.defaultBarGap||0,stacks:{}},a=o.stacks;e[i]=o;var s=t.stackId;a[s]||o.autoWidthCount++,a[s]=a[s]||{width:0,maxWidth:0};var l=t.barWidth;l&&!a[s].width&&(a[s].width=l,l=Math.min(o.remainedWidth,l),o.remainedWidth-=l);var c=t.barMaxWidth;c&&(a[s].maxWidth=c);var u=t.barMinWidth;u&&(a[s].minWidth=u);var d=t.barGap;null!=d&&(o.gap=d);var h=t.barCategoryGap;null!=h&&(o.categoryGap=h)});var n={};return Ui(e,function(t,e){n[e]={};var i=t.stacks,r=t.bandWidth,o=t.categoryGap;if(null==o){var a=Zi(i).length;o=Math.max(35-4*a,15)+"%"}var s=ql(o,r),l=ql(t.gap,1),c=t.remainedWidth,u=t.autoWidthCount,d=(c-s)/(u+(u-1)*l);d=Math.max(d,0),Ui(i,function(t){var e=t.maxWidth,n=t.minWidth;if(t.width){i=t.width;e&&(i=Math.min(i,e)),n&&(i=Math.max(i,n)),t.width=i,c-=i+l*i,u--}else{var i=d;e&&ei&&(i=n),i!==d&&(t.width=i,c-=i+l*i,u--)}}),d=(c-s)/(u+(u-1)*l),d=Math.max(d,0);var h,p=0;Ui(i,function(t,e){t.width||(t.width=d),h=t,p+=t.width*(1+l)}),h&&(p-=h.width*l);var f=-p/2;Ui(i,function(t,i){n[e][i]=n[e][i]||{bandWidth:r,offset:f,width:t.width},f+=t.width*(1+l)})}),n}(n)}var uS=function(t){function e(e){var n=t.call(this,e)||this;return n.type="time",n}return S(e,t),e.prototype.getLabel=function(t){var e=this.getSetting("useUTC");return Og(t.value,Ig[function(t){switch(t){case"year":case"month":return"day";case"millisecond":return"millisecond";default:return"second"}}(Ng(this._minLevelUnit))]||Ig.second,e,this.getSetting("locale"))},e.prototype.getFormattedLabel=function(t,e,n){var i=this.getSetting("useUTC");return function(t,e,n,i,r){var o=null;if(er(n))o=n;else if(tr(n)){var a={time:t.time,level:t.time.level},s=null;s&&s.makeAxisLabelFormatterParamBreak(a,t.break),o=n(t.value,e,a)}else{var l=t.time;if(l){var c=n[l.lowerTimeUnit][l.upperTimeUnit];o=c[Math.min(l.level,c.length-1)]||""}else{var u=zg(t.value,r);o=n[u][u][0]}}return Og(new Date(t.value),o,r,i)}(t,e,n,this.getSetting("locale"),i)},e.prototype.getTicks=function(t){var e=this._interval,n=this._extent,i=[];if(!e)return i;var r=this.getSetting("useUTC"),o=zg(n[1],r);i.push({value:n[0],time:{level:0,upperTimeUnit:o,lowerTimeUnit:o}});var a=function(t,e,n,i,r,o){var a=1e4,s=Pg,l=0;function c(t,e,n,r,s,c,u){for(var d=function(t,e){var n=new Date(0);n[t](1);var i=n.getTime();n[t](1+e);var r=n.getTime()-i;return function(t,e){return Math.max(0,Math.round((e-t)/r))}}(s,t),h=e,p=new Date(h);ha));)if(p[s](p[r]()+t),h=p.getTime(),o){var f=o.calcNiceTickMultiple(h,d);f>0&&(p[s](p[r]()+f*t),h=p.getTime())}u.push({value:h,notAdd:!0})}function u(t,r,o){var a=[],s=!r.length;if(!function(t,e,n,i){return Hg(new Date(e),t,i).getTime()===Hg(new Date(n),t,i).getTime()}(Ng(t),i[0],i[1],n)){s&&(r=[{value:vS(i[0],t,n)},{value:i[1]}]);for(var l=0;l=i[0]&&u<=i[1]&&c(h,u,d,p,f,g,a),"year"===t&&o.length>1&&0===l&&o.unshift({value:o[0].value-h})}}for(l=0;l=i[0]&&_<=i[1]&&p++)}var b=r/e;if(p>1.5*b&&f>b/1.5)break;if(d.push(v),p>b||t===s[g])break}h=[]}}var x=Yi(Gi(d,function(t){return Yi(t,function(t){return t.value>=i[0]&&t.value<=i[1]&&!t.notAdd})}),function(t){return t.length>0}),w=[],S=x.length-1;for(g=0;gn&&(this._approxInterval=n);var r=dS.length,o=Math.min(function(t,e,n,i){for(;n>>1;t[r][1]16?16:t>7.5?7:t>3.5?4:t>1.5?2:1}function pS(t){return(t/=2592e6)>6?6:t>3?3:t>2?2:1}function fS(t){return(t/=Sg)>12?12:t>6?6:t>3.5?4:t>2?2:1}function gS(t,e){return(t/=e?wg:xg)>30?30:t>20?20:t>15?15:t>10?10:t>5?5:t>2?2:1}function mS(t){return ec(t)}function vS(t,e,n){var i=Math.max(0,Wi(Dg,e)-1);return Hg(new Date(t),Dg[i],n).getTime()}Kw.registerClass(uS);var yS=Gl,_S=Math.floor,bS=Math.ceil,xS=Math.pow,wS=Math.log,SS=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="log",e.base=10,e._originalScale=new iS,e}return S(e,t),e.prototype.getTicks=function(e){e=e||{};var n=this._extent.slice(),i=this._originalScale.getExtent(),r=t.prototype.getTicks.call(this,e),o=this.base;return this._originalScale._innerGetBreaks(),Gi(r,function(t){var e=t.value,r=null,a=xS(o,e);return e===n[0]&&this._fixMin?r=i[0]:e===n[1]&&this._fixMax&&(r=i[1]),null!=r&&(a=CS(a,r)),{value:a,break:void 0}},this)},e.prototype._getNonTransBreaks=function(){return this._originalScale._innerGetBreaks()},e.prototype.setExtent=function(e,n){this._originalScale.setExtent(e,n);var i=Zw(this.base,[e,n]);t.prototype.setExtent.call(this,i[0],i[1])},e.prototype.getExtent=function(){var e=this.base,n=t.prototype.getExtent.call(this);n[0]=xS(e,n[0]),n[1]=xS(e,n[1]);var i=this._originalScale.getExtent();return this._fixMin&&(n[0]=CS(n[0],i[0])),this._fixMax&&(n[1]=CS(n[1],i[1])),n},e.prototype.unionExtentFromData=function(t,e){this._originalScale.unionExtentFromData(t,e);var n=Zw(this.base,t.getApproximateExtent(e),!0);this._innerUnionExtent(n)},e.prototype.calcNiceTicks=function(t){t=t||10;var e=this._extent.slice(),n=this._getExtentSpanWithBreaks();if(isFinite(n)&&!(n<=0)){var i,r=(i=n,Math.pow(10,tc(i)));for(t/n*r<=.5&&(r*=10);!isNaN(r)&&Math.abs(r)<1&&Math.abs(r)>0;)r*=10;var o=[yS(bS(e[0]/r)*r),yS(_S(e[1]/r)*r)];this._interval=r,this._intervalPrecision=jw(r),this._niceExtent=o}},e.prototype.calcNiceExtent=function(e){t.prototype.calcNiceExtent.call(this,e),this._fixMin=e.fixMin,this._fixMax=e.fixMax},e.prototype.contain=function(e){return e=wS(e)/wS(this.base),t.prototype.contain.call(this,e)},e.prototype.normalize=function(e){return e=wS(e)/wS(this.base),t.prototype.normalize.call(this,e)},e.prototype.scale=function(e){return e=t.prototype.scale.call(this,e),xS(this.base,e)},e.prototype.setBreaksFromOption=function(t){},e.type="log",e}(iS);function CS(t,e){return yS(t,Xl(e))}Kw.registerClass(SS);var kS=function(){function t(t,e,n){this._prepareParams(t,e,n)}return t.prototype._prepareParams=function(t,e,n){n[1]0&&s>0&&!l&&(a=0),a<0&&s<0&&!c&&(s=0));var d=this._determinedMin,h=this._determinedMax;return null!=d&&(a=d,l=!0),null!=h&&(s=h,c=!0),{min:a,max:s,minFixed:l,maxFixed:c,isBlank:u}},t.prototype.modifyDataMinMax=function(t,e){this[TS[t]]=e},t.prototype.setDeterminedMinMax=function(t,e){this[MS[t]]=e},t.prototype.freeze=function(){this.frozen=!0},t}(),MS={min:"_determinedMin",max:"_determinedMax"},TS={min:"_dataMin",max:"_dataMax"};function AS(t,e){return null==e?null:cr(e)?NaN:t.parse(e)}function IS(t,e){var n=t.type,i=function(t,e,n){var i=t.rawExtentInfo;return i||(i=new kS(t,e,n),t.rawExtentInfo=i,i)}(t,e,t.getExtent()).calculate();t.setBlank(i.isBlank);var r=i.min,o=i.max,a=e.ecModel;if(a&&"time"===n){var s=function(t,e){var n=[];return e.eachSeriesByType(t,function(t){(function(t){return t.coordinateSystem&&"cartesian2d"===t.coordinateSystem.type})(t)&&n.push(t)}),n}("bar",a),l=!1;if(Ui(s,function(t){l=l||t.getBaseAxis()===e.axis}),l){var c=cS(s),u=function(t,e,n,i){var r=n.axis.getExtent(),o=Math.abs(r[1]-r[0]),a=function(t,e){if(t&&e)return t[lS(e)]}(i,n.axis);if(void 0===a)return{min:t,max:e};var s=1/0;Ui(a,function(t){s=Math.min(t.offset,s)});var l=-1/0;Ui(a,function(t){l=Math.max(t.offset+t.width,l)}),s=Math.abs(s),l=Math.abs(l);var c=s+l,u=e-t,d=u/(1-(s+l)/o)-u;return e+=d*(l/c),t-=d*(s/c),{min:t,max:e}}(r,o,e,c);r=u.min,o=u.max}}return{extent:[r,o],fixMin:i.minFixed,fixMax:i.maxFixed}}function DS(t,e){var n=e,i=IS(t,n),r=i.extent,o=n.get("splitNumber");t instanceof SS&&(t.base=n.get("logBase"));var a=t.type,s=n.get("interval"),l="interval"===a||"time"===a;t.setBreaksFromOption(HS(n)),t.setExtent(r[0],r[1]),t.calcNiceExtent({splitNumber:o,fixMin:i.fixMin,fixMax:i.fixMax,minInterval:l?n.get("minInterval"):null,maxInterval:l?n.get("maxInterval"):null}),null!=s&&t.setInterval&&t.setInterval(s)}function PS(t){var e=t.getLabelModel().get("formatter");if("time"===t.type){var n=Lg(e);return function(e,i){return t.scale.getFormattedLabel(e,i,n)}}if(er(e))return function(n){var i=t.scale.getLabel(n);return e.replace("{value}",null!=i?i:"")};if(tr(e)){if("category"===t.type)return function(n,i){return e(LS(t,n),n.value-t.scale.getExtent()[0],null)};var i=null;return function(n,r){var o=null;return i&&(o=i.makeAxisLabelFormatterParamBreak(o,n.break)),e(LS(t,n),r,o)}}return function(e){return t.scale.getLabel(e)}}function LS(t,e){return"category"===t.type?t.scale.getLabel(e):e.value}function ES(t){var e=t.get("interval");return null==e?"auto":e}function NS(t){return"category"===t.type&&0===ES(t.getLabelModel())}function RS(t,e){var n={};return Ui(t.mapDimensionsAll(e),function(e){n[function(t,e){return Bw(t,e)?t.getCalculationInfo("stackResultDimension"):e}(t,e)]=!0}),Zi(n)}function OS(t){return"middle"===t||"center"===t}function zS(t){return t.getShallow("show")}function HS(t){t.get("breaks",!0)}var BS=function(){function t(){}return t.prototype.getNeedCrossZero=function(){return!this.option.scale},t.prototype.getCoordSysModel=function(){},t}(),$S=[],FS={registerPreprocessor:Kx,registerProcessor:Qx,registerPostInit:function(t){Jx("afterinit",t)},registerPostUpdate:function(t){Jx("afterupdate",t)},registerUpdateLifecycle:Jx,registerAction:tw,registerCoordinateSystem:function(t,e){cm.register(t,e)},registerLayout:function(t,e){iw(Vx,t,e,1e3,"layout")},registerVisual:ew,registerTransform:ow,registerLoading:rw,registerMap:function(t,e,n){var i=Jb["registerMap"];i&&i(t,e,n)},registerImpl:function(t,e){Jb[t]=e},PRIORITY:nx,ComponentModel:Am,ComponentView:h_,SeriesModel:r_,ChartView:m_,registerComponentModel:function(t){Am.registerClass(t)},registerComponentView:function(t){h_.registerClass(t)},registerSeriesModel:function(t){r_.registerClass(t)},registerChartView:function(t){m_.registerClass(t)},registerCustomSeries:function(t,e){},registerSubTypeDefaulter:function(t,e){Am.registerSubTypeDefaulter(t,e)},registerPainter:function(t,e){var n;n=e,Rl[t]=n}};function VS(t){Ji(t)?Ui(t,function(t){VS(t)}):Wi($S,t)>=0||($S.push(t),tr(t)&&(t={install:t}),t.install(FS))}var WS=Sc(),jS=Sc(),qS=1,US=2;function GS(t){return{out:{noPxChangeTryDetermine:[]},kind:t}}function XS(t,e){var n=Gi(e,function(e){return t.scale.parse(e)});return"time"===t.type&&n.length>0&&(n.sort(),n.unshift(n[0]),n.push(n[n.length-1])),n}function YS(t,e){var n=t.getLabelModel().get("customValues");if(n){var i=PS(t),r=t.scale.getExtent();return{labels:Gi(Yi(XS(t,n),function(t){return t>=r[0]&&t<=r[1]}),function(e){var n={value:e};return{formattedLabel:i(n),rawLabel:t.scale.getLabel(n),tickValue:e,time:void 0,break:void 0}})}}return"category"===t.type?function(t,e){var n=t.getLabelModel(),i=KS(t,n,e);return!n.get("show")||t.scale.isBlank()?{labels:[]}:i}(t,e):function(t){var e=t.scale.getTicks(),n=PS(t);return{labels:Gi(e,function(e,i){return{formattedLabel:n(e,i),rawLabel:t.scale.getLabel(e),tickValue:e.value,time:e.time,break:e.break}})}}(t)}function ZS(t,e,n){var i=t.getTickModel().get("customValues");if(i){var r=t.scale.getExtent();return{ticks:Yi(XS(t,i),function(t){return t>=r[0]&&t<=r[1]})}}return"category"===t.type?function(t,e){var n,i,r=QS(t),o=ES(e),a=eC(r,o);if(a)return a;e.get("show")&&!t.scale.isBlank()||(n=[]);if(tr(o))n=aC(t,o,!0);else if("auto"===o){var s=KS(t,t.getLabelModel(),GS(US));i=s.labelCategoryInterval,n=Gi(s.labels,function(t){return t.tickValue})}else n=oC(t,i=o,!0);return nC(r,o,{ticks:n,tickCategoryInterval:i})}(t,e):{ticks:Gi(t.scale.getTicks(n),function(t){return t.value})}}function KS(t,e,n){var i,r,o=JS(t),a=ES(e),s=n.kind===qS;if(!s){var l=eC(o,a);if(l)return l}tr(a)?i=aC(t,a):(r="auto"===a?function(t,e){if(e.kind===qS){var n=t.calculateCategoryInterval(e);return e.out.noPxChangeTryDetermine.push(function(){return jS(t).autoInterval=n,!0}),n}var i=jS(t).autoInterval;return null!=i?i:jS(t).autoInterval=t.calculateCategoryInterval(e)}(t,n):a,i=oC(t,r));var c={labels:i,labelCategoryInterval:r};return s?n.out.noPxChangeTryDetermine.push(function(){return nC(o,a,c),!0}):nC(o,a,c),c}var QS=tC("axisTick"),JS=tC("axisLabel");function tC(t){return function(e){return jS(e)[t]||(jS(e)[t]={list:[]})}}function eC(t,e){for(var n=0;ne&&i.axisExtent0===r[0]&&i.axisExtent1===r[1])return o;i.lastTickCount=n,i.lastAutoInterval=e,i.axisExtent0=r[0],i.axisExtent1=r[1]}function oC(t,e,n){var i=PS(t),r=t.scale,o=r.getExtent(),a=t.getLabelModel(),s=[],l=Math.max((e||0)+1,1),c=o[0],u=r.count();0!==c&&l>1&&u/l>2&&(c=Math.round(Math.ceil(c/l)*l));var d=NS(t),h=a.get("showMinLabel")||d,p=a.get("showMaxLabel")||d;h&&c!==o[0]&&g(o[0]);for(var f=c;f<=o[1];f+=l)g(f);function g(t){var e={value:t};s.push(n?t:{formattedLabel:i(e),rawLabel:r.getLabel(e),tickValue:t,time:void 0,break:void 0})}return p&&f-l!==o[1]&&g(o[1]),s}function aC(t,e,n){var i=t.scale,r=PS(t),o=[];return Ui(i.getTicks(),function(t){var a=i.getLabel(t),s=t.value;e(t.value,a)&&o.push(n?s:{formattedLabel:r(t),rawLabel:a,tickValue:s,time:void 0,break:void 0})}),o}var sC=[0,1],lC=function(){function t(t,e,n){this.onBand=!1,this.inverse=!1,this.dim=t,this.scale=e,this._extent=n||[0,0]}return t.prototype.contain=function(t){var e=this._extent,n=Math.min(e[0],e[1]),i=Math.max(e[0],e[1]);return t>=n&&t<=i},t.prototype.containData=function(t){return this.scale.contain(this.scale.parse(t))},t.prototype.getExtent=function(){return this._extent.slice()},t.prototype.getPixelPrecision=function(t){return function(t,e){var n=Math.log,i=Math.LN10,r=Math.floor(n(t[1]-t[0])/i),o=Math.round(n(Wl(e[1]-e[0]))/i),a=Math.min(Math.max(-r+o,0),20);return isFinite(a)?a:20}(t||this.scale.getExtent(),this._extent)},t.prototype.setExtent=function(t,e){var n=this._extent;n[0]=t,n[1]=e},t.prototype.dataToCoord=function(t,e){var n=this._extent,i=this.scale;return t=i.normalize(i.parse(t)),this.onBand&&"ordinal"===i.type&&cC(n=n.slice(),i.count()),jl(t,sC,n,e)},t.prototype.coordToData=function(t,e){var n=this._extent,i=this.scale;this.onBand&&"ordinal"===i.type&&cC(n=n.slice(),i.count());var r=jl(t,n,sC,e);return this.scale.scale(r)},t.prototype.pointToData=function(t,e){},t.prototype.getTicksCoords=function(t){var e=(t=t||{}).tickModel||this.getTickModel(),n=Gi(ZS(this,e,{breakTicks:t.breakTicks,pruneByBreak:t.pruneByBreak}).ticks,function(t){return{coord:this.dataToCoord("ordinal"===this.scale.type?this.scale.getRawOrdinalNumber(t):t),tickValue:t}},this);return function(t,e,n,i){var r=e.length;if(!t.onBand||n||!r)return;var o,a,s=t.getExtent();if(1===r)e[0].coord=s[0],e[0].onBand=!0,o=e[1]={coord:s[1],tickValue:e[0].tickValue,onBand:!0};else{var l=e[r-1].tickValue-e[0].tickValue,c=(e[r-1].coord-e[0].coord)/l;Ui(e,function(t){t.coord-=c/2,t.onBand=!0});var u=t.scale.getExtent();a=1+u[1]-e[r-1].tickValue,o={coord:e[r-1].coord+c*a,tickValue:u[1]+1,onBand:!0},e.push(o)}var d=s[0]>s[1];h(e[0].coord,s[0])&&(i?e[0].coord=s[0]:e.shift());i&&h(s[0],e[0].coord)&&e.unshift({coord:s[0],onBand:!0});h(s[1],o.coord)&&(i?o.coord=s[1]:e.pop());i&&h(o.coord,s[1])&&e.push({coord:s[1],onBand:!0});function h(t,e){return t=Gl(t),e=Gl(e),d?t>e:t0&&t<100||(t=5),Gi(this.scale.getMinorTicks(t),function(t){return Gi(t,function(t){return{coord:this.dataToCoord(t),tickValue:t}},this)},this)},t.prototype.getViewLabels=function(t){return YS(this,t=t||GS(US)).labels},t.prototype.getLabelModel=function(){return this.model.getModel("axisLabel")},t.prototype.getTickModel=function(){return this.model.getModel("axisTick")},t.prototype.getBandWidth=function(){var t=this._extent,e=this.scale.getExtent(),n=e[1]-e[0]+(this.onBand?1:0);0===n&&(n=1);var i=Math.abs(t[1]-t[0]);return Math.abs(i)/n},t.prototype.calculateCategoryInterval=function(t){return function(t,e){var n=e.kind,i=function(t){var e=t.getLabelModel();return{axisRotate:t.getRotate?t.getRotate():t.isHorizontal&&!t.isHorizontal()?90:0,labelRotate:e.get("rotate")||0,font:e.getFont()}}(t),r=PS(t),o=(i.axisRotate-i.labelRotate)/180*Math.PI,a=t.scale,s=a.getExtent(),l=a.count();if(s[1]-s[0]<1)return 0;var c=1;l>40&&(c=Math.max(1,Math.floor(l/40)));for(var u=s[0],d=t.dataToCoord(u+1)-t.dataToCoord(u),h=Math.abs(d*Math.cos(o)),p=Math.abs(d*Math.sin(o)),f=0,g=0;u<=s[1];u+=c){var m,v,y=vl(r({value:u}),i.font,"center","top");m=1.3*y.width,v=1.3*y.height,f=Math.max(f,m,7),g=Math.max(g,v,7)}var _=f/h,b=g/p;isNaN(_)&&(_=1/0),isNaN(b)&&(b=1/0);var x=Math.max(0,Math.floor(Math.min(_,b)));if(n===qS)return e.out.noPxChangeTryDetermine.push(Ki(iC,null,t,x,l)),x;var w=rC(t,x,l);return null!=w?w:x}(this,t=t||GS(US))},t}();function cC(t,e){var n=(t[1]-t[0])/e/2;t[0]+=n,t[1]-=n}var uC=["label","labelLine","layoutOption","priority","defaultAttr","marginForce","minMarginForce","marginDefault","suggestIgnore"];function dC(t,e,n){n=n||3,e?t.dirty|=n:t.dirty&=~n}function hC(t,e){return e=e||3,null==t.dirty||!!(t.dirty&e)}function pC(t){if(t)return hC(t)&&function(t,e,n){var i=e.getComputedTransform();t.transform=Rf(t.transform,i);var r=t.localRect=Nf(t.localRect,e.getBoundingRect()),o=e.style,a=o.margin,s=n&&n.marginForce,l=n&&n.minMarginForce,c=n&&n.marginDefault,u=o.__marginType;null==u&&c&&(a=c,u=Jf.textMargin);for(var d=0;d<4;d++)fC[d]=u===Jf.minMargin&&l&&null!=l[d]?l[d]:s&&null!=s[d]?s[d]:a?a[d]:0;u===Jf.textMargin&&Mf(r,fC,!1,!1);var h=t.rect=Nf(t.rect,r);i&&h.applyTransform(i);u===Jf.minMargin&&Mf(h,fC,!1,!1);t.axisAligned=Lf(i),(t.label=t.label||{}).ignore=e.ignore,dC(t,!1),dC(t,!0,2)}(t,t.label,t),t}var fC=[0,0,0,0];function gC(t,e){for(var n=0;n-1&&(s.style.stroke=s.style.fill,s.style.fill=Im.color.neutral00,s.style.lineWidth=2),e},e.type="series.line",e.dependencies=["grid","polar"],e.defaultOption={z:3,coordinateSystem:"cartesian2d",legendHoverLink:!0,clip:!0,label:{position:"top"},endLabel:{show:!1,valueAnimation:!0,distance:8},lineStyle:{width:2,type:"solid"},emphasis:{scale:!0},step:!1,smooth:!1,smoothMonotone:null,symbol:"emptyCircle",symbolSize:6,symbolRotate:null,showSymbol:!0,showAllSymbol:"auto",connectNulls:!1,sampling:"none",animationEasing:"linear",progressive:0,hoverLayerThreshold:1/0,universalTransition:{divideShape:"clone"},triggerLineEvent:!1},e}(r_);function _C(t,e){var n=t.mapDimensionsAll("defaultedLabel"),i=n.length;if(1===i){var r=ly(t,e,n[0]);return null!=r?r+"":null}if(i){for(var o=[],a=0;a0?+h:1;M.scaleX=this._sizeX*T,M.scaleY=this._sizeY*T,this.setSymbolScale(1),Eh(this,l,c,u)},e.prototype.setSymbolScale=function(t){this.scaleX=this.scaleY=t},e.prototype.fadeOut=function(t,e,n){var i=this.childAt(0),r=Ud(this).dataIndex,o=n&&n.animation;if(this.silent=i.silent=!0,n&&n.fadeLabel){var a=i.getTextContent();a&&af(a,{style:{opacity:0}},e,{dataIndex:r,removeOpt:o,cb:function(){i.removeTextContent()}})}else i.removeTextContent();af(i,{style:{opacity:0},scaleX:0,scaleY:0},e,{dataIndex:r,cb:t,removeOpt:o})},e.getSymbolSize=function(t,e){return Ji(n=t.getItemVisual(e,"symbolSize"))||(n=[+n,+n]),[n[0]||0,n[1]||0];var n},e.getSymbolZ2=function(t,e){return t.getItemVisual(e,"z2")},e}(Nl);function xC(t,e){this.parent.drift(t,e)}function wC(t,e,n,i){return e&&!isNaN(e[0])&&!isNaN(e[1])&&!(i.isIgnore&&i.isIgnore(n))&&!(i.clipShape&&!i.clipShape.contain(e[0],e[1]))&&"none"!==t.getItemVisual(n,"symbol")}function SC(t){return null==t||rr(t)||(t={isIgnore:t}),t||{}}function CC(t){var e=t.hostModel,n=e.getModel("emphasis");return{emphasisItemStyle:n.getModel("itemStyle").getItemStyle(),blurItemStyle:e.getModel(["blur","itemStyle"]).getItemStyle(),selectItemStyle:e.getModel(["select","itemStyle"]).getItemStyle(),focus:n.get("focus"),blurScope:n.get("blurScope"),emphasisDisabled:n.get("disabled"),hoverScale:n.get("scale"),labelStatesModels:Wf(e),cursorStyle:e.get("cursor")}}var kC=function(){function t(t){this.group=new Nl,this._SymbolCtor=t||bC}return t.prototype.updateData=function(t,e){this._progressiveEls=null,e=SC(e);var n=this.group,i=t.hostModel,r=this._data,o=this._SymbolCtor,a=e.disableAnimation,s=CC(t),l={disableAnimation:a},c=e.getSymbolPoint||function(e){return t.getItemLayout(e)};r||n.removeAll(),t.diff(r).add(function(i){var r=c(i);if(wC(t,r,i,e)){var a=new o(t,i,s,l);a.setPosition(r),t.setItemGraphicEl(i,a),n.add(a)}}).update(function(u,d){var h=r.getItemGraphicEl(d),p=c(u);if(wC(t,p,u,e)){var f=t.getItemVisual(u,"symbol")||"circle",g=h&&h.getSymbolType&&h.getSymbolType();if(!h||g&&g!==f)n.remove(h),(h=new o(t,u,s,l)).setPosition(p);else{h.updateData(t,u,s,l);var m={x:p[0],y:p[1]};a?h.attr(m):nf(h,m,i)}n.add(h),t.setItemGraphicEl(u,h)}else n.remove(h)}).remove(function(t){var e=r.getItemGraphicEl(t);e&&e.fadeOut(function(){n.remove(e)},i)}).execute(),this._getSymbolPoint=c,this._data=t},t.prototype.updateLayout=function(){var t=this,e=this._data;e&&e.eachItemGraphicEl(function(e,n){var i=t._getSymbolPoint(n);e.setPosition(i),e.markRedraw()})},t.prototype.incrementalPrepareUpdate=function(t){this._seriesScope=CC(t),this._data=null,this.group.removeAll()},t.prototype.incrementalUpdate=function(t,e,n){function i(t){t.isGroup||(t.incremental=!0,t.ensureState("emphasis").hoverLayer=!0)}this._progressiveEls=[],n=SC(n);for(var r=t.start;r0?n=i[0]:i[1]<0&&(n=i[1]);return n}(r,n),a=i.dim,s=r.dim,l=e.mapDimension(s),c=e.mapDimension(a),u="x"===s||"radius"===s?1:0,d=Gi(t.dimensions,function(t){return e.mapDimension(t)}),h=!1,p=e.getCalculationInfo("stackResultDimension");return Bw(e,d[0])&&(h=!0,d[0]=p),Bw(e,d[1])&&(h=!0,d[1]=p),{dataDimsForPoint:d,valueStart:o,valueAxisDim:s,baseAxisDim:a,stacked:!!h,valueDim:l,baseDim:c,baseDataOffset:u,stackedOverDimension:e.getCalculationInfo("stackedOverDimension")}}function TC(t,e,n,i){var r=NaN;t.stacked&&(r=n.get(n.getCalculationInfo("stackedOverDimension"),i)),isNaN(r)&&(r=t.valueStart);var o=t.baseDataOffset,a=[];return a[o]=n.get(t.baseDim,i),a[1-o]=r,e.dataToPoint(a)}var AC=Math.min,IC=Math.max;function DC(t,e){return isNaN(t)||isNaN(e)}function PC(t,e,n,i,r,o,a,s,l){for(var c,u,d,h,p,f,g=n,m=0;m=r||g<0)break;if(DC(v,y)){if(l){g+=o;continue}break}if(g===n)t[o>0?"moveTo":"lineTo"](v,y),d=v,h=y;else{var _=v-c,b=y-u;if(_*_+b*b<.5){g+=o;continue}if(a>0){for(var x=g+o,w=e[2*x],S=e[2*x+1];w===v&&S===y&&m=i||DC(w,S))p=v,f=y;else{M=w-c,T=S-u;var D=v-c,P=w-v,L=y-u,E=S-y,N=void 0,R=void 0;if("x"===s){var O=M>0?1:-1;p=v-O*(N=Math.abs(D))*a,f=y,A=v+O*(R=Math.abs(P))*a,I=y}else if("y"===s){var z=T>0?1:-1;p=v,f=y-z*(N=Math.abs(L))*a,A=v,I=y+z*(R=Math.abs(E))*a}else N=Math.sqrt(D*D+L*L),p=v-M*a*(1-(k=(R=Math.sqrt(P*P+E*E))/(R+N))),f=y-T*a*(1-k),I=y+T*a*k,A=AC(A=v+M*a*k,IC(w,v)),I=AC(I,IC(S,y)),A=IC(A,AC(w,v)),f=y-(T=(I=IC(I,AC(S,y)))-y)*N/R,p=AC(p=v-(M=A-v)*N/R,IC(c,v)),f=AC(f,IC(u,y)),A=v+(M=v-(p=IC(p,AC(c,v))))*R/N,I=y+(T=y-(f=IC(f,AC(u,y))))*R/N}t.bezierCurveTo(d,h,p,f,v,y),d=A,h=I}else t.lineTo(v,y)}c=v,u=y,g+=o}return m}var LC=function(){this.smooth=0,this.smoothConstraint=!0},EC=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polyline",n}return S(e,t),e.prototype.getDefaultStyle=function(){return{stroke:Im.color.neutral99,fill:null}},e.prototype.getDefaultShape=function(){return new LC},e.prototype.buildPath=function(t,e){var n=e.points,i=0,r=n.length/2;if(e.connectNulls){for(;r>0&&DC(n[2*r-2],n[2*r-1]);r--);for(;i=0){var m=a?(u-i)*g+i:(c-n)*g+n;return a?[t,m]:[m,t]}n=c,i=u;break;case o.C:c=r[l++],u=r[l++],d=r[l++],h=r[l++],p=r[l++],f=r[l++];var v=a?ya(n,c,d,p,t,s):ya(i,u,h,f,t,s);if(v>0)for(var y=0;y=0){m=a?ma(i,u,h,f,_):ma(n,c,d,p,_);return a?[t,m]:[m,t]}}n=p,i=f}}},e}(vd),NC=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e}(LC),RC=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polygon",n}return S(e,t),e.prototype.getDefaultShape=function(){return new NC},e.prototype.buildPath=function(t,e){var n=e.points,i=e.stackedOnPoints,r=0,o=n.length/2,a=e.smoothMonotone;if(e.connectNulls){for(;o>0&&DC(n[2*o-2],n[2*o-1]);o--);for(;r=0&&t<=1){var i=t*(e.length-1),r=Math.floor(i),o=Math.ceil(i),a=qa(e[r]),s=qa(e[o]),l=i-r,c=Ya([Na(Ba(a[0],s[0],l)),Na(Ba(a[1],s[1],l)),Na(Ba(a[2],s[2],l)),Ra(Ba(a[3],s[3],l))],"rgba");return n?{color:c,leftIndex:r,rightIndex:o,value:i}:c}}((n-i)/(e.coord-i),[t.color,e.color])}}for(var s=0;se){i?r.push(a(i,l,e)):n&&r.push(a(n,l,0),a(n,l,e));break}n&&(r.push(a(n,l,0)),n=null),r.push(l),i=l}}return r}function VC(t,e,n){var i=t.get("showAllSymbol"),r="auto"===i;if(!i||r){var o=n.getAxesByScale("ordinal")[0];if(o&&(!r||!function(t,e){var n=t.getExtent(),i=Math.abs(n[1]-n[0])/t.scale.count();isNaN(i)&&(i=0);for(var r=e.count(),o=Math.max(1,Math.round(r/5)),a=0;ai)return!1;return!0}(o,e))){var a=e.mapDimension(o.dim),s={};return Ui(o.getViewLabels(),function(t){var e=o.scale.getRawOrdinalNumber(t.tickValue);s[e]=1}),function(t){return!s.hasOwnProperty(e.get(a,t))}}}}function WC(t,e){return isNaN(t)||isNaN(e)}function jC(t,e){return[t[2*e],t[2*e+1]]}function qC(t){if(t.get(["endLabel","show"]))return!0;for(var e=0;e=0;a--){var s=t.getDimensionInfo(i[a].dimension);if("x"===(r=s&&s.coordDim)||"y"===r){o=i[a];break}}if(o){var l=e.getAxis(r),c=Gi(o.stops,function(t){return{coord:l.toGlobalCoord(l.dataToCoord(t.value)),color:t.color}}),u=c.length,d=o.outerColors.slice();u&&c[0].coord>c[u-1].coord&&(c.reverse(),d.reverse());var h=FC(c,"x"===r?n.getWidth():n.getHeight()),p=h.length;if(!p&&u)return c[0].coord<0?d[1]?d[1]:c[u-1].color:d[0]?d[0]:c[0].color;var f=h[0].coord-10,g=h[p-1].coord+10,m=g-f;if(m<.001)return"transparent";Ui(h,function(t){t.offset=(t.coord-f)/m}),h.push({offset:p?h[p-1].offset:.5,color:d[1]||"transparent"}),h.unshift({offset:p?h[0].offset:.5,color:d[0]||"transparent"});var v=new Fp(0,0,0,0,h,!0);return v[r]=f,v[r+"2"]=g,v}}}(o,i,n)||o.getVisual("style")[o.getVisual("drawType")];if(h&&u.type===i.type&&k===this._step){m&&!p?p=this._newPolygon(l,_):p&&!m&&(f.remove(p),p=this._polygon=null),c||this._initOrUpdateEndLabel(t,i,am(M));var T=f.getClipPath();if(T)rf(T,{shape:UC(this,i,!1,t).shape},t);else f.setClipPath(UC(this,i,!0,t));b&&d.updateData(o,{isIgnore:w,clipShape:C,disableAnimation:!0,getSymbolPoint:function(t){return[l[2*t],l[2*t+1]]}}),OC(this._stackedOnPoints,_)&&OC(this._points,l)||(g?this._doUpdateAnimation(o,_,i,n,k,v,x):(k&&(_&&(_=$C(_,l,i,k,x)),l=$C(l,null,i,k,x)),h.setShape({points:l}),p&&p.setShape({points:l,stackedOnPoints:_})))}else b&&d.updateData(o,{isIgnore:w,clipShape:C,disableAnimation:!0,getSymbolPoint:function(t){return[l[2*t],l[2*t+1]]}}),g&&this._initSymbolLabelAnimation(o,i,C),k&&(_&&(_=$C(_,l,i,k,x)),l=$C(l,null,i,k,x)),h=this._newPolyline(l),m?p=this._newPolygon(l,_):p&&(f.remove(p),p=this._polygon=null),c||this._initOrUpdateEndLabel(t,i,am(M)),f.setClipPath(UC(this,i,!0,t));var A=t.getModel("emphasis"),I=A.get("focus"),D=A.get("blurScope"),P=A.get("disabled");(h.useStyle(Vi(a.getLineStyle(),{fill:"none",stroke:M,lineJoin:"bevel"})),Oh(h,t,"lineStyle"),h.style.lineWidth>0&&"bolder"===t.get(["emphasis","lineStyle","width"]))&&(h.getState("emphasis").style.lineWidth=+h.style.lineWidth+1);Ud(h).seriesIndex=t.seriesIndex,Eh(h,I,D,P);var L=BC(t.get("smooth")),E=t.get("smoothMonotone");if(h.setShape({smooth:L,smoothMonotone:E,connectNulls:x}),p){var N=o.getCalculationInfo("stackedOnSeries"),R=0;p.useStyle(Vi(s.getAreaStyle(),{fill:M,opacity:.7,lineJoin:"bevel",decal:o.getVisual("style").decal})),N&&(R=BC(N.get("smooth"))),p.setShape({smooth:L,stackedOnSmooth:R,smoothMonotone:E,connectNulls:x}),Oh(p,t,"areaStyle"),Ud(p).seriesIndex=t.seriesIndex,Eh(p,I,D,P)}var O=this._changePolyState;o.eachItemGraphicEl(function(t){t&&(t.onHoverStateChange=O)}),this._polyline.onHoverStateChange=O,this._data=o,this._coordSys=i,this._stackedOnPoints=_,this._points=l,this._step=k,this._valueOrigin=v,t.get("triggerLineEvent")&&(this.packEventData(t,h),p&&this.packEventData(t,p))},e.prototype.packEventData=function(t,e){Ud(e).eventData={componentType:"series",componentSubType:"line",componentIndex:t.componentIndex,seriesIndex:t.seriesIndex,seriesName:t.name,seriesType:"line"}},e.prototype.highlight=function(t,e,n,i){var r=t.getData(),o=wc(r,i);if(this._changePolyState("emphasis"),!(o instanceof Array)&&null!=o&&o>=0){var a=r.getLayout("points"),s=r.getItemGraphicEl(o);if(!s){var l=a[2*o],c=a[2*o+1];if(isNaN(l)||isNaN(c))return;if(this._clipShapeForSymbol&&!this._clipShapeForSymbol.contain(l,c))return;var u=t.get("zlevel")||0,d=t.get("z")||0;(s=new bC(r,o)).x=l,s.y=c,s.setZ(u,d);var h=s.getSymbolPath().getTextContent();h&&(h.zlevel=u,h.z=d,h.z2=this._polyline.z2+1),s.__temp=!0,r.setItemGraphicEl(o,s),s.stopSymbolAnimation(!0),this.group.add(s)}s.highlight()}else m_.prototype.highlight.call(this,t,e,n,i)},e.prototype.downplay=function(t,e,n,i){var r=t.getData(),o=wc(r,i);if(this._changePolyState("normal"),null!=o&&o>=0){var a=r.getItemGraphicEl(o);a&&(a.__temp?(r.setItemGraphicEl(o,null),this.group.remove(a)):a.downplay())}else m_.prototype.downplay.call(this,t,e,n,i)},e.prototype._changePolyState=function(t){var e=this._polygon;gh(this._polyline,t),e&&gh(e,t)},e.prototype._newPolyline=function(t){var e=this._polyline;return e&&this._lineGroup.remove(e),e=new EC({shape:{points:t},segmentIgnoreThreshold:2,z2:10}),this._lineGroup.add(e),this._polyline=e,e},e.prototype._newPolygon=function(t,e){var n=this._polygon;return n&&this._lineGroup.remove(n),n=new RC({shape:{points:t,stackedOnPoints:e},segmentIgnoreThreshold:2}),this._lineGroup.add(n),this._polygon=n,n},e.prototype._initSymbolLabelAnimation=function(t,e,n){var i,r,o=e.getBaseAxis(),a=o.inverse;"cartesian2d"===e.type?(i=o.isHorizontal(),r=!1):"polar"===e.type&&(i="angle"===o.dim,r=!0);var s=t.hostModel,l=s.get("animationDuration");tr(l)&&(l=l(null));var c=s.get("animationDelay")||0,u=tr(c)?c(null):c;t.eachItemGraphicEl(function(t,o){var s=t;if(s){var d=[t.x,t.y],h=void 0,p=void 0,f=void 0;if(n)if(r){var g=n,m=e.pointToCoord(d);i?(h=g.startAngle,p=g.endAngle,f=-m[1]/180*Math.PI):(h=g.r0,p=g.r,f=m[0])}else{var v=n;i?(h=v.x,p=v.x+v.width,f=t.x):(h=v.y+v.height,p=v.y,f=t.y)}var y=p===h?0:(f-h)/(p-h);a&&(y=1-y);var _=tr(c)?c(o):l*y+u,b=s.getSymbolPath(),x=b.getTextContent();s.attr({scaleX:0,scaleY:0}),s.animateTo({scaleX:1,scaleY:1},{duration:200,setToFinal:!0,delay:_}),x&&x.animateFrom({style:{opacity:0}},{duration:300,delay:_}),b.disableLabelAnimation=!0}})},e.prototype._initOrUpdateEndLabel=function(t,e,n){var i=t.getModel("endLabel");if(qC(t)){var r=t.getData(),o=this._polyline,a=r.getLayout("points");if(!a)return o.removeTextContent(),void(this._endLabel=null);var s=this._endLabel;s||((s=this._endLabel=new Ed({z2:200})).ignoreClip=!0,o.setTextContent(this._endLabel),o.disableLabelAnimation=!0);var l=function(t){for(var e=t.length/2;e>0&&WC(t[2*e-2],t[2*e-1]);e--);return e-1}(a);l>=0&&(Vf(o,Wf(t,"endLabel"),{inheritColor:n,labelFetcher:t,labelDataIndex:l,defaultText:function(t,e,n){return null!=n?function(t,e){var n=t.mapDimensionsAll("defaultedLabel");if(!Ji(e))return e+"";for(var i=[],r=0;r=0&&i.push(e[o])}return i.join(" ")}(r,n):_C(r,t)},enableTextSetter:!0},function(t,e){var n=e.getBaseAxis(),i=n.isHorizontal(),r=n.inverse,o=i?r?"right":"left":"center",a=i?"middle":r?"top":"bottom";return{normal:{align:t.get("align")||o,verticalAlign:t.get("verticalAlign")||a}}}(i,e)),o.textConfig.position=null)}else this._endLabel&&(this._polyline.removeTextContent(),this._endLabel=null)},e.prototype._endLabelOnDuring=function(t,e,n,i,r,o,a){var s=this._endLabel,l=this._polyline;if(s){t<1&&null==i.originalX&&(i.originalX=s.x,i.originalY=s.y);var c=n.getLayout("points"),u=n.hostModel,d=u.get("connectNulls"),h=o.get("precision"),p=o.get("distance")||0,f=a.getBaseAxis(),g=f.isHorizontal(),m=f.inverse,v=e.shape,y=m?g?v.x:v.y+v.height:g?v.x+v.width:v.y,_=(g?p:0)*(m?-1:1),b=(g?0:-p)*(m?-1:1),x=g?"x":"y",w=function(t,e,n){for(var i,r,o=t.length/2,a="x"===n?0:1,s=0,l=-1,c=0;c=e||i>=e&&r<=e){l=c;break}s=c,i=r}else i=r;return{range:[s,l],t:(e-i)/(r-i)}}(c,y,x),S=w.range,C=S[1]-S[0],k=void 0;if(C>=1){if(C>1&&!d){var M=jC(c,S[0]);s.attr({x:M[0]+_,y:M[1]+b}),r&&(k=u.getRawValue(S[0]))}else{(M=l.getPointOn(y,x))&&s.attr({x:M[0]+_,y:M[1]+b});var T=u.getRawValue(S[0]),A=u.getRawValue(S[1]);r&&(k=function(t,e,n,i,r){var o=null==e||"auto"===e;if(null==i)return i;if(ir(i))return Gl(f=cc(n||0,i,r),o?Math.max(Xl(n||0),Xl(i)):e);if(er(i))return r<1?n:i;for(var a=[],s=n,l=i,c=Math.max(s?s.length:0,l.length),u=0;u0?S[0]:0;M=jC(c,I);r&&(k=u.getRawValue(I)),s.attr({x:M[0]+_,y:M[1]+b})}if(r){var D=Qf(s);"function"==typeof D.setLabelText&&D.setLabelText(k)}}},e.prototype._doUpdateAnimation=function(t,e,n,i,r,o,a){var s=this._polyline,l=this._polygon,c=t.hostModel,u=function(t,e,n,i,r,o,a){for(var s=function(t,e){var n=[];return e.diff(t).add(function(t){n.push({cmd:"+",idx:t})}).update(function(t,e){n.push({cmd:"=",idx:e,idx1:t})}).remove(function(t){n.push({cmd:"-",idx:t})}).execute(),n}(t,e),l=[],c=[],u=[],d=[],h=[],p=[],f=[],g=MC(r,e,a),m=t.getLayout("points")||[],v=e.getLayout("points")||[],y=0;y3e3||l&&HC(h,f)>3e3)return s.stopAnimation(),s.setShape({points:p}),void(l&&(l.stopAnimation(),l.setShape({points:p,stackedOnPoints:f})));s.shape.__points=u.current,s.shape.points=d;var g={shape:{points:p}};u.current!==d&&(g.shape.__points=u.next),s.stopAnimation(),nf(s,g,c),l&&(l.setShape({points:d,stackedOnPoints:h}),l.stopAnimation(),nf(l,{shape:{stackedOnPoints:f}},c),s.shape.points!==l.shape.points&&(l.shape.points=s.shape.points));for(var m=[],v=u.status,y=0;ye&&(e=t[n]);return isFinite(e)?e:NaN},min:function(t){for(var e=1/0,n=0;ne[1]&&e.reverse(),e},e.prototype.pointToData=function(t,e){return this.coordToData(this.toLocalCoord(t["x"===this.dim?0:1]),e)},e.prototype.setCategorySortInfo=function(t){if("category"!==this.type)return!1;this.model.option.categorySortInfo=t,this.scale.setSortInfo(t)},e}(lC),hk="expandAxisBreak",pk=Math.PI,fk=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],gk=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],mk=Sc(),vk=Sc(),yk=function(){function t(t){this.recordMap={},this.resolveAxisNameOverlap=t}return t.prototype.ensureRecord=function(t){var e=t.axis.dim,n=t.componentIndex,i=this.recordMap,r=i[e]||(i[e]=[]);return r[n]||(r[n]={ready:{}})},t}();var _k=[1,0,0,1,0,0],bk=new Lo(0,0,0,0),xk=function(t,e,n,i,r,o){if(OS(t.nameLocation)){var a=o.stOccupiedRect;a&&wk(function(t,e,n){return t.transform=Rf(t.transform,n),t.localRect=Nf(t.localRect,e),t.rect=Nf(t.rect,e),n&&t.rect.applyTransform(n),t.axisAligned=Lf(n),t.obb=void 0,(t.label=t.label||{}).ignore=!1,t}({},a,o.transGroup.transform),i,r)}else Sk(o.labelInfoList,o.dirVec,i,r)};function wk(t,e,n){var i=new yo;vC(t,e,i,{direction:Math.atan2(n.y,n.x),bidirectional:!1,touchThreshold:.05})&&function(t,e){if(t){t.label.x+=e.x,t.label.y+=e.y,t.label.markRedraw();var n=t.transform;n&&(n[4]+=e.x,n[5]+=e.y);var i=t.rect;i&&(i.x+=e.x,i.y+=e.y);var r=t.obb;r&&r.fromBoundingRect(t.localRect,n)}}(e,i)}function Sk(t,e,n,i){for(var r=yo.dot(i,e)>=0,o=0,a=t.length;o0?"top":"bottom",i="center"):Kl(o-pk)?(r=n>0?"bottom":"top",i="center"):(r="middle",i=o>0&&o0?"right":"left":n>0?"left":"right"),{rotation:o,textAlign:i,textVerticalAlign:r}},t.makeAxisEventDataBase=function(t){var e={componentType:t.mainType,componentIndex:t.componentIndex};return e[t.mainType+"Index"]=t.componentIndex,e},t.isLabelSilent=function(t){var e=t.get("tooltip");return t.get("silent")||!(t.get("triggerEvent")||e&&e.show)},t}(),kk=["axisLine","axisTickLabelEstimate","axisTickLabelDetermine","axisName"],Mk={axisLine:function(t,e,n,i,r,o,a){var s=i.get(["axisLine","show"]);if("auto"===s&&(s=!0,null!=t.raw.axisLineAutoShow&&(s=!!t.raw.axisLineAutoShow)),s){var l=i.axis.getExtent(),c=o.transform,u=[l[0],0],d=[l[1],0],h=u[0]>d[0];c&&(zr(u,u,c),zr(d,d,c));var p=Fi({lineCap:"round"},i.getModel(["axisLine","lineStyle"]).getLineStyle()),f={strokeContainThreshold:t.raw.strokeContainThreshold||5,silent:!0,z2:1,style:p};if(i.get(["axisLine","breakLine"])&&i.axis.scale.hasBreaks())null.buildAxisBreakLine(i,r,o,f);else{var g=new Lp(Fi({shape:{x1:u[0],y1:u[1],x2:d[0],y2:d[1]}},f));yf(g.shape,g.style.lineWidth),g.anid="line",r.add(g)}var m=i.get(["axisLine","symbol"]);if(null!=m){var v=i.get(["axisLine","symbolSize"]);er(m)&&(m=[m,m]),(er(v)||ir(v))&&(v=[v,v]);var y=Cb(i.get(["axisLine","symbolOffset"])||0,v),_=v[0],b=v[1];Ui([{rotate:t.rotation+Math.PI/2,offset:y[0],r:0},{rotate:t.rotation-Math.PI/2,offset:y[1],r:Math.sqrt((u[0]-d[0])*(u[0]-d[0])+(u[1]-d[1])*(u[1]-d[1]))}],function(e,n){if("none"!==m[n]&&null!=m[n]){var i=Sb(m[n],-_/2,-b/2,_,b,p.stroke,!0),o=e.r+e.offset,a=h?d:u;i.attr({rotation:e.rotate,x:a[0]+o*Math.cos(t.rotation),y:a[1]-o*Math.sin(t.rotation),silent:!0,z2:11}),r.add(i)}})}}},axisTickLabelEstimate:function(t,e,n,i,r,o,a,s){Dk(e,r,s)&&Tk(t,e,n,i,r,o,a,qS)},axisTickLabelDetermine:function(t,e,n,i,r,o,a,s){Dk(e,r,s)&&Tk(t,e,n,i,r,o,a,US);var l=function(t,e,n,i){var r=i.axis,o=i.getModel("axisTick"),a=o.get("show");"auto"===a&&(a=!0,null!=t.raw.axisTickAutoShow&&(a=!!t.raw.axisTickAutoShow));if(!a||r.scale.isBlank())return[];for(var s=o.getModel("lineStyle"),l=t.tickDirection*o.get("length"),c=Ik(r.getTicksCoords(),n.transform,l,Vi(s.getLineStyle(),{stroke:i.get(["axisLine","lineStyle","color"])}),"ticks"),u=0;ui[1],l="start"===e&&!s||"start"!==e&&s;Kl(a-pk/2)?(o=l?"bottom":"top",r="center"):Kl(a-1.5*pk)?(o=l?"top":"bottom",r="center"):(o="middle",r=a<1.5*pk&&a>pk/2?l?"left":"right":l?"right":"left");return{rotation:a,textAlign:r,textVerticalAlign:o}}(t.rotation,u,x||0,f),null!=(b=t.raw.axisNameAvailableWidth)&&(b=Math.abs(b/Math.sin(_.rotation)),!isFinite(b)&&(b=null)));var w=h.getFont(),S=i.get("nameTruncate",!0)||{},C=S.ellipsis,k=ur(t.raw.nameTruncateMaxWidth,S.maxWidth,b),M=s.nameMarginLevel||0,T=new Ed({x:m.x,y:m.y,rotation:_.rotation,silent:Ck.isLabelSilent(i),style:jf(h,{text:c,font:w,overflow:"truncate",width:k,ellipsis:C,fill:h.getTextColor()||i.get(["axisLine","lineStyle","color"]),align:h.get("align")||_.textAlign,verticalAlign:h.get("verticalAlign")||_.textVerticalAlign}),z2:1});if(If({el:T,componentModel:i,itemName:c}),T.__fullText=c,T.anid="name",i.get("triggerEvent")){var A=Ck.makeAxisEventDataBase(i);A.targetType="axisName",A.name=c,Ud(T).eventData=A}o.add(T),T.updateTransform(),e.nameEl=T;var I=l.nameLayout=pC({label:T,priority:T.z2,defaultAttr:{ignore:T.ignore},marginDefault:OS(u)?fk[M]:gk[M]});if(l.nameLocation=u,r.add(T),T.decomposeTransform(),t.shouldNameMoveOverlap&&I){var D=n.ensureRecord(i);n.resolveAxisNameOverlap(t,n,i,I,v,D)}}}};function Tk(t,e,n,i,r,o,a,s){Pk(e)||function(t,e,n,i,r,o){var a=r.axis,s=ur(t.raw.axisLabelShow,r.get(["axisLabel","show"])),l=new Nl;n.add(l);var c=GS(i);if(!s||a.scale.isBlank())return void Lk(e,[],l,c);var u=r.getModel("axisLabel"),d=a.getViewLabels(c),h=(ur(t.raw.labelRotate,u.get("rotate"))||0)*pk/180,p=Ck.innerTextLayout(t.rotation,h,t.labelDirection),f=r.getCategories&&r.getCategories(!0),g=[],m=r.get("triggerEvent"),v=1/0,y=-1/0;Ui(d,function(t,e){var n,i="ordinal"===a.scale.type?a.scale.getRawOrdinalNumber(t.tickValue):t.tickValue,s=t.formattedLabel,c=t.rawLabel,h=u;if(f&&f[i]){var _=f[i];rr(_)&&_.textStyle&&(h=new ug(_.textStyle,u,r.ecModel))}var b=h.getTextColor()||r.get(["axisLine","lineStyle","color"]),x=h.getShallow("align",!0)||p.textAlign,w=dr(h.getShallow("alignMinLabel",!0),x),S=dr(h.getShallow("alignMaxLabel",!0),x),C=h.getShallow("verticalAlign",!0)||h.getShallow("baseline",!0)||p.textVerticalAlign,k=dr(h.getShallow("verticalAlignMinLabel",!0),C),M=dr(h.getShallow("verticalAlignMaxLabel",!0),C),T=10+((null===(n=t.time)||void 0===n?void 0:n.level)||0);v=Math.min(v,T),y=Math.max(y,T);var A=new Ed({x:0,y:0,rotation:0,silent:Ck.isLabelSilent(r),z2:T,style:jf(h,{text:s,align:0===e?w:e===d.length-1?S:x,verticalAlign:0===e?k:e===d.length-1?M:C,fill:tr(b)?b("category"===a.type?c:"value"===a.type?i+"":i,e):b})});A.anid="label_"+i;var I=mk(A);if(I.break=t.break,I.tickValue=i,I.layoutRotation=p.rotation,If({el:A,componentModel:r,itemName:s,formatterParamsExtra:{isTruncated:function(){return A.isTruncated},value:c,tickIndex:e}}),m){var D=Ck.makeAxisEventDataBase(r);D.targetType="axisLabel",D.value=c,D.tickIndex=e,t.break&&(D.break={start:t.break.parsedBreak.vmin,end:t.break.parsedBreak.vmax}),"category"===a.type&&(D.dataIndex=i),Ud(A).eventData=D,t.break&&function(t,e,n,i){n.on("click",function(n){var r={type:hk,breaks:[{start:i.parsedBreak.breakOption.start,end:i.parsedBreak.breakOption.end}]};r[t.axis.dim+"AxisIndex"]=t.componentIndex,e.dispatchAction(r)})}(r,o,A,t.break)}g.push(A),l.add(A)});var _=Gi(g,function(t){return{label:t,priority:mk(t).break?t.z2+(y-v+1):t.z2,defaultAttr:{ignore:t.ignore}}});Lk(e,_,l,c)}(t,e,r,s,i,a);var l=e.labelLayoutList;!function(t,e,n,i){var r=e.get(["axisLabel","margin"]);Ui(n,function(n,o){var a=pC(n);if(a){var s=a.label,l=mk(s);a.suggestIgnore=s.ignore,s.ignore=!1,ul(Ek,Nk),Ek.x=e.axis.dataToCoord(l.tickValue),Ek.y=t.labelOffset+t.labelDirection*r,Ek.rotation=l.layoutRotation,i.add(Ek),Ek.updateTransform(),i.remove(Ek),Ek.decomposeTransform(),ul(s,Ek),s.markRedraw(),dC(a,!0),pC(a)}})}(t,i,l,o),t.rotation;var c=t.optionHideOverlap;!function(t,e,n){if(NS(t.axis))return;function i(t,i,r){var o=pC(e[i]),a=pC(e[r]);if(o&&a)if(!1===t||o.suggestIgnore)Ak(o.label);else if(a.suggestIgnore)Ak(a.label);else{var s=.1;if(!n){var l=[0,0,0,0];o=gC({marginForce:l},o),a=gC({marginForce:l},a)}vC(o,a,null,{touchThreshold:s})&&Ak(t?a.label:o.label)}}var r=t.get(["axisLabel","showMinLabel"]),o=t.get(["axisLabel","showMaxLabel"]),a=e.length;i(r,0,1),i(o,a-1,a-2)}(i,l,c),c&&function(t){var e=[];function n(t){if(!t.ignore){var e=t.ensureState("emphasis");null==e.ignore&&(e.ignore=!1)}t.ignore=!0}t.sort(function(t,e){return(e.suggestIgnore?1:0)-(t.suggestIgnore?1:0)||e.priority-t.priority});for(var i=0;i.1?"x":"y",u=a.transGroup[c];if(s.sort(function(t,e){return Math.abs(t.label[c]-u)-Math.abs(e.label[c]-u)}),l&&r){var d=o.getExtent(),h=Math.min(d[0],d[1]),p=Math.max(d[0],d[1])-h;r.union(new Lo(h,0,p,1))}a.stOccupiedRect=r,a.labelInfoList=s}(t,n,i,l)}function Ak(t){t&&(t.ignore=!0)}function Ik(t,e,n,i,r){for(var o=[],a=[],s=[],l=0;l=0;o--){var a=t[+n[o]],s=a.model,l=a.scale;Fw(l)&&s.get("alignTicks")&&null==s.get("interval")?r.push(a):(DS(l,s),Fw(l)&&(e=a))}r.length&&(e||DS((e=r.pop()).scale,e.model),Ui(r,function(t){!function(t,e,n){var i=iS.prototype,r=i.getTicks.call(n),o=i.getTicks.call(n,{expandToNicedExtent:!0}),a=r.length-1,s=i.getInterval.call(n),l=IS(t,e),c=l.extent,u=l.fixMin,d=l.fixMax;"log"===t.type&&(c=Zw(t.base,c,!0)),t.setBreaksFromOption(HS(e)),t.setExtent(c[0],c[1]),t.calcNiceExtent({splitNumber:a,fixMin:u,fixMax:d});var h=i.getExtent.call(t);u&&(c[0]=h[0]),d&&(c[1]=h[1]);var p=i.getInterval.call(t),f=c[0],g=c[1];if(u&&d)p=(g-f)/a;else if(u)for(g=c[0]+p*a;gc[0]&&isFinite(f)&&isFinite(c[0]);)p=Ww(p),f=c[1]-p*a;else{t.getTicks().length-1>a&&(p=Ww(p));var m=p*a;(f=Gl((g=Math.ceil(c[1]/p)*p)-m))<0&&c[0]>=0?(f=0,g=Gl(m)):g>0&&c[1]<=0&&(g=0,f=-Gl(m))}var v=(r[0].value-o[0].value)/s,y=(r[a].value-o[a].value)/s;i.setExtent.call(t,f+p*v,g+p*y),i.setInterval.call(t,p),(v||y)&&i.setNiceExtent.call(t,f+p,g-p)}(t.scale,t.model,e.scale)}))}}this._updateScale(t,this.model),i(n.x),i(n.y);var r={};Ui(n.x,function(t){Fk(n,"y",t,r)}),Ui(n.y,function(t){Fk(n,"x",t,r)}),this.resize(this.model,e)},t.prototype.resize=function(t,e,n){var i=Sm(t,e),r=this._rect=xm(t.getBoxLayoutParams(),i.refContainer),o=this._axesMap,a=this._coordsList,s=t.get("containLabel");if(Wk(o,r),!n){var l=function(t,e,n,i,r){var o=new yk(Gk);return Ui(n,function(n){return Ui(n,function(n){if(zS(n.model)){var a=!i;n.axisBuilder=function(t,e,n,i,r,o){for(var a=Ok(t,n),s=!1,l=!1,c=0;c0&&i>0||n<0&&i<0)}(t)}function Wk(t,e){Ui(t.x,function(t){return jk(t,e.x,e.width)}),Ui(t.y,function(t){return jk(t,e.y,e.height)})}function jk(t,e,n){var i=[0,n],r=t.inverse?1:0;t.setExtent(i[r],i[1-r]),function(t,e){var n=t.getExtent(),i=n[0]+n[1];t.toGlobalCoord="x"===t.dim?function(t){return t+e}:function(t){return i-t+e},t.toLocalCoord="x"===t.dim?function(t){return t-e}:function(t){return i-t+e}}(t,e)}function qk(t,e,n,i,r,o,a){Uk(i,r,qS,e,!1,a);var s=[0,0,0,0];c(0),c(1),u(i,0,NaN),u(i,1,NaN);var l=null==function(t,e,n){if(t&&e)for(var i=0,r=t.length;i0});return Mf(i,s,!0,!0,n),Wk(r,i),l;function c(t){Ui(r[cf[t]],function(e){if(zS(e.model)){var n=o.ensureRecord(e.model),i=n.labelInfoList;if(i)for(var r=0;r0&&!cr(e)&&e>1e-4&&(t/=e),t}}function Uk(t,e,n,i,r,o){var a=n===US;Ui(e,function(e){return Ui(e,function(e){zS(e.model)&&(!function(t,e,n){var i=Ok(e,n);t.updateCfg(i)}(e.axisBuilder,t,e.model),e.axisBuilder.build(a?{axisTickLabelDetermine:!0}:{axisTickLabelEstimate:!0},{noPxChange:r}))})});var s={x:0,y:0};function l(e){s[cf[1-e]]=t[uf[e]]<=.5*o.refContainer[uf[e]]?0:1-e==1?2:1}l(0),l(1),Ui(e,function(t,e){return Ui(t,function(t){zS(t.model)&&(("all"===i||a)&&t.axisBuilder.build({axisName:!0},{nameMarginLevel:s[e]}),a&&t.axisBuilder.build({axisLine:!0}))})})}var Gk=function(t,e,n,i,r,o){var a="x"===n.axis.dim?"y":"x";xk(t,0,0,i,r,o),OS(t.nameLocation)||Ui(e.recordMap[a],function(t){t&&t.labelInfoList&&t.dirVec&&Sk(t.labelInfoList,t.dirVec,i,r)})};function Xk(t,e){var n={axesInfo:{},seriesInvolved:!1,coordSysAxesInfo:{},coordSysMap:{}};return function(t,e,n){var i=e.getComponent("tooltip"),r=e.getComponent("axisPointer"),o=r.get("link",!0)||[],a=[];Ui(n.getCoordinateSystems(),function(n){if(n.axisPointerEnabled){var s=Qk(n.model),l=t.coordSysAxesInfo[s]={};t.coordSysMap[s]=n;var c=n.model.getModel("tooltip",i);if(Ui(n.getAxes(),Qi(p,!1,null)),n.getTooltipAxes&&i&&c.get("show")){var u="axis"===c.get("trigger"),d="cross"===c.get(["axisPointer","type"]),h=n.getTooltipAxes(c.get(["axisPointer","axis"]));(u||d)&&Ui(h.baseAxes,Qi(p,!d||"cross",u)),d&&Ui(h.otherAxes,Qi(p,"cross",!1))}}function p(i,s,u){var d=u.model.getModel("axisPointer",r),h=d.get("show");if(h&&("auto"!==h||i||Kk(d))){null==s&&(s=d.get("triggerTooltip")),d=i?function(t,e,n,i,r,o){var a=e.getModel("axisPointer"),s={};Ui(["type","snap","lineStyle","shadowStyle","label","animation","animationDurationUpdate","animationEasingUpdate","z"],function(t){s[t]=Bi(a.get(t))}),s.snap="category"!==t.type&&!!o,"cross"===a.get("type")&&(s.type="line");var l=s.label||(s.label={});if(null==l.show&&(l.show=!1),"cross"===r){var c=a.get(["label","show"]);if(l.show=null==c||c,!o){var u=s.lineStyle=a.get("crossStyle");u&&Vi(l,u.textStyle)}}return t.model.getModel("axisPointer",new ug(s,n,i))}(u,c,r,e,i,s):d;var p=d.get("snap"),f=d.get("triggerEmphasis"),g=Qk(u.model),m=s||p||"category"===u.type,v=t.axesInfo[g]={key:g,axis:u,coordSys:n,axisPointerModel:d,triggerTooltip:s,triggerEmphasis:f,involveSeries:m,snap:p,useHandle:Kk(d),seriesModels:[],linkGroup:null};l[g]=v,t.seriesInvolved=t.seriesInvolved||m;var y=function(t,e){for(var n=e.model,i=e.dim,r=0;r=0||t===e}function Zk(t){var e=(t.ecModel.getComponent("axisPointer")||{}).coordSysAxesInfo;return e&&e.axesInfo[Qk(t)]}function Kk(t){return!!t.get(["handle","show"])}function Qk(t){return t.type+"||"+t.id}var Jk={},tM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.prototype.render=function(e,n,i,r){this.axisPointerClass&&function(t){var e=Zk(t);if(e){var n=e.axisPointerModel,i=e.axis.scale,r=n.option,o=n.get("status"),a=n.get("value");null!=a&&(a=i.parse(a));var s=Kk(n);null==o&&(r.status=s?"show":"hide");var l=i.getExtent().slice();l[0]>l[1]&&l.reverse(),(null==a||a>l[1])&&(a=l[1]),aa)return!0;if(o){var s=Zk(t).seriesDataCount,l=i.getExtent();return Math.abs(l[0]-l[1])/s>a}return!1}return!0===n},t.prototype.makeElOption=function(t,e,n,i,r){},t.prototype.createPointerEl=function(t,e,n,i){var r=e.pointer;if(r){var o=uM(t).pointerEl=new Bf[r.type](dM(e.pointer));t.add(o)}},t.prototype.createLabelEl=function(t,e,n,i){if(e.label){var r=uM(t).labelEl=new Ed(dM(e.label));t.add(r),mM(r,i)}},t.prototype.updatePointerEl=function(t,e,n){var i=uM(t).pointerEl;i&&e.pointer&&(i.setStyle(e.pointer.style),n(i,{shape:e.pointer.shape}))},t.prototype.updateLabelEl=function(t,e,n,i){var r=uM(t).labelEl;r&&(r.setStyle(e.label.style),n(r,{x:e.label.x,y:e.label.y}),mM(r,i))},t.prototype._renderHandle=function(t){if(!this._dragging&&this.updateHandleTransform){var e,n=this._axisPointerModel,i=this._api.getZr(),r=this._handle,o=n.getModel("handle"),a=n.get("status");if(!o.get("show")||!a||"hide"===a)return r&&i.remove(r),void(this._handle=null);this._handle||(e=!0,r=this._handle=Sf(o.get("icon"),{cursor:"move",draggable:!0,onmousemove:function(t){so(t.event)},onmousedown:hM(this._onHandleDragMove,this,0,0),drift:hM(this._onHandleDragMove,this),ondragend:hM(this._onHandleDragEnd,this)}),i.add(r)),yM(r,n,!1),r.setStyle(o.getItemStyle(null,["color","borderColor","borderWidth","opacity","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]));var s=o.get("size");Ji(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,M_(this,"_doDispatchAxisPointer",o.get("throttle")||0,"fixRate"),this._moveHandleToValue(t,e)}},t.prototype._moveHandleToValue=function(t,e){fM(this._axisPointerModel,!e&&this._moveAnimation,this._handle,vM(this.getHandleTransform(t,this._axisModel,this._axisPointerModel)))},t.prototype._onHandleDragMove=function(t,e){var n=this._handle;if(n){this._dragging=!0;var i=this.updateHandleTransform(vM(n),[t,e],this._axisModel,this._axisPointerModel);this._payloadInfo=i,n.stopAnimation(),n.attr(vM(i)),uM(n).lastProp=null,this._doDispatchAxisPointer()}},t.prototype._doDispatchAxisPointer=function(){if(this._handle){var t=this._payloadInfo,e=this._axisModel;this._api.dispatchAction({type:"updateAxisPointer",x:t.cursorPoint[0],y:t.cursorPoint[1],tooltipOption:t.tooltipOption,axesInfo:[{axisDim:e.axis.dim,axisIndex:e.componentIndex}]})}},t.prototype._onHandleDragEnd=function(){if(this._dragging=!1,this._handle){var t=this._axisPointerModel.get("value");this._moveHandleToValue(t),this._api.dispatchAction({type:"hideTip"})}},t.prototype.clear=function(t){this._lastValue=null,this._lastStatus=null;var e=t.getZr(),n=this._group,i=this._handle;e&&n&&(this._lastGraphicKey=null,n&&e.remove(n),i&&e.remove(i),this._group=null,this._handle=null,this._payloadInfo=null),T_(this,"_doDispatchAxisPointer")},t.prototype.doClear=function(){},t.prototype.buildLabel=function(t,e,n){return{x:t[n=n||0],y:t[1-n],width:e[n],height:e[1-n]}},t}();function fM(t,e,n,i){gM(uM(n).lastProp,i)||(uM(n).lastProp=i,e?nf(n,i,t):(n.stopAnimation(),n.attr(i)))}function gM(t,e){if(rr(t)&&rr(e)){var n=!0;return Ui(e,function(e,i){n=n&&gM(t[i],e)}),!!n}return t===e}function mM(t,e){t[e.get(["label","show"])?"show":"hide"]()}function vM(t){return{x:t.x||0,y:t.y||0,rotation:t.rotation||0}}function yM(t,e,n){var i=e.get("z"),r=e.get("zlevel");t&&t.traverse(function(t){"group"!==t.type&&(null!=i&&(t.z=i),null!=r&&(t.zlevel=r),t.silent=n)})}function _M(t,e,n,i,r){var o=bM(n.get("value"),e.axis,e.ecModel,n.get("seriesDataIndices"),{precision:n.get(["label","precision"]),formatter:n.get(["label","formatter"])}),a=n.getModel("label"),s=em(a.get("padding")||0),l=a.getFont(),c=vl(o,l),u=r.position,d=c.width+s[1]+s[3],h=c.height+s[0]+s[2],p=r.align;"right"===p&&(u[0]-=d),"center"===p&&(u[0]-=d/2);var f=r.verticalAlign;"bottom"===f&&(u[1]-=h),"middle"===f&&(u[1]-=h/2),function(t,e,n,i){var r=i.getWidth(),o=i.getHeight();t[0]=Math.min(t[0]+e,r)-e,t[1]=Math.min(t[1]+n,o)-n,t[0]=Math.max(t[0],0),t[1]=Math.max(t[1],0)}(u,d,h,i);var g=a.get("backgroundColor");g&&"auto"!==g||(g=e.get(["axisLine","lineStyle","color"])),t.label={x:u[0],y:u[1],style:jf(a,{text:o,font:l,fill:a.getTextColor(),padding:s,backgroundColor:g}),z2:10}}function bM(t,e,n,i,r){t=e.scale.parse(t);var o=e.scale.getLabel({value:t},{precision:r.precision}),a=r.formatter;if(a){var s={value:LS(e,{value:t}),axisDimension:e.dim,axisIndex:e.index,seriesData:[]};Ui(i,function(t){var e=n.getSeriesByIndex(t.seriesIndex),i=t.dataIndexInside,r=e&&e.getDataParams(i);r&&s.seriesData.push(r)}),er(a)?o=a.replace("{value}",o):tr(a)&&(o=a(s))}return o}function xM(t,e,n){var i=[1,0,0,1,0,0];return mo(i,i,n.rotation),go(i,i,n.position),bf([t.dataToCoord(e),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],i)}var wM=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e.prototype.makeElOption=function(t,e,n,i,r){var o=n.axis,a=o.grid,s=i.get("type"),l=SM(a,o).getOtherAxis(o).getGlobalExtent(),c=o.toGlobalCoord(o.dataToCoord(e,!0));if(s&&"none"!==s){var u=function(t){var e,n=t.get("type"),i=t.getModel(n+"Style");return"line"===n?(e=i.getLineStyle()).fill=null:"shadow"===n&&((e=i.getAreaStyle()).stroke=null),e}(i),d=CM[s](o,c,l);d.style=u,t.graphicKey=d.type,t.pointer=d}!function(t,e,n,i,r,o){var a=Ck.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=r.get(["label","margin"]),_M(e,i,r,o,{position:xM(i.axis,t,n),align:a.textAlign,verticalAlign:a.textVerticalAlign})}(e,t,Ok(a.getRect(),n),n,i,r)},e.prototype.getHandleTransform=function(t,e,n){var i=Ok(e.axis.grid.getRect(),e,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var r=xM(e.axis,t,i);return{x:r[0],y:r[1],rotation:i.rotation+(i.labelDirection<0?Math.PI:0)}},e.prototype.updateHandleTransform=function(t,e,n,i){var r=n.axis,o=r.grid,a=r.getGlobalExtent(!0),s=SM(o,r).getOtherAxis(r).getGlobalExtent(),l="x"===r.dim?0:1,c=[t.x,t.y];c[l]+=e[l],c[l]=Math.min(a[1],c[l]),c[l]=Math.max(a[0],c[l]);var u=(s[1]+s[0])/2,d=[u,u];d[l]=c[l];return{x:c[0],y:c[1],rotation:t.rotation,cursorPoint:d,tooltipOption:[{verticalAlign:"middle"},{align:"center"}][l]}},e}(pM);function SM(t,e){var n={};return n[e.dim+"AxisIndex"]=e.index,t.getCartesian(n)}var CM={line:function(t,e,n){var i,r,o;return{type:"Line",subPixelOptimize:!0,shape:(i=[e,n[0]],r=[e,n[1]],o=kM(t),{x1:i[o=o||0],y1:i[1-o],x2:r[o],y2:r[1-o]})}},shadow:function(t,e,n){var i,r,o,a=Math.max(1,t.getBandWidth()),s=n[1]-n[0];return{type:"Rect",shape:(i=[e-a/2,n[0]],r=[a,s],o=kM(t),{x:i[o=o||0],y:i[1-o],width:r[o],height:r[1-o]})}}};function kM(t){return"x"===t.dim?0:1}var MM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.type="axisPointer",e.defaultOption={show:"auto",z:50,type:"line",snap:!1,triggerTooltip:!0,triggerEmphasis:!0,value:null,status:null,link:[],animation:null,animationDurationUpdate:200,lineStyle:{color:Im.color.border,width:1,type:"dashed"},shadowStyle:{color:Im.color.shadowTint},label:{show:!0,formatter:null,precision:"auto",margin:3,color:Im.color.neutral00,padding:[5,7,5,7],backgroundColor:Im.color.accent60,borderColor:null,borderWidth:0,borderRadius:3},handle:{show:!1,icon:"M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z",size:45,margin:50,color:Im.color.accent40,throttle:40}},e}(Am),TM=Sc(),AM=Ui;function IM(t,e,n){if(!yi.node){var i=e.getZr();TM(i).records||(TM(i).records={}),function(t,e){if(TM(t).initialized)return;function n(n,i){t.on(n,function(n){var r=function(t){var e={showTip:[],hideTip:[]},n=function(i){var r=e[i.type];r?r.push(i):(i.dispatchAction=n,t.dispatchAction(i))};return{dispatchAction:n,pendings:e}}(e);AM(TM(t).records,function(t){t&&i(t,n,r.dispatchAction)}),function(t,e){var n,i=t.showTip.length,r=t.hideTip.length;i?n=t.showTip[i-1]:r&&(n=t.hideTip[r-1]);n&&(n.dispatchAction=null,e.dispatchAction(n))}(r.pendings,e)})}TM(t).initialized=!0,n("click",Qi(PM,"click")),n("mousemove",Qi(PM,"mousemove")),n("globalout",DM)}(i,e),(TM(i).records[t]||(TM(i).records[t]={})).handler=n}}function DM(t,e,n){t.handler("leave",null,n)}function PM(t,e,n,i){e.handler(t,n,i)}function LM(t,e){if(!yi.node){var n=e.getZr();(TM(n).records||{})[t]&&(TM(n).records[t]=null)}}var EM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.prototype.render=function(t,e,n){var i=e.getComponent("tooltip"),r=t.get("triggerOn")||i&&i.get("triggerOn")||"mousemove|click";IM("axisPointer",n,function(t,e,n){"none"!==r&&("leave"===t||r.indexOf(t)>=0)&&n({type:"updateAxisPointer",currTrigger:t,x:e&&e.offsetX,y:e&&e.offsetY})})},e.prototype.remove=function(t,e){LM("axisPointer",e)},e.prototype.dispose=function(t,e){LM("axisPointer",e)},e.type="axisPointer",e}(h_);function NM(t,e){var n,i=[],r=t.seriesIndex;if(null==r||!(n=e.getSeriesByIndex(r)))return{point:[]};var o=n.getData(),a=wc(o,t);if(null==a||a<0||Ji(a))return{point:[]};var s=o.getItemGraphicEl(a),l=n.coordinateSystem;if(n.getTooltipPosition)i=n.getTooltipPosition(a)||[];else if(l&&l.dataToPoint)if(t.isStacked){var c=l.getBaseAxis(),u=l.getOtherAxis(c).dim,d=c.dim,h="x"===u||"radius"===u?1:0,p=o.mapDimension(d),f=[];f[h]=o.get(p,a),f[1-h]=o.get(o.getCalculationInfo("stackResultDimension"),a),i=l.dataToPoint(f)||[]}else i=l.dataToPoint(o.getValues(Gi(l.dimensions,function(t){return o.mapDimension(t)}),a))||[];else if(s){var g=s.getBoundingRect().clone();g.applyTransform(s.transform),i=[g.x+g.width/2,g.y+g.height/2]}return{point:i,el:s}}var RM=Sc();function OM(t,e,n){var i=t.currTrigger,r=[t.x,t.y],o=t,a=t.dispatchAction||Ki(n.dispatchAction,n),s=e.getComponent("axisPointer").coordSysAxesInfo;if(s){FM(r)&&(r=NM({seriesIndex:o.seriesIndex,dataIndex:o.dataIndex},e).point);var l=FM(r),c=o.axesInfo,u=s.axesInfo,d="leave"===i||FM(r),h={},p={},f={list:[],map:{}},g={showPointer:Qi(HM,p),showTooltip:Qi(BM,f)};Ui(s.coordSysMap,function(t,e){var n=l||t.containPoint(r);Ui(s.coordSysAxesInfo[e],function(t,e){var i=t.axis,o=function(t,e){for(var n=0;n<(t||[]).length;n++){var i=t[n];if(e.axis.dim===i.axisDim&&e.axis.model.componentIndex===i.axisIndex)return i}}(c,t);if(!d&&n&&(!c||o)){var a=o&&o.value;null!=a||l||(a=i.pointToData(r)),null!=a&&zM(t,a,g,!1,h)}})});var m={};return Ui(u,function(t,e){var n=t.linkGroup;n&&!p[e]&&Ui(n.axesInfo,function(e,i){var r=p[i];if(e!==t&&r){var o=r.value;n.mapper&&(o=t.axis.scale.parse(n.mapper(o,$M(e),$M(t)))),m[t.key]=o}})}),Ui(m,function(t,e){zM(u[e],t,g,!0,h)}),function(t,e,n){var i=n.axesInfo=[];Ui(e,function(e,n){var r=e.axisPointerModel.option,o=t[n];o?(!e.useHandle&&(r.status="show"),r.value=o.value,r.seriesDataIndices=(o.payloadBatch||[]).slice()):!e.useHandle&&(r.status="hide"),"show"===r.status&&i.push({axisDim:e.axis.dim,axisIndex:e.axis.model.componentIndex,value:r.value})})}(p,u,h),function(t,e,n,i){if(FM(e)||!t.list.length)return void i({type:"hideTip"});var r=((t.list[0].dataByAxis[0]||{}).seriesDataIndices||[])[0]||{};i({type:"showTip",escapeConnect:!0,x:e[0],y:e[1],tooltipOption:n.tooltipOption,position:n.position,dataIndexInside:r.dataIndexInside,dataIndex:r.dataIndex,seriesIndex:r.seriesIndex,dataByCoordSys:t.list})}(f,r,t,a),function(t,e,n){var i=n.getZr(),r="axisPointerLastHighlights",o=RM(i)[r]||{},a=RM(i)[r]={};Ui(t,function(t,e){var n=t.axisPointerModel.option;"show"===n.status&&t.triggerEmphasis&&Ui(n.seriesDataIndices,function(t){var e=t.seriesIndex+" | "+t.dataIndex;a[e]=t})});var s=[],l=[];Ui(o,function(t,e){!a[e]&&l.push(t)}),Ui(a,function(t,e){!o[e]&&s.push(t)}),l.length&&n.dispatchAction({type:"downplay",escapeConnect:!0,notBlur:!0,batch:l}),s.length&&n.dispatchAction({type:"highlight",escapeConnect:!0,notBlur:!0,batch:s})}(u,0,n),h}}function zM(t,e,n,i,r){var o=t.axis;if(!o.scale.isBlank()&&o.containData(e))if(t.involveSeries){var a=function(t,e){var n=e.axis,i=n.dim,r=t,o=[],a=Number.MAX_VALUE,s=-1;return Ui(e.seriesModels,function(e,l){var c,u,d=e.getData().mapDimensionsAll(i);if(e.getAxisTooltipData){var h=e.getAxisTooltipData(d,t,n);u=h.dataIndices,c=h.nestestValue}else{if(!(u=e.indicesOfNearest(i,d[0],t,"category"===n.type?.5:null)).length)return;c=e.getData().get(d[0],u[0])}if(null!=c&&isFinite(c)){var p=t-c,f=Math.abs(p);f<=a&&((f=0&&s<0)&&(a=f,s=p,r=c,o.length=0),Ui(u,function(t){o.push({seriesIndex:e.seriesIndex,dataIndexInside:t,dataIndex:e.getData().getRawIndex(t)})}))}}),{payloadBatch:o,snapToValue:r}}(e,t),s=a.payloadBatch,l=a.snapToValue;s[0]&&null==r.seriesIndex&&Fi(r,s[0]),!i&&t.snap&&o.containData(l)&&null!=l&&(e=l),n.showPointer(t,e,s),n.showTooltip(t,a,l)}else n.showPointer(t,e)}function HM(t,e,n,i){t[e.key]={value:n,payloadBatch:i}}function BM(t,e,n,i){var r=n.payloadBatch,o=e.axis,a=o.model,s=e.axisPointerModel;if(e.triggerTooltip&&r.length){var l=e.coordSys.model,c=Qk(l),u=t.map[c];u||(u=t.map[c]={coordSysId:l.id,coordSysIndex:l.componentIndex,coordSysType:l.type,coordSysMainType:l.mainType,dataByAxis:[]},t.list.push(u)),u.dataByAxis.push({axisDim:o.dim,axisIndex:a.componentIndex,axisType:a.type,axisId:a.id,value:i,valueLabelOpt:{precision:s.get(["label","precision"]),formatter:s.get(["label","formatter"])},seriesDataIndices:r.slice()})}}function $M(t){var e=t.axis.model,n={},i=n.axisDim=t.axis.dim;return n.axisIndex=n[i+"AxisIndex"]=e.componentIndex,n.axisName=n[i+"AxisName"]=e.name,n.axisId=n[i+"AxisId"]=e.id,n}function FM(t){return!t||null==t[0]||isNaN(t[0])||null==t[1]||isNaN(t[1])}function VM(t){tM.registerAxisPointerClass("CartesianAxisPointer",wM),t.registerComponentModel(MM),t.registerComponentView(EM),t.registerPreprocessor(function(t){if(t){(!t.axisPointer||0===t.axisPointer.length)&&(t.axisPointer={});var e=t.axisPointer.link;e&&!Ji(e)&&(t.axisPointer.link=[e])}}),t.registerProcessor(t.PRIORITY.PROCESSOR.STATISTIC,function(t,e){t.getComponent("axisPointer").coordSysAxesInfo=Xk(t,e)}),t.registerAction({type:"updateAxisPointer",event:"updateAxisPointer",update:":updateAxisPointer"},OM)}var WM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.type="tooltip",e.dependencies=["axisPointer"],e.defaultOption={z:60,show:!0,showContent:!0,trigger:"item",triggerOn:"mousemove|click",alwaysShowContent:!1,renderMode:"auto",confine:null,showDelay:0,hideDelay:100,transitionDuration:.4,displayTransition:!0,enterable:!1,backgroundColor:Im.color.neutral00,shadowBlur:10,shadowColor:"rgba(0, 0, 0, .2)",shadowOffsetX:1,shadowOffsetY:2,borderRadius:4,borderWidth:1,defaultBorderColor:Im.color.border,padding:null,extraCssText:"",axisPointer:{type:"line",axis:"auto",animation:"auto",animationDurationUpdate:200,animationEasingUpdate:"exponentialOut",crossStyle:{color:Im.color.borderShade,width:1,type:"dashed",textStyle:{}}},textStyle:{color:Im.color.tertiary,fontSize:14}},e}(Am);function jM(t){var e=t.get("confine");return null!=e?!!e:"richText"===t.get("renderMode")}function qM(t){if(yi.domSupported)for(var e=document.documentElement.style,n=0,i=t.length;n0&&r.push(function(t,e,n){var i="cubic-bezier(0.23,1,0.32,1)",r="",o="";return n&&(o="opacity"+(r=" "+t/2+"s "+i)+",visibility"+r),e||(r=" "+t+"s "+i,o+=(o.length?",":"")+(yi.transformSupported?""+YM+r:",left"+r+",top"+r)),XM+":"+o}(o,n,i)),a&&r.push("background-color:"+a),Ui(["width","color","radius"],function(e){var n="border-"+e,i=tm(n),o=t.get(i);null!=o&&r.push(n+":"+o+("color"===e?"":"px"))}),r.push(function(t){var e=[],n=t.get("fontSize"),i=t.getTextColor();i&&e.push("color:"+i),e.push("font:"+t.getFont());var r=dr(t.get("lineHeight"),Math.round(3*n/2));n&&e.push("line-height:"+r+"px");var o=t.get("textShadowColor"),a=t.get("textShadowBlur")||0,s=t.get("textShadowOffsetX")||0,l=t.get("textShadowOffsetY")||0;return o&&a&&e.push("text-shadow:"+s+"px "+l+"px "+a+"px "+o),Ui(["decoration","align"],function(n){var i=t.get(n);i&&e.push("text-"+n+":"+i)}),e.join(";")}(d)),null!=h&&r.push("padding:"+em(h).join("px ")+"px"),r.join(";")+";"}function JM(t,e,n,i,r){var o=e&&e.painter;if(n){var a=o&&o.getViewportRoot();a&&function(t,e,n,i,r){Xr(Gr,e,i,r,!0)&&Xr(t,n,Gr[0],Gr[1])}(t,a,n,i,r)}else{t[0]=i,t[1]=r;var s=o&&o.getViewportRootOffset();s&&(t[0]+=s.offsetLeft,t[1]+=s.offsetTop)}t[2]=t[0]/e.getWidth(),t[3]=t[1]/e.getHeight()}var tT=function(){function t(t,e){if(this._show=!1,this._styleCoord=[0,0,0,0],this._enterable=!0,this._alwaysShowContent=!1,this._firstShow=!0,this._longHide=!0,yi.wxa)return null;var n=document.createElement("div");n.domBelongToZr=!0,this.el=n;var i=this._zr=t.getZr(),r=e.appendTo,o=r&&(er(r)?document.querySelector(r):sr(r)?r:tr(r)&&r(t.getDom()));JM(this._styleCoord,i,o,t.getWidth()/2,t.getHeight()/2),(o||t.getDom()).appendChild(n),this._api=t,this._container=o;var a=this;n.onmouseenter=function(){a._enterable&&(clearTimeout(a._hideTimeout),a._show=!0),a._inContent=!0},n.onmousemove=function(t){if(t=t||window.event,!a._enterable){var e=i.handler;oo(i.painter.getViewportRoot(),t,!0),e.dispatch("mousemove",t)}},n.onmouseleave=function(){a._inContent=!1,a._enterable&&a._show&&a.hideLater(a._hideDelay)}}return t.prototype.update=function(t){if(!this._container){var e=this._api.getDom(),n=(o="position",(a=(r=e).currentStyle||document.defaultView&&document.defaultView.getComputedStyle(r))?a[o]:null),i=e.style;"absolute"!==i.position&&"absolute"!==n&&(i.position="relative")}var r,o,a,s=t.get("alwaysShowContent");s&&this._moveIfResized(),this._alwaysShowContent=s,this._enableDisplayTransition=t.get("displayTransition")&&t.get("transitionDuration")>0,this.el.className=t.get("className")||""},t.prototype.show=function(t,e){clearTimeout(this._hideTimeout),clearTimeout(this._longHideTimeout);var n=this.el,i=n.style,r=this._styleCoord;n.innerHTML?i.cssText=ZM+QM(t,!this._firstShow,this._longHide,this._enableDisplayTransition)+KM(r[0],r[1],!0)+"border-color:"+am(e)+";"+(t.get("extraCssText")||"")+";pointer-events:"+(this._enterable?"auto":"none"):i.display="none",this._show=!0,this._firstShow=!1,this._longHide=!1},t.prototype.setContent=function(t,e,n,i,r){var o=this.el;if(null!=t){var a="";if(er(r)&&"item"===n.get("trigger")&&!jM(n)&&(a=function(t,e,n){if(!er(n)||"inside"===n)return"";var i=t.get("backgroundColor"),r=t.get("borderWidth");e=am(e);var o,a,s="left"===(o=n)?"right":"right"===o?"left":"top"===o?"bottom":"top",l=Math.max(1.5*Math.round(r),6),c="",u=YM+":";Wi(["left","right"],s)>-1?(c+="top:50%",u+="translateY(-50%) rotate("+(a="left"===s?-225:-45)+"deg)"):(c+="left:50%",u+="translateX(-50%) rotate("+(a="top"===s?225:45)+"deg)");var d=a*Math.PI/180,h=l+r,p=h*Math.abs(Math.cos(d))+h*Math.abs(Math.sin(d)),f=e+" solid "+r+"px;";return'
'}(n,i,r)),er(t))o.innerHTML=t+a;else if(t){o.innerHTML="",Ji(t)||(t=[t]);for(var s=0;s=0?this._tryShow(n,i):"leave"===e&&this._hide(i))},this))},e.prototype._keepShow=function(){var t=this._tooltipModel,e=this._ecModel,n=this._api,i=t.get("triggerOn");if(null!=this._lastX&&null!=this._lastY&&"none"!==i&&"click"!==i){var r=this;clearTimeout(this._refreshUpdateTimeout),this._refreshUpdateTimeout=setTimeout(function(){!n.isDisposed()&&r.manuallyShowTip(t,e,n,{x:r._lastX,y:r._lastY,dataByCoordSys:r._lastDataByCoordSys})})}},e.prototype.manuallyShowTip=function(t,e,n,i){if(i.from!==this.uid&&!yi.node&&n.getDom()){var r=lT(i,n);this._ticket="";var o=i.dataByCoordSys,a=function(t,e,n){var i=Mc(t).queryOptionMap,r=i.keys()[0];if(!r||"series"===r)return;var o=Ac(e,r,i.get(r),{useDefault:!1,enableAll:!1,enableNone:!1}),a=o.models[0];if(!a)return;var s,l=n.getViewOfComponentModel(a);if(l.group.traverse(function(e){var n=Ud(e).tooltipConfig;if(n&&n.name===t.name)return s=e,!0}),s)return{componentMainType:r,componentIndex:a.componentIndex,el:s}}(i,e,n);if(a){var s=a.el.getBoundingRect().clone();s.applyTransform(a.el.transform),this._tryShow({offsetX:s.x+s.width/2,offsetY:s.y+s.height/2,target:a.el,position:i.position,positionDefault:"bottom"},r)}else if(i.tooltip&&null!=i.x&&null!=i.y){var l=oT;l.x=i.x,l.y=i.y,l.update(),Ud(l).tooltipConfig={name:null,option:i.tooltip},this._tryShow({offsetX:i.x,offsetY:i.y,target:l},r)}else if(o)this._tryShow({offsetX:i.x,offsetY:i.y,position:i.position,dataByCoordSys:o,tooltipOption:i.tooltipOption},r);else if(null!=i.seriesIndex){if(this._manuallyAxisShowTip(t,e,n,i))return;var c=NM(i,e),u=c.point[0],d=c.point[1];null!=u&&null!=d&&this._tryShow({offsetX:u,offsetY:d,target:c.el,position:i.position,positionDefault:"bottom"},r)}else null!=i.x&&null!=i.y&&(n.dispatchAction({type:"updateAxisPointer",x:i.x,y:i.y}),this._tryShow({offsetX:i.x,offsetY:i.y,position:i.position,target:n.getZr().findHover(i.x,i.y).target},r))}},e.prototype.manuallyHideTip=function(t,e,n,i){var r=this._tooltipContent;this._tooltipModel&&r.hideLater(this._tooltipModel.get("hideDelay")),this._lastX=this._lastY=this._lastDataByCoordSys=null,i.from!==this.uid&&this._hide(lT(i,n))},e.prototype._manuallyAxisShowTip=function(t,e,n,i){var r=i.seriesIndex,o=i.dataIndex,a=e.getComponent("axisPointer").coordSysAxesInfo;if(null!=r&&null!=o&&null!=a){var s=e.getSeriesByIndex(r);if(s)if("axis"===sT([s.getData().getItemModel(o),s,(s.coordinateSystem||{}).model],this._tooltipModel).get("trigger"))return n.dispatchAction({type:"updateAxisPointer",seriesIndex:r,dataIndex:o,position:i.position}),!0}},e.prototype._tryShow=function(t,e){var n=t.target;if(this._tooltipModel){this._lastX=t.offsetX,this._lastY=t.offsetY;var i=t.dataByCoordSys;if(i&&i.length)this._showAxisTooltip(i,t);else if(n){var r,o;if("legend"===Ud(n).ssrType)return;this._lastDataByCoordSys=null,db(n,function(t){if(t.tooltipDisabled)return r=o=null,!0;r||o||(null!=Ud(t).dataIndex?r=t:null!=Ud(t).tooltipConfig&&(o=t))},!0),r?this._showSeriesItemTooltip(t,r,e):o?this._showComponentItemTooltip(t,o,e):this._hide(e)}else this._lastDataByCoordSys=null,this._hide(e)}},e.prototype._showOrMove=function(t,e){var n=t.get("showDelay");e=Ki(e,this),clearTimeout(this._showTimout),n>0?this._showTimout=setTimeout(e,n):e()},e.prototype._showAxisTooltip=function(t,e){var n=this._ecModel,i=this._tooltipModel,r=[e.offsetX,e.offsetY],o=sT([e.tooltipOption],i),a=this._renderMode,s=[],l=jy("section",{blocks:[],noHeader:!0}),c=[],u=new t_;Ui(t,function(t){Ui(t.dataByAxis,function(t){var e=n.getComponent(t.axisDim+"Axis",t.axisIndex),r=t.value;if(e&&null!=r){var o=bM(r,e.axis,n,t.seriesDataIndices,t.valueLabelOpt),d=jy("section",{header:o,noHeader:!mr(o),sortBlocks:!0,blocks:[]});l.blocks.push(d),Ui(t.seriesDataIndices,function(l){var h=n.getSeriesByIndex(l.seriesIndex),p=l.dataIndexInside,f=h.getDataParams(p);if(!(f.dataIndex<0)){f.axisDim=t.axisDim,f.axisIndex=t.axisIndex,f.axisType=t.axisType,f.axisId=t.axisId,f.axisValue=LS(e.axis,{value:r}),f.axisValueLabel=o,f.marker=u.makeTooltipMarker("item",am(f.color),a);var g=dy(h.formatTooltip(p,!0,null)),m=g.frag;if(m){var v=sT([h],i).get("valueFormatter");d.blocks.push(v?Fi({valueFormatter:v},m):m)}g.text&&c.push(g.text),s.push(f)}})}})}),l.blocks.reverse(),c.reverse();var d=e.position,h=o.get("order"),p=Zy(l,u,a,h,n.get("useUTC"),o.get("textStyle"));p&&c.unshift(p);var f="richText"===a?"\n\n":"
",g=c.join(f);this._showOrMove(o,function(){this._updateContentNotChangedOnAxis(t,s)?this._updatePosition(o,d,r[0],r[1],this._tooltipContent,s):this._showTooltipContent(o,g,s,Math.random()+"",r[0],r[1],d,null,u)})},e.prototype._showSeriesItemTooltip=function(t,e,n){var i=this._ecModel,r=Ud(e),o=r.seriesIndex,a=i.getSeriesByIndex(o),s=r.dataModel||a,l=r.dataIndex,c=r.dataType,u=s.getData(c),d=this._renderMode,h=t.positionDefault,p=sT([u.getItemModel(l),s,a&&(a.coordinateSystem||{}).model],this._tooltipModel,h?{position:h}:null),f=p.get("trigger");if(null==f||"item"===f){var g=s.getDataParams(l,c),m=new t_;g.marker=m.makeTooltipMarker("item",am(g.color),d);var v=dy(s.formatTooltip(l,!1,c)),y=p.get("order"),_=p.get("valueFormatter"),b=v.frag,x=b?Zy(_?Fi({valueFormatter:_},b):b,m,d,y,i.get("useUTC"),p.get("textStyle")):v.text,w="item_"+s.name+"_"+l;this._showOrMove(p,function(){this._showTooltipContent(p,x,g,w,t.offsetX,t.offsetY,t.position,t.target,m)}),n({type:"showTip",dataIndexInside:l,dataIndex:u.getRawIndex(l),seriesIndex:o,from:this.uid})}},e.prototype._showComponentItemTooltip=function(t,e,n){var i="html"===this._renderMode,r=Ud(e),o=r.tooltipConfig.option||{},a=o.encodeHTMLContent;if(er(o)){o={content:o,formatter:o},a=!0}a&&i&&o.content&&((o=Bi(o)).content=Qr(o.content));var s=[o],l=this._ecModel.getComponent(r.componentMainType,r.componentIndex);l&&s.push(l),s.push({formatter:o.content});var c=t.positionDefault,u=sT(s,this._tooltipModel,c?{position:c}:null),d=u.get("content"),h=Math.random()+"",p=new t_;this._showOrMove(u,function(){var n=Bi(u.get("formatterParams")||{});this._showTooltipContent(u,d,n,h,t.offsetX,t.offsetY,t.position,e,p)}),n({type:"showTip",from:this.uid})},e.prototype._showTooltipContent=function(t,e,n,i,r,o,a,s,l){if(this._ticket="",t.get("showContent")&&t.get("show")){var c=this._tooltipContent;c.setEnterable(t.get("enterable"));var u=t.get("formatter");a=a||t.get("position");var d=e,h=this._getNearestPoint([r,o],n,t.get("trigger"),t.get("borderColor"),t.get("defaultBorderColor",!0)).color;if(u)if(er(u)){var p=t.ecModel.get("useUTC"),f=Ji(n)?n[0]:n;d=u,f&&f.axisType&&f.axisType.indexOf("time")>=0&&(d=Og(f.axisValue,d,p)),d=om(d,n,!0)}else if(tr(u)){var g=Ki(function(e,i){e===this._ticket&&(c.setContent(i,l,t,h,a),this._updatePosition(t,a,r,o,c,n,s))},this);this._ticket=i,d=u(n,i,g)}else d=u;c.setContent(d,l,t,h,a),c.show(t,h),this._updatePosition(t,a,r,o,c,n,s)}},e.prototype._getNearestPoint=function(t,e,n,i,r){return"axis"===n||Ji(e)?{color:i||r}:Ji(e)?void 0:{color:i||e.color||e.borderColor}},e.prototype._updatePosition=function(t,e,n,i,r,o,a){var s=this._api.getWidth(),l=this._api.getHeight();e=e||t.get("position");var c=r.getSize(),u=t.get("align"),d=t.get("verticalAlign"),h=a&&a.getBoundingRect().clone();if(a&&h.applyTransform(a.transform),tr(e)&&(e=e([n,i],o,r.el,h,{viewSize:[s,l],contentSize:c.slice()})),Ji(e))n=ql(e[0],s),i=ql(e[1],l);else if(rr(e)){var p=e;p.width=c[0],p.height=c[1];var f=xm(p,{width:s,height:l});n=f.x,i=f.y,u=null,d=null}else if(er(e)&&a){var g=function(t,e,n,i){var r=n[0],o=n[1],a=Math.ceil(Math.SQRT2*i)+8,s=0,l=0,c=e.width,u=e.height;switch(t){case"inside":s=e.x+c/2-r/2,l=e.y+u/2-o/2;break;case"top":s=e.x+c/2-r/2,l=e.y-o-a;break;case"bottom":s=e.x+c/2-r/2,l=e.y+u+a;break;case"left":s=e.x-r-a,l=e.y+u/2-o/2;break;case"right":s=e.x+c+a,l=e.y+u/2-o/2}return[s,l]}(e,h,c,t.get("borderWidth"));n=g[0],i=g[1]}else{g=function(t,e,n,i,r,o,a){var s=n.getSize(),l=s[0],c=s[1];null!=o&&(t+l+o+2>i?t-=l+o:t+=o);null!=a&&(e+c+a>r?e-=c+a:e+=a);return[t,e]}(n,i,r,s,l,u?null:20,d?null:20);n=g[0],i=g[1]}if(u&&(n-=cT(u)?c[0]/2:"right"===u?c[0]:0),d&&(i-=cT(d)?c[1]/2:"bottom"===d?c[1]:0),jM(t)){g=function(t,e,n,i,r){var o=n.getSize(),a=o[0],s=o[1];return t=Math.min(t+a,i)-a,e=Math.min(e+s,r)-s,t=Math.max(t,0),e=Math.max(e,0),[t,e]}(n,i,r,s,l);n=g[0],i=g[1]}r.moveTo(n,i)},e.prototype._updateContentNotChangedOnAxis=function(t,e){var n=this._lastDataByCoordSys,i=this._cbParamsList,r=!!n&&n.length===t.length;return r&&Ui(n,function(n,o){var a=n.dataByAxis||[],s=(t[o]||{}).dataByAxis||[];(r=r&&a.length===s.length)&&Ui(a,function(t,n){var o=s[n]||{},a=t.seriesDataIndices||[],l=o.seriesDataIndices||[];(r=r&&t.value===o.value&&t.axisType===o.axisType&&t.axisId===o.axisId&&a.length===l.length)&&Ui(a,function(t,e){var n=l[e];r=r&&t.seriesIndex===n.seriesIndex&&t.dataIndex===n.dataIndex}),i&&Ui(t.seriesDataIndices,function(t){var n=t.seriesIndex,o=e[n],a=i[n];o&&a&&a.data!==o.data&&(r=!1)})})}),this._lastDataByCoordSys=t,this._cbParamsList=e,!!r},e.prototype._hide=function(t){this._lastDataByCoordSys=null,t({type:"hideTip",from:this.uid})},e.prototype.dispose=function(t,e){!yi.node&&e.getDom()&&(T_(this,"_updatePosition"),this._tooltipContent.dispose(),LM("itemTooltip",e))},e.type="tooltip",e}(h_);function sT(t,e,n){var i,r=e.ecModel;n?(i=new ug(n,r,r),i=new ug(e.option,i,r)):i=e;for(var o=t.length-1;o>=0;o--){var a=t[o];a&&(a instanceof ug&&(a=a.get("tooltip",!0)),er(a)&&(a={formatter:a}),a&&(i=new ug(a,i,r)))}return i}function lT(t,e){return t.dispatchAction||Ki(e.dispatchAction,e)}function cT(t){return"center"===t||"middle"===t}var uT=Math.sin,dT=Math.cos,hT=Math.PI,pT=2*Math.PI,fT=180/hT,gT=function(){function t(){}return t.prototype.reset=function(t){this._start=!0,this._d=[],this._str="",this._p=Math.pow(10,t||4)},t.prototype.moveTo=function(t,e){this._add("M",t,e)},t.prototype.lineTo=function(t,e){this._add("L",t,e)},t.prototype.bezierCurveTo=function(t,e,n,i,r,o){this._add("C",t,e,n,i,r,o)},t.prototype.quadraticCurveTo=function(t,e,n,i){this._add("Q",t,e,n,i)},t.prototype.arc=function(t,e,n,i,r,o){this.ellipse(t,e,n,n,0,i,r,o)},t.prototype.ellipse=function(t,e,n,i,r,o,a,s){var l=a-o,c=!s,u=Math.abs(l),d=ns(u-pT)||(c?l>=pT:-l>=pT),h=l>0?l%pT:l%pT+pT,p=!1;p=!!d||!ns(u)&&h>=hT==!!c;var f=t+n*dT(o),g=e+i*uT(o);this._start&&this._add("M",f,g);var m=Math.round(r*fT);if(d){var v=1/this._p,y=(c?1:-1)*(pT-v);this._add("A",n,i,m,1,+c,t+n*dT(o+y),e+i*uT(o+y)),v>.01&&this._add("A",n,i,m,0,+c,f,g)}else{var _=t+n*dT(a),b=e+i*uT(a);this._add("A",n,i,m,+p,+c,_,b)}},t.prototype.rect=function(t,e,n,i){this._add("M",t,e),this._add("l",n,0),this._add("l",0,i),this._add("l",-n,0),this._add("Z")},t.prototype.closePath=function(){this._d.length>0&&this._add("Z")},t.prototype._add=function(t,e,n,i,r,o,a,s,l){for(var c=[],u=this._p,d=1;d"}(r,o)+("style"!==r?Qr(a):a||"")+(i?""+n+Gi(i,function(e){return t(e)}).join(n)+n:"")+("")}(t)}function TT(t){return{zrId:t,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function AT(t,e,n,i){return kT("svg","root",{width:t,height:e,xmlns:xT,"xmlns:xlink":wT,version:"1.1",baseProfile:"full",viewBox:!!i&&"0 0 "+t+" "+e},n)}var IT=0;function DT(){return IT++}var PT={cubicIn:"0.32,0,0.67,0",cubicOut:"0.33,1,0.68,1",cubicInOut:"0.65,0,0.35,1",quadraticIn:"0.11,0,0.5,0",quadraticOut:"0.5,1,0.89,1",quadraticInOut:"0.45,0,0.55,1",quarticIn:"0.5,0,0.75,0",quarticOut:"0.25,1,0.5,1",quarticInOut:"0.76,0,0.24,1",quinticIn:"0.64,0,0.78,0",quinticOut:"0.22,1,0.36,1",quinticInOut:"0.83,0,0.17,1",sinusoidalIn:"0.12,0,0.39,0",sinusoidalOut:"0.61,1,0.88,1",sinusoidalInOut:"0.37,0,0.63,1",exponentialIn:"0.7,0,0.84,0",exponentialOut:"0.16,1,0.3,1",exponentialInOut:"0.87,0,0.13,1",circularIn:"0.55,0,1,0.45",circularOut:"0,0.55,0.45,1",circularInOut:"0.85,0,0.15,1"},LT="transform-origin";function ET(t,e,n){var i=Fi({},t.shape);Fi(i,e),t.buildPath(n,i);var r=new gT;return r.reset(hs(t)),n.rebuildPath(r,1),r.generateStr(),r.getStr()}function NT(t,e){var n=e.originX,i=e.originY;(n||i)&&(t[LT]=n+"px "+i+"px")}var RT={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function OT(t,e){var n=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[n]=t,n}function zT(t){return er(t)?PT[t]?"cubic-bezier("+PT[t]+")":Aa(t)?t:"":""}function HT(t,e,n,i){var r=t.animators,o=r.length,a=[];if(t instanceof Bp){var s=function(t,e,n){var i,r,o=t.shape.paths,a={};if(Ui(o,function(t){var e=TT(n.zrId);e.animation=!0,HT(t,{},e,!0);var o=e.cssAnims,s=e.cssNodes,l=Zi(o),c=l.length;if(c){var u=o[r=l[c-1]];for(var d in u){var h=u[d];a[d]=a[d]||{d:""},a[d].d+=h.d||""}for(var p in s){var f=s[p].animation;f.indexOf(r)>=0&&(i=f)}}}),i){e.d=!1;var s=OT(a,n);return i.replace(r,s)}}(t,e,n);if(s)a.push(s);else if(!o)return}else if(!o)return;for(var l={},c=0;c0}).length)return OT(u,n)+" "+r[0]+" both"}for(var m in l){(s=g(l[m]))&&a.push(s)}if(a.length){var v=n.zrId+"-cls-"+DT();n.cssNodes["."+v]={animation:a.join(",")},e.class=v}}function BT(t,e,n,i){var r=JSON.stringify(t),o=n.cssStyleCache[r];o||(o=n.zrId+"-cls-"+DT(),n.cssStyleCache[r]=o,n.cssNodes["."+o+":hover"]=t),e.class=e.class?e.class+" "+o:o}var $T=Math.round;function FT(t){return t&&er(t.src)}function VT(t){return t&&tr(t.toDataURL)}function WT(t,e,n,i){bT(function(r,o){var a="fill"===r||"stroke"===r;a&&us(o)?tA(e,t,r,i):a&&ss(o)?eA(n,t,r,i):t[r]=o,a&&i.ssr&&"none"===o&&(t["pointer-events"]="visible")},e,n,!1),function(t,e,n){var i=t.style;if(function(t){return t&&(t.shadowBlur||t.shadowOffsetX||t.shadowOffsetY)}(i)){var r=function(t){var e=t.style,n=t.getGlobalScale();return[e.shadowColor,(e.shadowBlur||0).toFixed(2),(e.shadowOffsetX||0).toFixed(2),(e.shadowOffsetY||0).toFixed(2),n[0],n[1]].join(",")}(t),o=n.shadowCache,a=o[r];if(!a){var s=t.getGlobalScale(),l=s[0],c=s[1];if(!l||!c)return;var u=i.shadowOffsetX||0,d=i.shadowOffsetY||0,h=i.shadowBlur,p=ts(i.shadowColor),f=p.opacity,g=p.color,m=h/2/l+" "+h/2/c;a=n.zrId+"-s"+n.shadowIdx++,n.defs[a]=kT("filter",a,{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},[kT("feDropShadow","",{dx:u/l,dy:d/c,stdDeviation:m,"flood-color":g,"flood-opacity":f})]),o[r]=a}e.filter=ds(a)}}(n,t,i)}function jT(t,e){var n=function(t){if("function"==typeof zl)return zl(t)}(e);n&&(n.each(function(e,n){null!=e&&(t[(ST+n).toLowerCase()]=e+"")}),e.isSilent()&&(t[ST+"silent"]="true"))}function qT(t){return ns(t[0]-1)&&ns(t[1])&&ns(t[2])&&ns(t[3]-1)}function UT(t,e,n){if(e&&(!function(t){return ns(t[4])&&ns(t[5])}(e)||!qT(e))){var i=1e4;t.transform=qT(e)?"translate("+$T(e[4]*i)/i+" "+$T(e[5]*i)/i+")":function(t){return"matrix("+is(t[0])+","+is(t[1])+","+is(t[2])+","+is(t[3])+","+rs(t[4])+","+rs(t[5])+")"}(e)}}function GT(t,e,n){for(var i=t.points,r=[],o=0;o=0&&a||o;s&&(r=Qa(s))}var l=i.lineWidth;l&&(l/=!i.strokeNoScale&&t.transform?t.transform[0]:1);var c={cursor:"pointer"};r&&(c.fill=r),i.stroke&&(c.stroke=i.stroke),l&&(c["stroke-width"]=l),BT(c,e,n)}}(t,o,e),kT(s,t.id+"",o)}function JT(t,e){return t instanceof vd?QT(t,e):t instanceof wd?function(t,e){var n=t.style,i=n.image;if(i&&!er(i)&&(FT(i)?i=i.src:VT(i)&&(i=i.toDataURL())),i){var r=n.x||0,o=n.y||0,a={href:i,width:n.width,height:n.height};return r&&(a.x=r),o&&(a.y=o),UT(a,t.transform),WT(a,n,t,e),jT(a,t),e.animation&&HT(t,a,e),kT("image",t.id+"",a)}}(t,e):t instanceof _d?function(t,e){var n=t.style,i=n.text;if(null!=i&&(i+=""),i&&!isNaN(n.x)&&!isNaN(n.y)){var r=n.font||bi,o=n.x||0,a=function(t,e,n){return"top"===n?t+=e/2:"bottom"===n&&(t-=e/2),t}(n.y||0,bl(r),n.textBaseline),s={"dominant-baseline":"central","text-anchor":os[n.textAlign]||n.textAlign};if(Bd(n)){var l="",c=n.fontStyle,u=zd(n.fontSize);if(!parseFloat(u))return;var d=n.fontFamily||_i,h=n.fontWeight;l+="font-size:"+u+";font-family:"+d+";",c&&"normal"!==c&&(l+="font-style:"+c+";"),h&&"normal"!==h&&(l+="font-weight:"+h+";"),s.style=l}else s.style="font: "+r;return i.match(/\s/)&&(s["xml:space"]="preserve"),o&&(s.x=o),a&&(s.y=a),UT(s,t.transform),WT(s,n,t,e),jT(s,t),e.animation&&HT(t,s,e),kT("text",t.id+"",s,void 0,i)}}(t,e):void 0}function tA(t,e,n,i){var r,o=t[n],a={gradientUnits:o.global?"userSpaceOnUse":"objectBoundingBox"};if(ls(o))r="linearGradient",a.x1=o.x,a.y1=o.y,a.x2=o.x2,a.y2=o.y2;else{if(!cs(o))return;r="radialGradient",a.cx=dr(o.x,.5),a.cy=dr(o.y,.5),a.r=dr(o.r,.5)}for(var s=o.colorStops,l=[],c=0,u=s.length;cl?mA(t,null==n[d+1]?null:n[d+1].elm,n,s,d):vA(t,e,a,l))}(n,i,r):hA(r)?(hA(t.text)&&cA(n,""),mA(n,null,r,0,r.length-1)):hA(i)?vA(n,i,0,i.length-1):hA(t.text)&&cA(n,""):t.text!==e.text&&(hA(i)&&vA(n,i,0,i.length-1),cA(n,e.text)))}var bA=0,xA=function(){function t(t,e,n){if(this.type="svg",this.refreshHover=function(){},this.configLayer=function(){},this.storage=e,this._opts=n=Fi({},n),this.root=t,this._id="zr"+bA++,this._oldVNode=AT(n.width,n.height),t&&!n.ssr){var i=this._viewport=document.createElement("div");i.style.cssText="position:relative;overflow:hidden";var r=this._svgDom=this._oldVNode.elm=CT("svg");yA(null,this._oldVNode),i.appendChild(r),t.appendChild(i)}this.resize(n.width,n.height)}return t.prototype.getType=function(){return this.type},t.prototype.getViewportRoot=function(){return this._viewport},t.prototype.getViewportRootOffset=function(){var t=this.getViewportRoot();if(t)return{offsetLeft:t.offsetLeft||0,offsetTop:t.offsetTop||0}},t.prototype.getSvgDom=function(){return this._svgDom},t.prototype.refresh=function(){if(this.root){var t=this.renderToVNode({willUpdate:!0});t.attrs.style="position:absolute;left:0;top:0;user-select:none",function(t,e){if(fA(t,e))_A(t,e);else{var n=t.elm,i=sA(n);gA(e),null!==i&&(rA(i,e.elm,lA(n)),vA(i,[t],0,0))}}(this._oldVNode,t),this._oldVNode=t}},t.prototype.renderOneToVNode=function(t){return JT(t,TT(this._id))},t.prototype.renderToVNode=function(t){t=t||{};var e=this.storage.getDisplayList(!0),n=this._width,i=this._height,r=TT(this._id);r.animation=t.animation,r.willUpdate=t.willUpdate,r.compress=t.compress,r.emphasis=t.emphasis,r.ssr=this._opts.ssr;var o=[],a=this._bgVNode=function(t,e,n,i){var r;if(n&&"none"!==n)if(r=kT("rect","bg",{width:t,height:e,x:"0",y:"0"}),us(n))tA({fill:n},r.attrs,"fill",i);else if(ss(n))eA({style:{fill:n},dirty:Mr,getBoundingRect:function(){return{width:t,height:e}}},r.attrs,"fill",i);else{var o=ts(n),a=o.color,s=o.opacity;r.attrs.fill=a,s<1&&(r.attrs["fill-opacity"]=s)}return r}(n,i,this._backgroundColor,r);a&&o.push(a);var s=t.compress?null:this._mainVNode=kT("g","main",{},[]);this._paintList(e,r,s?s.children:o),s&&o.push(s);var l=Gi(Zi(r.defs),function(t){return r.defs[t]});if(l.length&&o.push(kT("defs","defs",{},l)),t.animation){var c=function(t,e,n){var i=(n=n||{}).newline?"\n":"",r=" {"+i,o=i+"}",a=Gi(Zi(t),function(e){return e+r+Gi(Zi(t[e]),function(n){return n+":"+t[e][n]+";"}).join(i)+o}).join(i),s=Gi(Zi(e),function(t){return"@keyframes "+t+r+Gi(Zi(e[t]),function(n){return n+r+Gi(Zi(e[t][n]),function(i){var r=e[t][n][i];return"d"===i&&(r='path("'+r+'")'),i+":"+r+";"}).join(i)+o}).join(i)+o}).join(i);return a||s?[""].join(i):""}(r.cssNodes,r.cssAnims,{newline:!0});if(c){var u=kT("style","stl",{},[],c);o.push(u)}}return AT(n,i,o,t.useViewBox)},t.prototype.renderToString=function(t){return t=t||{},MT(this.renderToVNode({animation:dr(t.cssAnimation,!0),emphasis:dr(t.cssEmphasis,!0),willUpdate:!1,compress:!0,useViewBox:dr(t.useViewBox,!0)}),{newline:!0})},t.prototype.setBackgroundColor=function(t){this._backgroundColor=t},t.prototype.getSvgRoot=function(){return this._mainVNode&&this._mainVNode.elm},t.prototype._paintList=function(t,e,n){for(var i,r,o=t.length,a=[],s=0,l=0,c=0;c=0&&(!d||!r||d[f]!==r[f]);f--);for(var g=p-1;g>f;g--)i=a[--s-1];for(var m=f+1;m10&&"cartesian2d"===o.type&&r){var s=o.getBaseAxis(),l=o.getOtherAxis(s),c=s.getExtent(),u=n.getDevicePixelRatio(),d=Math.abs(c[1]-c[0])*(u||1),h=Math.round(a/d);if(isFinite(h)&&h>1){"lttb"===r?t.setData(i.lttbDownSample(i.mapDimension(l.dim),1/h)):"minmax"===r&&t.setData(i.minmaxDownSample(i.mapDimension(l.dim),1/h));var p=void 0;er(r)?p=XC[r]:tr(r)&&(p=r),p&&t.setData(i.downSample(i.mapDimension(l.dim),1/h,p,YC))}}}}}("line"))},function(t){VS(cM),VS(VM)},function(t){VS(VM),t.registerComponentModel(WM),t.registerComponentView(aT),t.registerAction({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},Mr),t.registerAction({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},Mr)},function(t){t.registerPainter("svg",xA)}]);class wA extends Nt{constructor(){super(...arguments),this.options=null,this.data=[],this.height="120px",this._chart=null,this._resizeObserver=null}render(){return gt`
`}connectedCallback(){super.connectedCallback(),this.hasUpdated&&!this._chart&&this.options&&(this._mount(),this._observeResize())}firstUpdated(){this._mount(),this._observeResize()}updated(t){(t.has("options")||t.has("data"))&&(this._chart&&this.options?this._chart.setOption(this._mergedOptions(),!0):!this._chart&&this.options&&this._mount()),t.has("height")&&this._chart&&this._chart.resize()}disconnectedCallback(){this._destroy(),super.disconnectedCallback()}_mount(){if(!this.options)return;const t=this.shadowRoot?.querySelector(".chart-host");t&&(this._chart=Yx(t,void 0,{renderer:"svg"}),this._chart.setOption(this._mergedOptions(),!0))}_mergedOptions(){if(!this.options)throw new Error("span-chart: options not set");return{...this.options,series:this.data}}_observeResize(){if("undefined"==typeof ResizeObserver)return;this._resizeObserver=new ResizeObserver(()=>{this._chart&&this._chart.resize()});const t=this.shadowRoot?.querySelector(".chart-host");t&&this._resizeObserver.observe(t)}_destroy(){this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),this._chart&&(this._chart.dispose(),this._chart=null)}}wA.styles=P` +var El={},Nl={};var Rl,Ol=function(){function t(t,e,n){var i=this;this._sleepAfterStill=10,this._stillFrameAccum=0,this._needsRefresh=!0,this._needsRefreshHover=!0,this._darkMode=!1,n=n||{},this.dom=e,this.id=t;var r=new ea,o=n.renderer||"canvas";El[o]||(o=Xi(El)[0]),n.useDirtyRect=null!=n.useDirtyRect&&n.useDirtyRect;var a=new El[o](e,r,n,t),s=n.ssr||a.ssrOnly;this.storage=r,this.painter=a;var l,c=mi.node||mi.worker||s?null:new Gs(a.getViewportRoot(),a.root),u=n.useCoarsePointer;(null==u||"auto"===u?mi.touchEventsSupported:!!u)&&(l=cr(n.pointerSize,44)),this.handler=new $o(r,a,c,a.root,l),this.animation=new Ds({stage:{update:s?null:function(){return i._flush(!0)}}}),s||this.animation.start()}return t.prototype.add=function(t){!this._disposed&&t&&(this.storage.addRoot(t),t.addSelfToZr(this),this.refresh())},t.prototype.remove=function(t){!this._disposed&&t&&(this.storage.delRoot(t),t.removeSelfFromZr(this),this.refresh())},t.prototype.configLayer=function(t,e){this._disposed||(this.painter.configLayer&&this.painter.configLayer(t,e),this.refresh())},t.prototype.setBackgroundColor=function(t){this._disposed||(this.painter.setBackgroundColor&&this.painter.setBackgroundColor(t),this.refresh(),this._backgroundColor=t,this._darkMode=function(t){if(!t)return!1;if("string"==typeof t)return Xa(t,1)<.4;if(t.colorStops){for(var e=t.colorStops,n=0,i=e.length,r=0;r0&&(this._stillFrameAccum++,this._stillFrameAccum>this._sleepAfterStill&&this.animation.stop())},t.prototype.setSleepAfterStill=function(t){this._sleepAfterStill=t},t.prototype.wakeUp=function(){this._disposed||(this.animation.start(),this._stillFrameAccum=0)},t.prototype.refreshHover=function(){this._needsRefreshHover=!0},t.prototype.refreshHoverImmediately=function(){this._disposed||(this._needsRefreshHover=!1,this.painter.refreshHover&&"canvas"===this.painter.getType()&&this.painter.refreshHover())},t.prototype.resize=function(t){this._disposed||(t=t||{},this.painter.resize(t.width,t.height),this.handler.resize())},t.prototype.clearAnimation=function(){this._disposed||this.animation.clear()},t.prototype.getWidth=function(){if(!this._disposed)return this.painter.getWidth()},t.prototype.getHeight=function(){if(!this._disposed)return this.painter.getHeight()},t.prototype.setCursorStyle=function(t){this._disposed||this.handler.setCursorStyle(t)},t.prototype.findHover=function(t,e){if(!this._disposed)return this.handler.findHover(t,e)},t.prototype.on=function(t,e,n){return this._disposed||this.handler.on(t,e,n),this},t.prototype.off=function(t,e){this._disposed||this.handler.off(t,e)},t.prototype.trigger=function(t,e){this._disposed||this.handler.trigger(t,e)},t.prototype.clear=function(){if(!this._disposed){for(var t=this.storage.getRoots(),e=0;e0){if(t<=r)return a;if(t>=o)return s}else{if(t>=r)return a;if(t<=o)return s}else{if(t===r)return a;if(t===o)return s}return(t-r)/l*c+a}var Wl=function(t,e,n){switch(t){case"center":case"middle":t="50%";break;case"left":case"top":t="0%";break;case"right":case"bottom":t="100%"}return jl(t,e,n)};function jl(t,e,n){return Ji(t)?(i=t,i.replace(/^\s+|\s+$/g,"")).match(/%$/)?parseFloat(t)/100*e+(n||0):parseFloat(t):null==t?NaN:+t;var i}function ql(t,e,n){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),t=(+t).toFixed(e),n?t:+t}function Ul(t){if(t=+t,isNaN(t))return 0;if(t>1e-14)for(var e=1,n=0;n<15;n++,e*=10)if(Math.round(t*e)/e===t)return n;return function(t){var e=t.toString().toLowerCase(),n=e.indexOf("e"),i=n>0?+e.slice(n+1):0,r=n>0?n:e.length,o=e.indexOf("."),a=o<0?0:r-1-o;return Math.max(0,a-i)}(t)}function Gl(t,e){var n=Math.max(Ul(t),Ul(e)),i=t+e;return n>20?i:ql(i,n)}function Xl(t){var e=2*Math.PI;return(t%e+e)%e}function Yl(t){return t>-1e-4&&t=10&&e++,e}function Jl(t,e){var n=Ql(t),i=Math.pow(10,n),r=t/i;return t=(r<1.5?1:r<2.5?2:r<4?3:r<7?5:10)*i,n>=-20?+t.toFixed(n<0?-n:0):t}function tc(t){var e=parseFloat(t);return e==t&&(0!==e||!Ji(t)||t.indexOf("x")<=0)?e:NaN}function ec(){return Math.round(9*Math.random())}function nc(t,e){return 0===e?t:nc(e,t%e)}function ic(t,e){return null==t?e:null==e?t:t*e/nc(t,e)}var rc="undefined"!=typeof console&&console.warn&&console.log;function oc(t,e){!function(t,e){rc&&console[t]("[ECharts] "+e)}("error",t)}function ac(t){throw new Error(t)}function sc(t,e,n){return(e-t)*n+t}var lc="series\0";function cc(t){return t instanceof Array?t:null==t?[]:[t]}function uc(t,e,n){if(t){t[e]=t[e]||{},t.emphasis=t.emphasis||{},t.emphasis[e]=t.emphasis[e]||{};for(var i=0,r=n.length;i=0||r&&$i(r,s)<0)){var l=n.getShallow(s,e);null!=l&&(o[t[a][0]]=l)}}return o}}var Hc=zc([["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]]),Bc=function(){function t(){}return t.prototype.getAreaStyle=function(t,e){return Hc(this,t,e)},t}(),Fc=new Da(50);function $c(t){if("string"==typeof t){var e=Fc.get(t);return e&&e.image}return t}function Vc(t,e,n,i,r){if(t){if("string"==typeof t){if(e&&e.__zrImageSrc===t||!n)return e;var o=Fc.get(t),a={hostEl:n,cb:i,cbPayload:r};return o?!jc(e=o.image)&&o.pending.push(a):((e=wi.loadImage(t,Wc,Wc)).__zrImageSrc=t,Fc.put(t,e.__cachedImgObj={image:e,pending:[a]})),e}return t}return e}function Wc(){var t=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var e=0;e=s;c++)l-=s;var u=pl(a,n);return u>l&&(n="",u=0),l=t-u,r.ellipsis=n,r.ellipsisWidth=u,r.contentWidth=l,r.containerWidth=t,r}function Xc(t,e,n){var i=n.containerWidth,r=n.contentWidth,o=n.fontMeasureInfo;if(!i)return t.textLine="",void(t.isTruncated=!1);var a=pl(o,e);if(a<=i)return t.textLine=e,void(t.isTruncated=!1);for(var s=0;;s++){if(a<=r||s>=n.maxIterations){e+=n.ellipsis;break}var l=0===s?Yc(e,r,o):a>0?Math.floor(e.length*r/a):0;a=pl(o,e=e.substr(0,l))}""===e&&(e=n.placeholder),t.textLine=e,t.isTruncated=!0}function Yc(t,e,n){for(var i=0,r=0,o=t.length;r0&&f+i.accumWidth>i.width&&(o=e.split("\n"),d=!0),i.accumWidth=f}else{var g=nu(e,u,i.width,i.breakAll,i.accumWidth);i.accumWidth=g.accumWidth+p,a=g.linesWidths,o=g.lines}}o||(o=e.split("\n"));for(var m=cl(u),v=0;v=32&&e<=591||e>=880&&e<=4351||e>=4608&&e<=5119||e>=7680&&e<=8303}(t)||!!tu[t]}function nu(t,e,n,i,r){for(var o=[],a=[],s="",l="",c=0,u=0,d=cl(e),h=0;hn:r+u+f>n)?u?(s||l)&&(g?(s||(s=l,l="",u=c=0),o.push(s),a.push(u-c),l+=p,s="",u=c+=f):(l&&(s+=l,l="",c=0),o.push(s),a.push(u),s=p,u=f)):g?(o.push(l),a.push(c),l=p,c=f):(o.push(p),a.push(f)):(u+=f,g?(l+=p,c+=f):(l&&(s+=l,l="",c=0),s+=p))}else l&&(s+=l,u+=c),o.push(s),a.push(u),s="",l="",c=0,u=0}return l&&(s+=l),s&&(o.push(s),a.push(u)),1===o.length&&(u+=r),{accumWidth:u,lines:o,linesWidths:a}}function iu(t,e,n,i,r,o){if(t.baseX=n,t.baseY=i,t.outerWidth=t.outerHeight=null,e){var a=2*e.width,s=2*e.height;Do.set(ru,ml(n,a,r),vl(i,s,o),a,s),Do.intersect(e,ru,null,ou);var l=ou.outIntersectRect;t.outerWidth=l.width,t.outerHeight=l.height,t.baseX=ml(l.x,l.width,r,!0),t.baseY=vl(l.y,l.height,o,!0)}}var ru=new Do(0,0,0,0),ou={outIntersectRect:{},clamp:!0};function au(t){return null!=t?t+="":t=""}function su(t,e,n,i){var r=new Do(ml(t.x||0,e,t.textAlign),vl(t.y||0,n,t.textBaseline),e,n),o=null!=i?i:lu(t)?t.lineWidth:0;return o>0&&(r.x-=o/2,r.y-=o/2,r.width+=o,r.height+=o),r}function lu(t){var e=t.stroke;return null!=e&&"none"!==e&&t.lineWidth>0}var cu="__zr_style_"+Math.round(10*Math.random()),uu={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},du={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};uu[cu]=!0;var hu=["z","z2","invisible"],pu=["invisible"],fu=function(t){function e(e){return t.call(this,e)||this}var n;return S(e,t),e.prototype._init=function(e){for(var n=Xi(e),i=0;i1e-4)return s[0]=t-n,s[1]=e-i,l[0]=t+n,void(l[1]=e+i);if(wu[0]=bu(r)*n+t,wu[1]=_u(r)*i+e,Su[0]=bu(o)*n+t,Su[1]=_u(o)*i+e,c(s,wu,Su),u(l,wu,Su),(r%=xu)<0&&(r+=xu),(o%=xu)<0&&(o+=xu),r>o&&!a?o+=xu:rr&&(Cu[0]=bu(p)*n+t,Cu[1]=_u(p)*i+e,c(s,Cu,s),u(l,Cu,l))}var Pu={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},Lu=[],Eu=[],Nu=[],Ru=[],Ou=[],zu=[],Hu=Math.min,Bu=Math.max,Fu=Math.cos,$u=Math.sin,Vu=Math.abs,Wu=Math.PI,ju=2*Wu,qu="undefined"!=typeof Float32Array,Uu=[];function Gu(t){return Math.round(t/Wu*1e8)/1e8%2*Wu}var Xu=function(){function t(t){this.dpr=1,this._xi=0,this._yi=0,this._x0=0,this._y0=0,this._len=0,t&&(this._saveData=!1),this._saveData&&(this.data=[])}var e;return t.prototype.increaseVersion=function(){this._version++},t.prototype.getVersion=function(){return this._version},t.prototype.setScale=function(t,e,n){(n=n||0)>0&&(this._ux=Vu(n/Ys/t)||0,this._uy=Vu(n/Ys/e)||0)},t.prototype.setDPR=function(t){this.dpr=t},t.prototype.setContext=function(t){this._ctx=t},t.prototype.getContext=function(){return this._ctx},t.prototype.beginPath=function(){return this._ctx&&this._ctx.beginPath(),this.reset(),this},t.prototype.reset=function(){this._saveData&&(this._len=0),this._pathSegLen&&(this._pathSegLen=null,this._pathLen=0),this._version++},t.prototype.moveTo=function(t,e){return this._drawPendingPt(),this.addData(Pu.M,t,e),this._ctx&&this._ctx.moveTo(t,e),this._x0=t,this._y0=e,this._xi=t,this._yi=e,this},t.prototype.lineTo=function(t,e){var n=Vu(t-this._xi),i=Vu(e-this._yi),r=n>this._ux||i>this._uy;if(this.addData(Pu.L,t,e),this._ctx&&r&&this._ctx.lineTo(t,e),r)this._xi=t,this._yi=e,this._pendingPtDist=0;else{var o=n*n+i*i;o>this._pendingPtDist&&(this._pendingPtX=t,this._pendingPtY=e,this._pendingPtDist=o)}return this},t.prototype.bezierCurveTo=function(t,e,n,i,r,o){return this._drawPendingPt(),this.addData(Pu.C,t,e,n,i,r,o),this._ctx&&this._ctx.bezierCurveTo(t,e,n,i,r,o),this._xi=r,this._yi=o,this},t.prototype.quadraticCurveTo=function(t,e,n,i){return this._drawPendingPt(),this.addData(Pu.Q,t,e,n,i),this._ctx&&this._ctx.quadraticCurveTo(t,e,n,i),this._xi=n,this._yi=i,this},t.prototype.arc=function(t,e,n,i,r,o){this._drawPendingPt(),Uu[0]=i,Uu[1]=r,function(t,e){var n=Gu(t[0]);n<0&&(n+=ju);var i=n-t[0],r=t[1];r+=i,!e&&r-n>=ju?r=n+ju:e&&n-r>=ju?r=n-ju:!e&&n>r?r=n+(ju-Gu(n-r)):e&&n0&&o))for(var a=0;ac.length&&(this._expandData(),c=this.data);for(var u=0;u0&&(this._ctx&&this._ctx.lineTo(this._pendingPtX,this._pendingPtY),this._pendingPtDist=0)},t.prototype._expandData=function(){if(!(this.data instanceof Array)){for(var t=[],e=0;e11&&(this.data=new Float32Array(t)))}},t.prototype.getBoundingRect=function(){Nu[0]=Nu[1]=Ou[0]=Ou[1]=Number.MAX_VALUE,Ru[0]=Ru[1]=zu[0]=zu[1]=-Number.MAX_VALUE;var t,e=this.data,n=0,i=0,r=0,o=0;for(t=0;tn||Vu(m)>i||d===e-1)&&(f=Math.sqrt(I*I+m*m),r=g,o=_);break;case Pu.C:var v=t[d++],y=t[d++],_=(g=t[d++],t[d++]),b=t[d++],x=t[d++];f=_a(r,o,v,y,g,_,b,x,10),r=b,o=x;break;case Pu.Q:f=Ca(r,o,v=t[d++],y=t[d++],g=t[d++],_=t[d++],10),r=g,o=_;break;case Pu.A:var w=t[d++],S=t[d++],C=t[d++],k=t[d++],M=t[d++],T=t[d++],A=T+M;d+=1,p&&(a=Fu(M)*C+w,s=$u(M)*k+S),f=Bu(C,k)*Hu(ju,Math.abs(T)),r=Fu(A)*C+w,o=$u(A)*k+S;break;case Pu.R:a=r=t[d++],s=o=t[d++],f=2*t[d++]+2*t[d++];break;case Pu.Z:var I=a-r;m=s-o;f=Math.sqrt(I*I+m*m),r=a,o=s}f>=0&&(l[u++]=f,c+=f)}return this._pathLen=c,c},t.prototype.rebuildPath=function(t,e){var n,i,r,o,a,s,l,c,u,d,h=this.data,p=this._ux,f=this._uy,g=this._len,m=e<1,v=0,y=0,_=0;if(!m||(this._pathSegLen||this._calculateLength(),l=this._pathSegLen,c=e*this._pathLen))t:for(var b=0;b0&&(t.lineTo(u,d),_=0),x){case Pu.M:n=r=h[b++],i=o=h[b++],t.moveTo(r,o);break;case Pu.L:a=h[b++],s=h[b++];var S=Vu(a-r),C=Vu(s-o);if(S>p||C>f){if(m){if(v+(X=l[y++])>c){var k=(c-v)/X;t.lineTo(r*(1-k)+a*k,o*(1-k)+s*k);break t}v+=X}t.lineTo(a,s),r=a,o=s,_=0}else{var M=S*S+C*C;M>_&&(u=a,d=s,_=M)}break;case Pu.C:var T=h[b++],A=h[b++],I=h[b++],D=h[b++],P=h[b++],L=h[b++];if(m){if(v+(X=l[y++])>c){ya(r,T,I,P,k=(c-v)/X,Lu),ya(o,A,D,L,k,Eu),t.bezierCurveTo(Lu[1],Eu[1],Lu[2],Eu[2],Lu[3],Eu[3]);break t}v+=X}t.bezierCurveTo(T,A,I,D,P,L),r=P,o=L;break;case Pu.Q:T=h[b++],A=h[b++],I=h[b++],D=h[b++];if(m){if(v+(X=l[y++])>c){Sa(r,T,I,k=(c-v)/X,Lu),Sa(o,A,D,k,Eu),t.quadraticCurveTo(Lu[1],Eu[1],Lu[2],Eu[2]);break t}v+=X}t.quadraticCurveTo(T,A,I,D),r=I,o=D;break;case Pu.A:var E=h[b++],N=h[b++],R=h[b++],O=h[b++],z=h[b++],H=h[b++],B=h[b++],F=!h[b++],$=R>O?R:O,V=Vu(R-O)>.001,W=z+H,j=!1;if(m)v+(X=l[y++])>c&&(W=z+H*(c-v)/X,j=!0),v+=X;if(V&&t.ellipse?t.ellipse(E,N,R,O,B,z,W,F):t.arc(E,N,$,z,W,F),j)break t;w&&(n=Fu(z)*R+E,i=$u(z)*O+N),r=Fu(W)*R+E,o=$u(W)*O+N;break;case Pu.R:n=r=h[b],i=o=h[b+1],a=h[b++],s=h[b++];var q=h[b++],U=h[b++];if(m){if(v+(X=l[y++])>c){var G=c-v;t.moveTo(a,s),t.lineTo(a+Hu(G,q),s),(G-=q)>0&&t.lineTo(a+q,s+Hu(G,U)),(G-=U)>0&&t.lineTo(a+Bu(q-G,0),s+U),(G-=q)>0&&t.lineTo(a,s+Bu(U-G,0));break t}v+=X}t.rect(a,s,q,U);break;case Pu.Z:if(m){var X;if(v+(X=l[y++])>c){k=(c-v)/X;t.lineTo(r*(1-k)+n*k,o*(1-k)+i*k);break t}v+=X}t.closePath(),r=n,o=i}}},t.prototype.clone=function(){var e=new t,n=this.data;return e.data=n.slice?n.slice():Array.prototype.slice.call(n),e._len=this._len,e},t.prototype.canSave=function(){return!!this._saveData},t.CMD=Pu,t.initDefaultProps=((e=t.prototype)._saveData=!0,e._ux=0,e._uy=0,e._pendingPtDist=0,void(e._version=0)),t}();function Yu(t,e,n,i,r,o,a){if(0===r)return!1;var s=r,l=0;if(a>e+s&&a>i+s||at+s&&o>n+s||oe+d&&u>i+d&&u>o+d&&u>s+d||ut+d&&c>n+d&&c>r+d&&c>a+d||c=0&&pe+c&&l>i+c&&l>o+c||lt+c&&s>n+c&&s>r+c||s=0&&gn||u+cr&&(r+=td);var h=Math.atan2(l,s);return h<0&&(h+=td),h>=i&&h<=r||h+td>=i&&h+td<=r}function nd(t,e,n,i,r,o){if(o>e&&o>i||or?s:0}var id=Xu.CMD,rd=2*Math.PI;var od=[-1,-1,-1],ad=[-1,-1];function sd(){var t=ad[0];ad[0]=ad[1],ad[1]=t}function ld(t,e,n,i,r,o,a,s,l,c){if(c>e&&c>i&&c>o&&c>s||c1&&sd(),p=fa(e,i,o,s,ad[0]),h>1&&(f=fa(e,i,o,s,ad[1]))),2===h?me&&s>i&&s>o||s=0&&u<=1&&(r[l++]=u);else{var c=a*a-4*o*s;if(ha(c))(u=-a/(2*o))>=0&&u<=1&&(r[l++]=u);else if(c>0){var u,d=ra(c),h=(-a-d)/(2*o);(u=(-a+d)/(2*o))>=0&&u<=1&&(r[l++]=u),h>=0&&h<=1&&(r[l++]=h)}}return l}(e,i,o,s,od);if(0===l)return 0;var c=wa(e,i,o);if(c>=0&&c<=1){for(var u=0,d=ba(e,i,o,c),h=0;hn||s<-n)return 0;var l=Math.sqrt(n*n-s*s);od[0]=-l,od[1]=l;var c=Math.abs(i-r);if(c<1e-4)return 0;if(c>=rd-1e-4){i=0,r=rd;var u=o?1:-1;return a>=od[0]+t&&a<=od[1]+t?u:0}if(i>r){var d=i;i=r,r=d}i<0&&(i+=rd,r+=rd);for(var h=0,p=0;p<2;p++){var f=od[p];if(f+t>a){var g=Math.atan2(s,f);u=o?1:-1;g<0&&(g=rd+g),(g>=i&&g<=r||g+rd>=i&&g+rd<=r)&&(g>Math.PI/2&&g<1.5*Math.PI&&(u=-u),h+=u)}}return h}function dd(t,e,n,i,r){for(var o,a,s=t.data,l=t.len(),c=0,u=0,d=0,h=0,p=0,f=0;f1&&(n||(c+=nd(u,d,h,p,i,r))),m&&(h=u=s[f],p=d=s[f+1]),g){case id.M:u=h=s[f++],d=p=s[f++];break;case id.L:if(n){if(Yu(u,d,s[f],s[f+1],e,i,r))return!0}else c+=nd(u,d,s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case id.C:if(n){if(Zu(u,d,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=ld(u,d,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case id.Q:if(n){if(Ku(u,d,s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=cd(u,d,s[f++],s[f++],s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case id.A:var v=s[f++],y=s[f++],_=s[f++],b=s[f++],x=s[f++],w=s[f++];f+=1;var S=!!(1-s[f++]);o=Math.cos(x)*_+v,a=Math.sin(x)*b+y,m?(h=o,p=a):c+=nd(u,d,o,a,i,r);var C=(i-v)*b/_+v;if(n){if(ed(v,y,b,x,x+w,S,e,C,r))return!0}else c+=ud(v,y,b,x,x+w,S,C,r);u=Math.cos(x+w)*_+v,d=Math.sin(x+w)*b+y;break;case id.R:if(h=u=s[f++],p=d=s[f++],o=h+s[f++],a=p+s[f++],n){if(Yu(h,p,o,p,e,i,r)||Yu(o,p,o,a,e,i,r)||Yu(o,a,h,a,e,i,r)||Yu(h,a,h,p,e,i,r))return!0}else c+=nd(o,p,o,a,i,r),c+=nd(h,a,h,p,i,r);break;case id.Z:if(n){if(Yu(u,d,h,p,e,i,r))return!0}else c+=nd(u,d,h,p,i,r);u=h,d=p}}return n||function(t,e){return Math.abs(t-e)<1e-4}(d,p)||(c+=nd(u,d,h,p,i,r)||0),0!==c}var hd=Fi({fill:"#000",stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:"butt",miterLimit:10,strokeNoScale:!1,strokeFirst:!1},uu),pd={style:Fi({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},du.style)},fd=sl.concat(["invisible","culling","z","z2","zlevel","parent"]),gd=function(t){function e(e){return t.call(this,e)||this}var n;return S(e,t),e.prototype.update=function(){var n=this;t.prototype.update.call(this);var i=this.style;if(i.decal){var r=this._decalEl=this._decalEl||new e;r.buildPath===e.prototype.buildPath&&(r.buildPath=function(t){n.buildPath(t,n.shape)}),r.silent=!0;var o=r.style;for(var a in i)o[a]!==i[a]&&(o[a]=i[a]);o.fill=i.fill?i.decal:null,o.decal=null,o.shadowColor=null,i.strokeFirst&&(o.stroke=null);for(var s=0;s.5?Zs:e>.2?"#eee":Ks}if(t)return Ks}return Zs},e.prototype.getInsideTextStroke=function(t){var e=this.style.fill;if(Ji(e)){var n=this.__zr;if(!(!n||!n.isDarkMode())===Xa(t,0)<.4)return e}},e.prototype.buildPath=function(t,e,n){},e.prototype.pathUpdated=function(){this.__dirty&=-5},e.prototype.getUpdatedPathProxy=function(t){return!this.path&&this.createPathProxy(),this.path.beginPath(),this.buildPath(this.path,this.shape,t),this.path},e.prototype.createPathProxy=function(){this.path=new Xu(!1)},e.prototype.hasStroke=function(){var t=this.style,e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))},e.prototype.hasFill=function(){var t=this.style.fill;return null!=t&&"none"!==t},e.prototype.getBoundingRect=function(){var t=this._rect,e=this.style,n=!t;if(n){var i=!1;this.path||(i=!0,this.createPathProxy());var r=this.path;(i||4&this.__dirty)&&(r.beginPath(),this.buildPath(r,this.shape,!1),this.pathUpdated()),t=r.getBoundingRect()}if(this._rect=t,this.hasStroke()&&this.path&&this.path.len()>0){var o=this._rectStroke||(this._rectStroke=t.clone());if(this.__dirty||n){o.copy(t);var a=e.strokeNoScale?this.getLineScale():1,s=e.lineWidth;if(!this.hasFill()){var l=this.strokeContainThreshold;s=Math.max(s,null==l?4:l)}a>1e-10&&(o.width+=s/a,o.height+=s/a,o.x-=s/a/2,o.y-=s/a/2)}return o}return t},e.prototype.contain=function(t,e){var n=this.transformCoordToLocal(t,e),i=this.getBoundingRect(),r=this.style;if(t=n[0],e=n[1],i.contain(t,e)){var o=this.path;if(this.hasStroke()){var a=r.lineWidth,s=r.strokeNoScale?this.getLineScale():1;if(s>1e-10&&(this.hasFill()||(a=Math.max(a,this.strokeContainThreshold)),function(t,e,n,i){return dd(t,e,!0,n,i)}(o,a/s,t,e)))return!0}if(this.hasFill())return function(t,e,n){return dd(t,0,!1,e,n)}(o,t,e)}return!1},e.prototype.dirtyShape=function(){this.__dirty|=4,this._rect&&(this._rect=null),this._decalEl&&this._decalEl.dirtyShape(),this.markRedraw()},e.prototype.dirty=function(){this.dirtyStyle(),this.dirtyShape()},e.prototype.animateShape=function(t){return this.animate("shape",t)},e.prototype.updateDuringAnimation=function(t){"style"===t?this.dirtyStyle():"shape"===t?this.dirtyShape():this.markRedraw()},e.prototype.attrKV=function(e,n){"shape"===e?this.setShape(n):t.prototype.attrKV.call(this,e,n)},e.prototype.setShape=function(t,e){var n=this.shape;return n||(n=this.shape={}),"string"==typeof t?n[t]=e:Bi(n,t),this.dirtyShape(),this},e.prototype.shapeChanged=function(){return!!(4&this.__dirty)},e.prototype.createStyle=function(t){return wr(hd,t)},e.prototype._innerSaveToNormal=function(e){t.prototype._innerSaveToNormal.call(this,e);var n=this._normalState;e.shape&&!n.shape&&(n.shape=Bi({},this.shape))},e.prototype._applyStateObj=function(e,n,i,r,o,a){t.prototype._applyStateObj.call(this,e,n,i,r,o,a);var s,l=!(n&&r);if(n&&n.shape?o?r?s=n.shape:(s=Bi({},i.shape),Bi(s,n.shape)):(s=Bi({},r?this.shape:i.shape),Bi(s,n.shape)):l&&(s=i.shape),s)if(o){this.shape=Bi({},this.shape);for(var c={},u=Xi(s),d=0;dc&&(n*=c/(a=n+i),i*=c/a),r+o>c&&(r*=c/(a=r+o),o*=c/a),i+r>u&&(i*=u/(a=i+r),r*=u/a),n+o>u&&(n*=u/(a=n+o),o*=u/a),t.moveTo(s+n,l),t.lineTo(s+c-i,l),0!==i&&t.arc(s+c-i,l+i,i,-Math.PI/2,0),t.lineTo(s+c,l+u-r),0!==r&&t.arc(s+c-r,l+u-r,r,0,Math.PI/2),t.lineTo(s+o,l+u),0!==o&&t.arc(s+o,l+u-o,o,Math.PI/2,Math.PI),t.lineTo(s,l+n),0!==n&&t.arc(s+n,l+n,n,Math.PI,1.5*Math.PI)}(t,e):t.rect(n,i,r,o)},e.prototype.isZeroArea=function(){return!this.shape.width||!this.shape.height},e}(gd);Td.prototype.type="rect";var Ad={fill:"#000"},Id={},Dd={style:Fi({fill:!0,stroke:!0,fillOpacity:!0,strokeOpacity:!0,lineWidth:!0,fontSize:!0,lineHeight:!0,width:!0,height:!0,textShadowColor:!0,textShadowBlur:!0,textShadowOffsetX:!0,textShadowOffsetY:!0,backgroundColor:!0,padding:!0,borderColor:!0,borderWidth:!0,borderRadius:!0},du.style)},Pd=function(t){function e(e){var n=t.call(this)||this;return n.type="text",n._children=[],n._defaultStyle=Ad,n.attr(e),n}return S(e,t),e.prototype.childrenRef=function(){return this._children},e.prototype.update=function(){t.prototype.update.call(this),this.styleChanged()&&this._updateSubTexts();for(var e=0;ev&&p){var _=Math.floor(v/h);f=f||m.length>_,y=(m=m.slice(0,_)).length*h}if(r&&u&&null!=g)for(var b=Gc(g,c,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),x={},w=0;w0,k=0;kg&&Jc(o,a.substring(g,m),e,f),Jc(o,h[2],e,f,h[1]),g=qc.lastIndex}gd){var N=o.lines.length;A>0?(k.tokens=k.tokens.slice(0,A),S(k,T,M),o.lines=o.lines.slice(0,C+1)):o.lines=o.lines.slice(0,C),o.isTruncated=o.isTruncated||o.lines.length=0&&"right"===(T=_[M]).align;)this._placeToken(T,t,x,f,k,"right",m),w-=T.width,k-=T.width,M--;for(C+=(s-(C-p)-(g-k)-w)/2;S<=M;)T=_[S],this._placeToken(T,t,x,f,C+T.width/2,"center",m),C+=T.width,S++;f+=x}},e.prototype._placeToken=function(t,e,n,i,r,o,a){var s=e.rich[t.styleName]||{};s.text=t.text;var l=t.verticalAlign,c=i+n/2;"top"===l?c=i+t.height/2:"bottom"===l&&(c=i+n-t.height/2),!t.isLineHolder&&Wd(s)&&this._renderBackground(s,e,"right"===o?r-t.width:"center"===o?r-t.width/2:r,c-t.height/2,t.width,t.height);var u=!!s.backgroundColor,d=t.textPadding;d&&(r=$d(r,o,d),c-=t.height/2-d[0]-t.innerHeight/2);var h=this._getOrCreateChild(vd),p=h.createStyle();h.useStyle(p);var f=this._defaultStyle,g=!1,m=0,v=!1,y=Fd("fill"in s?s.fill:"fill"in e?e.fill:(g=!0,f.fill)),_=Bd("stroke"in s?s.stroke:"stroke"in e?e.stroke:u||a||f.autoStroke&&!g?null:(m=2,v=!0,f.stroke)),b=s.textShadowBlur>0||e.textShadowBlur>0;p.text=t.text,p.x=r,p.y=c,b&&(p.shadowBlur=s.textShadowBlur||e.textShadowBlur||0,p.shadowColor=s.textShadowColor||e.textShadowColor||"transparent",p.shadowOffsetX=s.textShadowOffsetX||e.textShadowOffsetX||0,p.shadowOffsetY=s.textShadowOffsetY||e.textShadowOffsetY||0),p.textAlign=o,p.textBaseline="middle",p.font=t.font||yi,p.opacity=ur(s.opacity,e.opacity,1),Od(p,s),_&&(p.lineWidth=ur(s.lineWidth,e.lineWidth,m),p.lineDash=cr(s.lineDash,e.lineDash),p.lineDashOffset=e.lineDashOffset||0,p.stroke=_),y&&(p.fill=y),h.setBoundingRect(su(p,t.contentWidth,t.contentHeight,v?0:null))},e.prototype._renderBackground=function(t,e,n,i,r,o){var a,s,l,c=t.backgroundColor,u=t.borderWidth,d=t.borderColor,h=c&&c.image,p=c&&!h,f=t.borderRadius,g=this;if(p||t.lineHeight||u&&d){(a=this._getOrCreateChild(Td)).useStyle(a.createStyle()),a.style.fill=null;var m=a.shape;m.x=n,m.y=i,m.width=r,m.height=o,m.r=f,a.dirtyShape()}if(p)(l=a.style).fill=c||null,l.fillOpacity=cr(t.fillOpacity,1);else if(h){(s=this._getOrCreateChild(bd)).onload=function(){g.dirtyStyle()};var v=s.style;v.image=c.image,v.x=n,v.y=i,v.width=r,v.height=o}u&&d&&((l=a.style).lineWidth=u,l.stroke=d,l.strokeOpacity=cr(t.strokeOpacity,1),l.lineDash=t.borderDash,l.lineDashOffset=t.borderDashOffset||0,a.strokeContainThreshold=0,a.hasFill()&&a.hasStroke()&&(l.strokeFirst=!0,l.lineWidth*=2));var y=(a||s).style;y.shadowBlur=t.shadowBlur||0,y.shadowColor=t.shadowColor||"transparent",y.shadowOffsetX=t.shadowOffsetX||0,y.shadowOffsetY=t.shadowOffsetY||0,y.opacity=ur(t.opacity,e.opacity,1)},e.makeFont=function(t){var e="";return zd(t)&&(e=[t.fontStyle,t.fontWeight,Rd(t.fontSize),t.fontFamily||"sans-serif"].join(" ")),e&&fr(e)||t.textFont||t.font},e}(fu),Ld={left:!0,right:1,center:1},Ed={top:1,bottom:1,middle:1},Nd=["fontStyle","fontWeight","fontSize","fontFamily"];function Rd(t){return"string"!=typeof t||-1===t.indexOf("px")&&-1===t.indexOf("rem")&&-1===t.indexOf("em")?isNaN(+t)?"12px":t+"px":t}function Od(t,e){for(var n=0;n=0,o=!1;if(t instanceof gd){var a=Gd(t),s=r&&a.selectFill||a.normalFill,l=r&&a.selectStroke||a.normalStroke;if(ih(s)||ih(l)){var c=(i=i||{}).style||{};"inherit"===c.fill?(o=!0,i=Bi({},i),(c=Bi({},c)).fill=s):!ih(c.fill)&&ih(s)?(o=!0,i=Bi({},i),(c=Bi({},c)).fill=Za(s)):!ih(c.stroke)&&ih(l)&&(o||(i=Bi({},i),c=Bi({},c)),c.stroke=Za(l)),i.style=c}}if(i&&null==i.z2){o||(i=Bi({},i));var u=t.z2EmphasisLift;i.z2=t.z2+(null!=u?u:10)}return i}(this,0,e,n);if("blur"===t)return function(t,e,n){var i=$i(t.currentStates,e)>=0,r=t.style.opacity,o=i?null:function(t,e,n,i){for(var r=t.style,o={},a=0;a0){var o={dataIndex:r,seriesIndex:t.seriesIndex};null!=i&&(o.dataType=i),e.push(o)}})}),e}function Dh(t,e,n){Rh(t,!0),hh(t,gh),function(t,e,n){var i=jd(t);null!=e?(i.focus=e,i.blurScope=n):i.focus&&(i.focus=null)}(t,e,n)}function Ph(t,e,n,i){i?function(t){Rh(t,!1)}(t):Dh(t,e,n)}var Lh=["emphasis","blur","select"],Eh={itemStyle:"getItemStyle",lineStyle:"getLineStyle",areaStyle:"getAreaStyle"};function Nh(t,e,n,i){n=n||"itemStyle";for(var r=0;r1&&(a*=Wh(f),s*=Wh(f));var g=(r===o?-1:1)*Wh((a*a*(s*s)-a*a*(p*p)-s*s*(h*h))/(a*a*(p*p)+s*s*(h*h)))||0,m=g*a*p/s,v=g*-s*h/a,y=(t+n)/2+qh(d)*m-jh(d)*v,_=(e+i)/2+jh(d)*m+qh(d)*v,b=Yh([1,0],[(h-m)/a,(p-v)/s]),x=[(h-m)/a,(p-v)/s],w=[(-1*h-m)/a,(-1*p-v)/s],S=Yh(x,w);if(Xh(x,w)<=-1&&(S=Uh),Xh(x,w)>=1&&(S=0),S<0){var C=Math.round(S/Uh*1e6)/1e6;S=2*Uh+C%2*Uh}u.addData(c,y,_,a,s,b,S,d,o)}var Kh=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,Qh=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;var Jh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e.prototype.applyTransform=function(t){},e}(gd);function tp(t){return null!=t.setData}function ep(t,e){var n=function(t){var e=new Xu;if(!t)return e;var n,i=0,r=0,o=i,a=r,s=Xu.CMD,l=t.match(Kh);if(!l)return e;for(var c=0;cD*D+P*P&&(C=M,k=T),{cx:C,cy:k,x0:-u,y0:-d,x1:C*(r/x-1),y1:k*(r/x-1)}}function yp(t,e){var n,i=fp(e.r,0),r=fp(e.r0||0,0),o=i>0;if(o||r>0){if(o||(i=r,r=0),r>i){var a=i;i=r,r=a}var s=e.startAngle,l=e.endAngle;if(!isNaN(s)&&!isNaN(l)){var c=e.cx,u=e.cy,d=!!e.clockwise,h=hp(l-s),p=h>sp&&h%sp;if(p>mp&&(h=p),i>mp)if(h>sp-mp)t.moveTo(c+i*cp(s),u+i*lp(s)),t.arc(c,u,i,s,l,!d),r>mp&&(t.moveTo(c+r*cp(l),u+r*lp(l)),t.arc(c,u,r,l,s,d));else{var f=void 0,g=void 0,m=void 0,v=void 0,y=void 0,_=void 0,b=void 0,x=void 0,w=void 0,S=void 0,C=void 0,k=void 0,M=void 0,T=void 0,A=void 0,I=void 0,D=i*cp(s),P=i*lp(s),L=r*cp(l),E=r*lp(l),N=h>mp;if(N){var R=e.cornerRadius;R&&(n=function(t){var e;if(Ki(t)){var n=t.length;if(!n)return t;e=1===n?[t[0],t[0],0,0]:2===n?[t[0],t[0],t[1],t[1]]:3===n?t.concat(t[2]):t}else e=[t,t,t,t];return e}(R),f=n[0],g=n[1],m=n[2],v=n[3]);var O=hp(i-r)/2;if(y=gp(O,m),_=gp(O,v),b=gp(O,f),x=gp(O,g),C=w=fp(y,_),k=S=fp(b,x),(w>mp||S>mp)&&(M=i*cp(l),T=i*lp(l),A=r*cp(s),I=r*lp(s),hmp){var j=gp(m,C),q=gp(v,C),U=vp(A,I,D,P,i,j,d),G=vp(M,T,L,E,i,q,d);t.moveTo(c+U.cx+U.x0,u+U.cy+U.y0),C0&&t.arc(c+U.cx,u+U.cy,j,dp(U.y0,U.x0),dp(U.y1,U.x1),!d),t.arc(c,u,i,dp(U.cy+U.y1,U.cx+U.x1),dp(G.cy+G.y1,G.cx+G.x1),!d),q>0&&t.arc(c+G.cx,u+G.cy,q,dp(G.y1,G.x1),dp(G.y0,G.x0),!d))}else t.moveTo(c+D,u+P),t.arc(c,u,i,s,l,!d);else t.moveTo(c+D,u+P);if(r>mp&&N)if(k>mp){j=gp(f,k),U=vp(L,E,M,T,r,-(q=gp(g,k)),d),G=vp(D,P,A,I,r,-j,d);t.lineTo(c+U.cx+U.x0,u+U.cy+U.y0),k0&&t.arc(c+U.cx,u+U.cy,q,dp(U.y0,U.x0),dp(U.y1,U.x1),!d),t.arc(c,u,r,dp(U.cy+U.y1,U.cx+U.x1),dp(G.cy+G.y1,G.cx+G.x1),d),j>0&&t.arc(c+G.cx,u+G.cy,j,dp(G.y1,G.x1),dp(G.y0,G.x0),!d))}else t.lineTo(c+L,u+E),t.arc(c,u,r,l,s,d);else t.lineTo(c+L,u+E)}else t.moveTo(c,u);t.closePath()}}}var _p=function(){this.cx=0,this.cy=0,this.r0=0,this.r=0,this.startAngle=0,this.endAngle=2*Math.PI,this.clockwise=!0,this.cornerRadius=0},bp=function(t){function e(e){return t.call(this,e)||this}return S(e,t),e.prototype.getDefaultShape=function(){return new _p},e.prototype.buildPath=function(t,e){yp(t,e)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(gd);bp.prototype.type="sector";var xp=function(){this.cx=0,this.cy=0,this.r=0,this.r0=0},wp=function(t){function e(e){return t.call(this,e)||this}return S(e,t),e.prototype.getDefaultShape=function(){return new xp},e.prototype.buildPath=function(t,e){var n=e.cx,i=e.cy,r=2*Math.PI;t.moveTo(n+e.r,i),t.arc(n,i,e.r,0,r,!1),t.moveTo(n+e.r0,i),t.arc(n,i,e.r0,0,r,!0)},e}(gd);function Sp(t,e,n){var i=e.smooth,r=e.points;if(r&&r.length>=2){if(i){var o=function(t,e,n,i){var r,o,a,s,l=[],c=[],u=[],d=[];if(i){a=[1/0,1/0],s=[-1/0,-1/0];for(var h=0,p=t.length;hqp[1]){if(r=!1,Up.negativeSize||n)return r;var s=Wp(qp[0]-jp[1]),l=Wp(jp[0]-qp[1]);$p(s,l)>Xp.len()&&(s=l||!Up.bidirectional)&&(mo.scale(Gp,a,-l*i),Up.useDir&&Up.calcDirMTV()))}}return r},t.prototype._getProjMinMaxOnAxis=function(t,e,n){for(var i=this._axes[t],r=this._origin,o=e[0].dot(i)+r[t],a=o,s=o,l=1;l0){var d={duration:u.duration,delay:u.delay||0,easing:u.easing,done:o,force:!!o||!!a,setToFinal:!c,scope:t,during:a};l?e.animateFrom(n,d):e.animateTo(n,d)}else e.stopAnimation(),!l&&e.attr(n),a&&a(1),o&&o()}function tf(t,e,n,i,r,o){Jp("update",t,e,n,i,r,o)}function ef(t,e,n,i,r,o){Jp("enter",t,e,n,i,r,o)}function nf(t){if(!t.__zr)return!0;for(var e=0;e=-1e-6)return!1;var f=t-r,g=e-o,m=Sf(f,g,c,u)/p;if(m<0||m>1)return!1;var v=Sf(f,g,d,h)/p;return!(v<0||v>1)}function Sf(t,e,n,i){return t*i-n*e}function Cf(t,e,n,i,r){return null==e||(er(e)?kf[0]=kf[1]=kf[2]=kf[3]=e:(kf[0]=e[0],kf[1]=e[1],kf[2]=e[2],kf[3]=e[3]),i&&(kf[0]=Fl(0,kf[0]),kf[1]=Fl(0,kf[1]),kf[2]=Fl(0,kf[2]),kf[3]=Fl(0,kf[3])),n&&(kf[0]=-kf[0],kf[1]=-kf[1],kf[2]=-kf[2],kf[3]=-kf[3]),Mf(t,kf,"x","width",3,1,r&&r[0]||0),Mf(t,kf,"y","height",0,2,r&&r[1]||0)),t}var kf=[0,0,0,0];function Mf(t,e,n,i,r,o,a){var s=e[o]+e[r],l=t[i];t[i]+=s,a=Fl(0,Bl(a,l)),t[i]=0?-e[r]:e[o]>=0?l+e[o]:$l(s)>1e-8?(l-a)*e[r]/s:0):t[n]-=e[r]}function Tf(t){var e=t.itemTooltipOption,n=t.componentModel,i=t.itemName,r=Ji(e)?{formatter:e}:e,o=n.mainType,a=n.componentIndex,s={componentType:o,name:i,$vars:["name"]};s[o+"Index"]=a;var l=t.formatterParamsExtra;l&&ji(Xi(l),function(t){Sr(s,t)||(s[t]=l[t],s.$vars.push(t))});var c=jd(t.el);c.componentMainType=o,c.componentIndex=a,c.tooltipConfig={name:i,option:Fi({content:i,encodeHTMLContent:!0,formatterParams:s},r)}}function Af(t,e){var n;t.isGroup&&(n=e(t)),n||t.traverse(e)}function If(t,e){if(t)if(Ki(t))for(var n=0;ne&&(e=i),ie&&(n=e=0),{min:n,max:e}},clipPointsByRect:function(t,e){return qi(t,function(t){var n=t[0];n=Fl(n,e.x),n=Bl(n,e.x+e.width);var i=t[1];return i=Fl(i,e.y),[n,i=Bl(i,e.y+e.height)]})},clipRectByRect:function(t,e){var n=Fl(t.x,e.x),i=Bl(t.x+t.width,e.x+e.width),r=Fl(t.y,e.y),o=Bl(t.y+t.height,e.y+e.height);if(i>=n&&o>=r)return{x:n,y:r,width:i-n,height:o-r}},createIcon:xf,ensureCopyRect:Lf,ensureCopyTransform:Ef,expandOrShrinkRect:Cf,extendPath:function(t,e){return cf(t,e)},extendShape:function(t){return gd.extend(t)},getShapeClass:function(t){if(af.hasOwnProperty(t))return af[t]},getTransform:function(t,e){for(var n=co([]);t&&t!==e;)ho(n,t.getLocalTransform(),n),t=t.parent;return n},groupTransition:bf,initProps:ef,isBoundingRectAxisAligned:Df,isElementRemoved:nf,lineLineIntersect:wf,linePolygonIntersect:function(t,e,n,i,r){for(var o=0,a=r[r.length-1];o$l(o[1])?o[0]>0?"right":"left":o[1]>0?"bottom":"top"},traverseElements:If,traverseUpdateZ:Rf,updateProps:tf}),Hf={};function Bf(t,e,n){var i,r=t.labelFetcher,o=t.labelDataIndex,a=t.labelDimIndex,s=e.normal;r&&(i=r.getFormattedLabel(o,"normal",null,a,s&&s.get("formatter"),null!=n?{interpolatedValue:n}:null)),null==i&&(i=Qi(t.defaultText)?t.defaultText(o,t,n):t.defaultText);for(var l={normal:i},c=0;c-1?dg:pg;function vg(t,e){t=t.toUpperCase(),gg[t]=new lg(e),fg[t]=e}vg(hg,{time:{month:["January","February","March","April","May","June","July","August","September","October","November","December"],monthAbbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayOfWeekAbbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},legend:{selector:{all:"All",inverse:"Inv"}},toolbox:{brush:{title:{rect:"Box Select",polygon:"Lasso Select",lineX:"Horizontally Select",lineY:"Vertically Select",keep:"Keep Selections",clear:"Clear Selections"}},dataView:{title:"Data View",lang:["Data View","Close","Refresh"]},dataZoom:{title:{zoom:"Zoom",back:"Zoom Reset"}},magicType:{title:{line:"Switch to Line Chart",bar:"Switch to Bar Chart",stack:"Stack",tiled:"Tile"}},restore:{title:"Restore"},saveAsImage:{title:"Save as Image",lang:["Right Click to Save Image"]}},series:{typeNames:{pie:"Pie chart",bar:"Bar chart",line:"Line chart",scatter:"Scatter plot",effectScatter:"Ripple scatter plot",radar:"Radar chart",tree:"Tree",treemap:"Treemap",boxplot:"Boxplot",candlestick:"Candlestick",k:"K line chart",heatmap:"Heat map",map:"Map",parallel:"Parallel coordinate map",lines:"Line graph",graph:"Relationship graph",sankey:"Sankey diagram",funnel:"Funnel chart",gauge:"Gauge",pictorialBar:"Pictorial bar",themeRiver:"Theme River Map",sunburst:"Sunburst",custom:"Custom chart",chart:"Chart"}},aria:{general:{withTitle:'This is a chart about "{title}"',withoutTitle:"This is a chart"},series:{single:{prefix:"",withName:" with type {seriesType} named {seriesName}.",withoutName:" with type {seriesType}."},multiple:{prefix:". It consists of {seriesCount} series count.",withName:" The {seriesId} series is a {seriesType} representing {seriesName}.",withoutName:" The {seriesId} series is a {seriesType}.",separator:{middle:"",end:""}}},data:{allData:"The data is as follows: ",partialData:"The first {displayCnt} items are: ",withName:"the data for {name} is {value}",withoutName:"{value}",separator:{middle:", ",end:". "}}}}),vg(dg,{time:{month:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],monthAbbr:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],dayOfWeek:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],dayOfWeekAbbr:["日","一","二","三","四","五","六"]},legend:{selector:{all:"全选",inverse:"反选"}},toolbox:{brush:{title:{rect:"矩形选择",polygon:"圈选",lineX:"横向选择",lineY:"纵向选择",keep:"保持选择",clear:"清除选择"}},dataView:{title:"数据视图",lang:["数据视图","关闭","刷新"]},dataZoom:{title:{zoom:"区域缩放",back:"区域缩放还原"}},magicType:{title:{line:"切换为折线图",bar:"切换为柱状图",stack:"切换为堆叠",tiled:"切换为平铺"}},restore:{title:"还原"},saveAsImage:{title:"保存为图片",lang:["右键另存为图片"]}},series:{typeNames:{pie:"饼图",bar:"柱状图",line:"折线图",scatter:"散点图",effectScatter:"涟漪散点图",radar:"雷达图",tree:"树图",treemap:"矩形树图",boxplot:"箱型图",candlestick:"K线图",k:"K线图",heatmap:"热力图",map:"地图",parallel:"平行坐标图",lines:"线图",graph:"关系图",sankey:"桑基图",funnel:"漏斗图",gauge:"仪表盘图",pictorialBar:"象形柱图",themeRiver:"主题河流图",sunburst:"旭日图",custom:"自定义图表",chart:"图表"}},aria:{general:{withTitle:"这是一个关于“{title}”的图表。",withoutTitle:"这是一个图表,"},series:{single:{prefix:"",withName:"图表类型是{seriesType},表示{seriesName}。",withoutName:"图表类型是{seriesType}。"},multiple:{prefix:"它由{seriesCount}个图表系列组成。",withName:"第{seriesId}个系列是一个表示{seriesName}的{seriesType},",withoutName:"第{seriesId}个系列是一个{seriesType},",separator:{middle:";",end:"。"}}},data:{allData:"其数据是——",partialData:"其中,前{displayCnt}项是——",withName:"{name}的数据是{value}",withoutName:"{value}",separator:{middle:",",end:""}}}});function yg(){return null}var _g=1e3,bg=6e4,xg=36e5,wg=864e5,Sg=31536e6,Cg={year:/({yyyy}|{yy})/,month:/({MMMM}|{MMM}|{MM}|{M})/,day:/({dd}|{d})/,hour:/({HH}|{H}|{hh}|{h})/,minute:/({mm}|{m})/,second:/({ss}|{s})/,millisecond:/({SSS}|{S})/},kg={year:"{yyyy}",month:"{MMM}",day:"{d}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{HH}:{mm}:{ss} {SSS}"},Mg="{yyyy}-{MM}-{dd}",Tg={year:"{yyyy}",month:"{yyyy}-{MM}",day:Mg,hour:Mg+" "+kg.hour,minute:Mg+" "+kg.minute,second:Mg+" "+kg.second,millisecond:"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}"},Ag=["year","month","day","hour","minute","second","millisecond"],Ig=["year","half-year","quarter","month","week","half-week","day","half-day","quarter-day","hour","minute","second","millisecond"];function Dg(t){return Ji(t)||Qi(t)?t:function(t){t=t||{};var e={},n=!0;return ji(Ag,function(e){n&&(n=null==t[e])}),ji(Ag,function(i,r){var o=t[i];e[i]={};for(var a=null,s=r;s>=0;s--){var l=Ag[s],c=nr(o)&&!Ki(o)?o[l]:o,u=void 0;Ki(c)?a=(u=c.slice())[0]||"":Ji(c)?u=[a=c]:(null==a?a=kg[i]:Cg[l].test(a)||(a=e[l][l][0]+" "+a),u=[a],n&&(u[1]="{primary|"+a+"}")),e[i][l]=u}}),e}(t)}function Pg(t,e){return"0000".substr(0,e-(t+="").length)+t}function Lg(t){switch(t){case"half-year":case"quarter":return"month";case"week":case"half-week":return"day";case"half-day":case"quarter-day":return"hour";default:return t}}function Eg(t){return t===Lg(t)}function Ng(t,e,n,i){var r=Kl(t),o=r[zg(n)](),a=r[Hg(n)]()+1,s=Math.floor((a-1)/3)+1,l=r[Bg(n)](),c=r["get"+(n?"UTC":"")+"Day"](),u=r[Fg(n)](),d=(u-1)%12+1,h=r[$g(n)](),p=r[Vg(n)](),f=r[Wg(n)](),g=u>=12?"pm":"am",m=g.toUpperCase(),v=i instanceof lg?i:function(t){return gg[t]}(i||mg)||gg[pg],y=v.getModel("time"),_=y.get("month"),b=y.get("monthAbbr"),x=y.get("dayOfWeek"),w=y.get("dayOfWeekAbbr");return(e||"").replace(/{a}/g,g+"").replace(/{A}/g,m+"").replace(/{yyyy}/g,o+"").replace(/{yy}/g,Pg(o%100+"",2)).replace(/{Q}/g,s+"").replace(/{MMMM}/g,_[a-1]).replace(/{MMM}/g,b[a-1]).replace(/{MM}/g,Pg(a,2)).replace(/{M}/g,a+"").replace(/{dd}/g,Pg(l,2)).replace(/{d}/g,l+"").replace(/{eeee}/g,x[c]).replace(/{ee}/g,w[c]).replace(/{e}/g,c+"").replace(/{HH}/g,Pg(u,2)).replace(/{H}/g,u+"").replace(/{hh}/g,Pg(d+"",2)).replace(/{h}/g,d+"").replace(/{mm}/g,Pg(h,2)).replace(/{m}/g,h+"").replace(/{ss}/g,Pg(p,2)).replace(/{s}/g,p+"").replace(/{SSS}/g,Pg(f,3)).replace(/{S}/g,f+"")}function Rg(t,e){var n=Kl(t),i=n[Hg(e)]()+1,r=n[Bg(e)](),o=n[Fg(e)](),a=n[$g(e)](),s=n[Vg(e)](),l=0===n[Wg(e)](),c=l&&0===s,u=c&&0===a,d=u&&0===o,h=d&&1===r;return h&&1===i?"year":h?"month":d?"day":u?"hour":c?"minute":l?"second":"millisecond"}function Og(t,e,n){switch(e){case"year":t[qg(n)](0);case"month":t[Ug(n)](1);case"day":t[Gg(n)](0);case"hour":t[Xg(n)](0);case"minute":t[Yg(n)](0);case"second":t[Zg(n)](0)}return t}function zg(t){return t?"getUTCFullYear":"getFullYear"}function Hg(t){return t?"getUTCMonth":"getMonth"}function Bg(t){return t?"getUTCDate":"getDate"}function Fg(t){return t?"getUTCHours":"getHours"}function $g(t){return t?"getUTCMinutes":"getMinutes"}function Vg(t){return t?"getUTCSeconds":"getSeconds"}function Wg(t){return t?"getUTCMilliseconds":"getMilliseconds"}function jg(t){return t?"setUTCFullYear":"setFullYear"}function qg(t){return t?"setUTCMonth":"setMonth"}function Ug(t){return t?"setUTCDate":"setDate"}function Gg(t){return t?"setUTCHours":"setHours"}function Xg(t){return t?"setUTCMinutes":"setMinutes"}function Yg(t){return t?"setUTCSeconds":"setSeconds"}function Zg(t){return t?"setUTCMilliseconds":"setMilliseconds"}function Kg(t){if(isNaN(tc(t)))return Ji(t)?t:"-";var e=(t+"").split(".");return e[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(e.length>1?"."+e[1]:"")}function Qg(t,e){return t=(t||"").toLowerCase().replace(/-(.)/g,function(t,e){return e.toUpperCase()}),e&&t&&(t=t.charAt(0).toUpperCase()+t.slice(1)),t}var Jg=hr;function tm(t,e,n){function i(t){return t&&fr(t)?t:"-"}function r(t){return!(null==t||isNaN(t)||!isFinite(t))}var o="time"===e,a=t instanceof Date;if(o||a){var s=o?Kl(t):t;if(!isNaN(+s))return Ng(s,"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}",n);if(a)return"-"}if("ordinal"===e)return tr(t)?i(t):er(t)&&r(t)?t+"":"-";var l=tc(t);return r(l)?Kg(l):tr(t)?i(t):"boolean"==typeof t?t+"":"-"}var em=["a","b","c","d","e","f","g"],nm=function(t,e){return"{"+t+(null==e?"":e)+"}"};function im(t,e,n){Ki(e)||(e=[e]);var i=e.length;if(!i)return"";for(var r=e[0].$vars||[],o=0;oi||l.newline?(o=0,u=g,a+=s+n,s=h.height):s=Math.max(s,h.height)}else{var m=h.height+(f?-f.y+h.y:0);(d=a+m)>r||l.newline?(o+=s+n,a=0,d=m,s=h.width):s=Math.max(s,h.width)}l.newline||(l.x=o,l.y=a,l.markRedraw(),"horizontal"===t?o=u+n:a=d+n)})}function _m(t,e,n){n=Jg(n||0);var i=e.width,r=e.height,o=Wl(t.left,i),a=Wl(t.top,r),s=Wl(t.right,i),l=Wl(t.bottom,r),c=Wl(t.width,i),u=Wl(t.height,r),d=n[2]+n[0],h=n[1]+n[3],p=t.aspect;switch(isNaN(c)&&(c=i-s-h-o),isNaN(u)&&(u=r-l-d-a),null!=p&&(isNaN(c)&&isNaN(u)&&(p>i/r?c=.8*i:u=.8*r),isNaN(c)&&(c=p*u),isNaN(u)&&(u=c/p)),isNaN(o)&&(o=i-s-c-h),isNaN(a)&&(a=r-l-u-d),t.left||t.right){case"center":o=i/2-c/2-n[3];break;case"right":o=i-c-h}switch(t.top||t.bottom){case"middle":case"center":a=r/2-u/2-n[0];break;case"bottom":a=r-u-d}o=o||0,a=a||0,isNaN(c)&&(c=i-h-o-(s||0)),isNaN(u)&&(u=r-d-a-(l||0));var f=new Do((e.x||0)+o+n[3],(e.y||0)+a+n[0],c,u);return f.margin=n,f}Zi(ym,"vertical"),Zi(ym,"horizontal");var bm=1;function xm(t,e,n){var i,r,o,a,s=t.boxCoordinateSystem;if(s){var l=function(t){var e=t.getShallow("coord",!0),n=lm;if(null==e){var i=um.get(t.type);i&&i.getCoord2&&(n=cm,e=i.getCoord2(t))}return{coord:e,from:n}}(t),c=l.coord,u=l.from;if(s.dataToLayout){o=bm,a=u;var d=s.dataToLayout(c);i=d.contentRect||d.rect}}return null==o&&(o=bm),o===bm&&(i||(i={x:0,y:0,width:e.getWidth(),height:e.getHeight()}),r=[i.x+i.width/2,i.y+i.height/2]),{type:o,refContainer:i,refPoint:r,boxCoordFrom:a}}function wm(t){var e=t.layoutMode||t.constructor.layoutMode;return nr(e)?e:e?{type:e}:null}function Sm(t,e,n){var i=n&&n.ignoreSize;!Ki(i)&&(i=[i,i]);var r=a(vm[0],0),o=a(vm[1],1);function a(n,r){var o={},a=0,l={},c=0;if(gm(n,function(e){l[e]=t[e]}),gm(n,function(t){Sr(e,t)&&(o[t]=l[t]=e[t]),s(o,t)&&a++,s(l,t)&&c++}),i[r])return s(e,n[1])?l[n[2]]=null:s(e,n[2])&&(l[n[1]]=null),l;if(2!==c&&a){if(a>=2)return o;for(var u=0;u=0;a--)o=Hi(o,n[a],!0);e.defaultOption=o}return e.defaultOption},e.prototype.getReferringComponents=function(t,e){var n=t+"Index",i=t+"Id";return Mc(this.ecModel,t,{index:this.get(n,!0),id:this.get(i,!0)},e)},e.prototype.getBoxLayoutParams=function(){return e=!1,{left:(t=this).getShallow("left",e),top:t.getShallow("top",e),right:t.getShallow("right",e),bottom:t.getShallow("bottom",e),width:t.getShallow("width",e),height:t.getShallow("height",e)};var t,e},e.prototype.getZLevelKey=function(){return""},e.prototype.setZLevel=function(t){this.option.zlevel=t},e.protoInitialize=((n=e.prototype).type="component",n.id="",n.name="",n.mainType="",n.subType="",void(n.componentIndex=0)),e}(lg);Lc(Mm,lg),Oc(Mm),function(t){var e={};t.registerSubTypeDefaulter=function(t,n){var i=Dc(t);e[i.main]=n},t.determineSubType=function(n,i){var r=i.type;if(!r){var o=Dc(n).main;t.hasSubTypes(n)&&e[o]&&(r=e[o](i))}return r}}(Mm),function(t,e){function n(t,e){return t[e]||(t[e]={predecessor:[],successor:[]}),t[e]}t.topologicalTravel=function(t,i,r,o){if(t.length){var a=function(t){var i={},r=[];return ji(t,function(o){var a=n(i,o),s=function(t,e){var n=[];return ji(t,function(t){$i(e,t)>=0&&n.push(t)}),n}(a.originalDeps=e(o),t);a.entryCount=s.length,0===a.entryCount&&r.push(o),ji(s,function(t){$i(a.predecessor,t)<0&&a.predecessor.push(t);var e=n(i,t);$i(e.successor,t)<0&&e.successor.push(o)})}),{graph:i,noEntryList:r}}(i),s=a.graph,l=a.noEntryList,c={};for(ji(t,function(t){c[t]=!0});l.length;){var u=l.pop(),d=s[u],h=!!c[u];h&&(r.call(o,u,d.originalDeps.slice()),delete c[u]),ji(d.successor,h?f:p)}ji(c,function(){throw new Error("")})}function p(t){s[t].entryCount--,0===s[t].entryCount&&l.push(t)}function f(t){c[t]=!0,p(t)}}}(Mm,function(t){var e=[];ji(Mm.getClassesByMainType(t),function(t){e=e.concat(t.dependencies||t.prototype.dependencies||[])}),e=qi(e,function(t){return Dc(t).main}),"dataset"!==t&&$i(e,"dataset")<=0&&e.unshift("dataset");return e});var Tm={color:{},darkColor:{},size:{}},Am=Tm.color={theme:["#5070dd","#b6d634","#505372","#ff994d","#0ca8df","#ffd10a","#fb628b","#785db0","#3fbe95"],neutral00:"#fff",neutral05:"#f4f7fd",neutral10:"#e8ebf0",neutral15:"#dbdee4",neutral20:"#cfd2d7",neutral25:"#c3c5cb",neutral30:"#b7b9be",neutral35:"#aaacb2",neutral40:"#9ea0a5",neutral45:"#929399",neutral50:"#86878c",neutral55:"#797b7f",neutral60:"#6d6e73",neutral65:"#616266",neutral70:"#54555a",neutral75:"#48494d",neutral80:"#3c3c41",neutral85:"#303034",neutral90:"#232328",neutral95:"#17171b",neutral99:"#000",accent05:"#eff1f9",accent10:"#e0e4f2",accent15:"#d0d6ec",accent20:"#c0c9e6",accent25:"#b1bbdf",accent30:"#a1aed9",accent35:"#91a0d3",accent40:"#8292cc",accent45:"#7285c6",accent50:"#6578ba",accent55:"#5c6da9",accent60:"#536298",accent65:"#4a5787",accent70:"#404c76",accent75:"#374165",accent80:"#2e3654",accent85:"#252b43",accent90:"#1b2032",accent95:"#121521",transparent:"rgba(0,0,0,0)",highlight:"rgba(255,231,130,0.8)"};for(var Im in Bi(Am,{primary:Am.neutral80,secondary:Am.neutral70,tertiary:Am.neutral60,quaternary:Am.neutral50,disabled:Am.neutral20,border:Am.neutral30,borderTint:Am.neutral20,borderShade:Am.neutral40,background:Am.neutral05,backgroundTint:"rgba(234,237,245,0.5)",backgroundTransparent:"rgba(255,255,255,0)",backgroundShade:Am.neutral10,shadow:"rgba(0,0,0,0.2)",shadowTint:"rgba(129,130,136,0.2)",axisLine:Am.neutral70,axisLineTint:Am.neutral40,axisTick:Am.neutral70,axisTickMinor:Am.neutral60,axisLabel:Am.neutral70,axisSplitLine:Am.neutral15,axisMinorSplitLine:Am.neutral05}),Am)if(Am.hasOwnProperty(Im)){var Dm=Am[Im];"theme"===Im?Tm.darkColor.theme=Am.theme.slice():"highlight"===Im?Tm.darkColor.highlight="rgba(255,231,130,0.4)":0===Im.indexOf("accent")?Tm.darkColor[Im]=Ua(Dm,0,function(t){return.5*t},function(t){return Math.min(1,1.3-t)}):Tm.darkColor[Im]=Ua(Dm,0,function(t){return.9*t},function(t){return 1-Math.pow(t,1.5)})}Tm.size={xxs:2,xs:5,s:10,m:15,l:20,xl:30,xxl:40,xxxl:50};var Pm="";"undefined"!=typeof navigator&&(Pm=navigator.platform||"");var Lm="rgba(0, 0, 0, 0.2)",Em=Tm.color.theme[0],Nm=Ua(Em,0,null,.9),Rm={darkMode:"auto",colorBy:"series",color:Tm.color.theme,gradientColor:[Nm,Em],aria:{decal:{decals:[{color:Lm,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:Lm,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:Lm,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:Lm,dashArrayX:[[6,6],[0,6,6,0]],dashArrayY:[6,0]},{color:Lm,dashArrayX:[[1,0],[1,6]],dashArrayY:[1,0,6,0],rotation:Math.PI/4},{color:Lm,symbol:"triangle",dashArrayX:[[9,9],[0,9,9,0]],dashArrayY:[7,2],symbolSize:.75}]}},textStyle:{fontFamily:Pm.match(/^Win/)?"Microsoft YaHei":"sans-serif",fontSize:12,fontStyle:"normal",fontWeight:"normal"},blendMode:null,stateAnimation:{duration:300,easing:"cubicOut"},animation:"auto",animationDuration:1e3,animationDurationUpdate:500,animationEasing:"cubicInOut",animationEasingUpdate:"cubicInOut",animationThreshold:2e3,progressiveThreshold:3e3,progressive:400,hoverLayerThreshold:3e3,useUTC:!1},Om=xr(["tooltip","label","itemName","itemId","itemGroupId","itemChildGroupId","seriesName"]),zm="original",Hm="arrayRows",Bm="objectRows",Fm="keyedColumns",$m="typedArray",Vm="unknown",Wm="column",jm="row",qm=1,Um=2,Gm=3,Xm=xc();function Ym(t,e,n){var i={},r=Zm(e);if(!r||!t)return i;var o,a,s=[],l=[],c=e.ecModel,u=Xm(c).datasetMap,d=r.uid+"_"+n.seriesLayoutBy;ji(t=t.slice(),function(e,n){var r=nr(e)?e:t[n]={name:e};"ordinal"===r.type&&null==o&&(o=n,a=f(r)),i[r.name]=[]});var h=u.get(d)||u.set(d,{categoryWayDim:a,valueWayDim:0});function p(t,e,n){for(var i=0;ie)return t[i];return t[n-1]}(i,a):n;if(u=u||n,!u||!u.length)return;var d=u[l];r&&(c[r]=d);return s.paletteIdx=(l+1)%u.length,d}(this,Jm,i,r,t,e,n)},t.prototype.clearColorPalette=function(){!function(t,e){e(t).paletteIdx=0,e(t).paletteNameMap={}}(this,Jm)},t}();var rv="\0_ec_inner",ov=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e.prototype.init=function(t,e,n,i,r,o){i=i||{},this.option=null,this._theme=new lg(i),this._locale=new lg(r),this._optionManager=o},e.prototype.setOption=function(t,e,n){var i=lv(e);this._optionManager.setOption(t,n,i),this._resetOption(null,i)},e.prototype.resetOption=function(t,e){return this._resetOption(t,lv(e))},e.prototype._resetOption=function(t,e){var n=!1,i=this._optionManager;if(!t||"recreate"===t){var r=i.mountOption("recreate"===t);this.option&&"recreate"!==t?(this.restoreData(),this._mergeOption(r,e)):nv(this,r),n=!0}if("timeline"!==t&&"media"!==t||this.restoreData(),!t||"recreate"===t||"timeline"===t){var o=i.getTimelineOption(this);o&&(n=!0,this._mergeOption(o,e))}if(!t||"recreate"===t||"media"===t){var a=i.getMediaOption(this);a.length&&ji(a,function(t){n=!0,this._mergeOption(t,e)},this)}return n},e.prototype.mergeOption=function(t){this._mergeOption(t,null)},e.prototype._mergeOption=function(t,e){var n=this.option,i=this._componentsMap,r=this._componentsCount,o=[],a=xr(),s=e&&e.replaceMergeMainTypeMap;Xm(this).datasetMap=xr(),ji(t,function(t,e){null!=t&&(Mm.hasClass(e)?e&&(o.push(e),a.set(e,!0)):n[e]=null==n[e]?zi(t):Hi(n[e],t,!0))}),s&&s.each(function(t,e){Mm.hasClass(e)&&!a.get(e)&&(o.push(e),a.set(e,!0))}),Mm.topologicalTravel(o,Mm.getAllClassMainTypes(),function(e){var o=function(t,e,n){var i=Qm.get(e);if(!i)return n;var r=i(t);return r?n.concat(r):n}(this,e,cc(t[e])),a=i.get(e),l=a?s&&s.get(e)?"replaceMerge":"normalMerge":"replaceAll",c=fc(a,o,l);(function(t,e,n){ji(t,function(t){var i=t.newOption;nr(i)&&(t.keyInfo.mainType=e,t.keyInfo.subType=function(t,e,n,i){return e.type?e.type:n?n.subType:i.determineSubType(t,e)}(e,i,t.existing,n))})})(c,e,Mm),n[e]=null,i.set(e,null),r.set(e,0);var u,d=[],h=[],p=0;ji(c,function(t,n){var i=t.existing,r=t.newOption;if(r){var o="series"===e,a=Mm.getClass(e,t.keyInfo.subType,!o);if(!a)return;if("tooltip"===e){if(u)return;u=!0}if(i&&i.constructor===a)i.name=t.keyInfo.name,i.mergeOption(r,this),i.optionUpdated(r,!1);else{var s=Bi({componentIndex:n},t.keyInfo);Bi(i=new a(r,this,this,s),s),t.brandNew&&(i.__requireNewView=!0),i.init(r,this,this),i.optionUpdated(null,!0)}}else i&&(i.mergeOption({},this),i.optionUpdated({},!1));i?(d.push(i.option),h.push(i),p++):(d.push(void 0),h.push(void 0))},this),n[e]=d,i.set(e,h),r.set(e,p),"series"===e&&tv(this)},this),this._seriesIndices||tv(this)},e.prototype.getOption=function(){var t=zi(this.option);return ji(t,function(e,n){if(Mm.hasClass(n)){for(var i=cc(e),r=i.length,o=!1,a=r-1;a>=0;a--)i[a]&&!_c(i[a])?o=!0:(i[a]=null,!o&&r--);i.length=r,t[n]=i}}),delete t[rv],t},e.prototype.setTheme=function(t){this._theme=new lg(t),this._resetOption("recreate",null)},e.prototype.getTheme=function(){return this._theme},e.prototype.getLocaleModel=function(){return this._locale},e.prototype.setUpdatePayload=function(t){this._payload=t},e.prototype.getUpdatePayload=function(){return this._payload},e.prototype.getComponent=function(t,e){var n=this._componentsMap.get(t);if(n){var i=n[e||0];if(i)return i;if(null==e)for(var r=0;r=e:"max"===n?t<=e:t===e})(i[a],t,o)||(r=!1)}}),r}var fv=ji,gv=nr,mv=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"];function vv(t){var e=t&&t.itemStyle;if(e)for(var n=0,i=mv.length;nc&&(c=p)}s[0]=l,s[1]=c}},i=function(){return this._data?this._data.length/this._dimSize:0};function r(t){for(var e=0;e=0&&(s=o.interpolatedValue[l])}return null!=s?s+"":""}):void 0},t.prototype.getRawValue=function(t,e){return ay(this.getData(e),t)},t.prototype.formatTooltip=function(t,e,n){},t}();function cy(t){var e,n;return nr(t)?t.type&&(n=t):e=t,{text:e,frag:n}}function uy(t){return new dy(t)}var dy=function(){function t(t){t=t||{},this._reset=t.reset,this._plan=t.plan,this._count=t.count,this._onDirty=t.onDirty,this._dirty=!0}return t.prototype.perform=function(t){var e,n=this._upstream,i=t&&t.skip;if(this._dirty&&n){var r=this.context;r.data=r.outputData=n.context.outputData}this.__pipeline&&(this.__pipeline.currentTask=this),this._plan&&!i&&(e=this._plan(this.context));var o,a=u(this._modBy),s=this._modDataCount||0,l=u(t&&t.modBy),c=t&&t.modDataCount||0;function u(t){return!(t>=1)&&(t=1),t}a===l&&s===c||(e="reset"),(this._dirty||"reset"===e)&&(this._dirty=!1,o=this._doReset(i)),this._modBy=l,this._modDataCount=c;var d=t&&t.step;if(this._dueEnd=n?n._outputDueEnd:this._count?this._count(this.context):1/0,this._progress){var h=this._dueIndex,p=Math.min(null!=d?this._dueIndex+d:1/0,this._dueEnd);if(!i&&(o||h1&&i>0?s:a}};return o;function a(){return e=t?null:oi?-this._resultLT:0},t}(),gy=function(){function t(){}return t.prototype.getRawData=function(){throw new Error("not supported")},t.prototype.getRawDataItem=function(t){throw new Error("not supported")},t.prototype.cloneRawData=function(){},t.prototype.getDimensionInfo=function(t){},t.prototype.cloneAllDimensionInfo=function(){},t.prototype.count=function(){},t.prototype.retrieveValue=function(t,e){},t.prototype.retrieveValueFromItem=function(t,e){},t.prototype.convertValue=function(t,e){return py(t,e)},t}();function my(t){if(!wy(t.sourceFormat)){ac("")}return t.data}function vy(t){var e=t.sourceFormat,n=t.data;if(!wy(e)){ac("")}if(e===Hm){for(var i=[],r=0,o=n.length;r65535?ky:My}function Py(){return[1/0,-1/0]}function Ly(t){var e=t.constructor;return e===Array?t.slice():new e(t)}function Ey(t,e,n,i,r){var o=Iy[n||"float"];if(r){var a=t[e],s=a&&a.length;if(s!==i){for(var l=new o(i),c=0;cg[1]&&(g[1]=f)}return this._rawCount=this._count=s,{start:a,end:s}},t.prototype._initDataFromProvider=function(t,e,n){for(var i=this._provider,r=this._chunks,o=this._dimensions,a=o.length,s=this._rawExtent,l=qi(o,function(t){return t.property}),c=0;cm[1]&&(m[1]=g)}}!i.persistent&&i.clean&&i.clean(),this._rawCount=this._count=e,this._extent=[]},t.prototype.count=function(){return this._count},t.prototype.get=function(t,e){if(!(e>=0&&e=0&&e=this._rawCount||t<0)return-1;if(!this._indices)return t;var e=this._indices,n=e[t];if(null!=n&&nt))return o;r=o-1}}return-1},t.prototype.getIndices=function(){var t,e=this._indices;if(e){var n=e.constructor,i=this._count;if(n===Array){t=new n(i);for(var r=0;r=c&&_<=u||isNaN(_))&&(a[s++]=p),p++}h=!0}else if(2===r){f=d[i[0]];var m=d[i[1]],v=t[i[1]][0],y=t[i[1]][1];for(g=0;g=c&&_<=u||isNaN(_))&&(b>=v&&b<=y||isNaN(b))&&(a[s++]=p),p++}h=!0}}if(!h)if(1===r)for(g=0;g=c&&_<=u||isNaN(_))&&(a[s++]=x)}else for(g=0;gt[C][1])&&(w=!1)}w&&(a[s++]=e.getRawIndex(g))}return sm[1]&&(m[1]=g)}}}},t.prototype.lttbDownSample=function(t,e){var n,i,r,o=this.clone([t],!0),a=o._chunks[t],s=this.count(),l=0,c=Math.floor(1/e),u=this.getRawIndex(0),d=new(Dy(this._rawCount))(Math.min(2*(Math.ceil(s/c)+2),s));d[l++]=u;for(var h=1;hn&&(n=i,r=k)}C>0&&Ca&&(f=a-c);for(var g=0;gp&&(p=m,h=c+g)}var v=this.getRawIndex(u),y=this.getRawIndex(h);uc-p&&(s=c-p,a.length=s);for(var f=0;fu[1]&&(u[1]=m),d[h++]=v}return r._count=h,r._indices=d,r._updateGetRawIdx(),r},t.prototype.each=function(t,e){if(this._count)for(var n=t.length,i=this._chunks,r=0,o=this.count();ra&&(a=l)}return i=[o,a],this._extent[t]=i,i},t.prototype.getRawDataItem=function(t){var e=this.getRawIndex(t);if(this._provider.persistent)return this._provider.getItem(e);for(var n=[],i=this._chunks,r=0;r=0?this._indices[t]:-1},t.prototype._updateGetRawIdx=function(){this.getRawIndex=this._indices?this._getRawIdx:this._getRawIdxIdentity},t.internalField=function(){function t(t,e,n,i){return py(t[i],this._dimensions[i])}Sy={arrayRows:t,objectRows:function(t,e,n,i){return py(t[e],this._dimensions[i])},keyedColumns:t,original:function(t,e,n,i){var r=t&&(null==t.value?t:t.value);return py(r instanceof Array?r[i]:r,this._dimensions[i])},typedArray:function(t,e,n,i){return t[i]}}}(),t}(),Ry=function(){function t(t){this._sourceList=[],this._storeList=[],this._upstreamSignList=[],this._versionSignBase=0,this._dirty=!0,this._sourceHost=t}return t.prototype.dirty=function(){this._setLocalSource([],[]),this._storeList=[],this._dirty=!0},t.prototype._setLocalSource=function(t,e){this._sourceList=t,this._upstreamSignList=e,this._versionSignBase++,this._versionSignBase>9e10&&(this._versionSignBase=0)},t.prototype._getVersionSign=function(){return this._sourceHost.uid+"_"+this._versionSignBase},t.prototype.prepareSource=function(){this._isDirty()&&(this._createSource(),this._dirty=!1)},t.prototype._createSource=function(){this._setLocalSource([],[]);var t,e,n=this._sourceHost,i=this._getUpstreamSourceManagers(),r=!!i.length;if(Oy(n)){var o=n,a=void 0,s=void 0,l=void 0;if(r){var c=i[0];c.prepareSource(),a=(l=c.getSource()).data,s=l.sourceFormat,e=[c._getVersionSign()]}else s=rr(a=o.get("data",!0))?$m:zm,e=[];var u=this._getSourceMetaRawOption()||{},d=l&&l.metaRawOption||{},h=cr(u.seriesLayoutBy,d.seriesLayoutBy)||null,p=cr(u.sourceHeader,d.sourceHeader),f=cr(u.dimensions,d.dimensions);t=h!==d.seriesLayoutBy||!!p!=!!d.sourceHeader||f?[Vv(a,{seriesLayoutBy:h,sourceHeader:p,dimensions:f},s)]:[]}else{var g=n;if(r){var m=this._applyTransform(i);t=m.sourceList,e=m.upstreamSignList}else{t=[Vv(g.get("source",!0),this._getSourceMetaRawOption(),null)],e=[]}}this._setLocalSource(t,e)},t.prototype._applyTransform=function(t){var e,n=this._sourceHost,i=n.get("transform",!0),r=n.get("fromTransformResult",!0);if(null!=r){1!==t.length&&zy("")}var o,a=[],s=[];return ji(t,function(t){t.prepareSource();var e=t.getSource(r||0);null==r||e||zy(""),a.push(e),s.push(t._getVersionSign())}),i?e=function(t,e){var n=cc(t),i=n.length;i||ac("");for(var r=0,o=i;r1||n>0&&!t.noHeader;return ji(t.blocks,function(t){var n=qy(t);n>=e&&(e=n+ +(i&&(!n||Wy(t)&&!t.noHeader)))}),e}return 0}function Uy(t,e,n,i){var r,o=e.noHeader,a=(r=qy(e),{html:Fy[r],richText:$y[r]}),s=[],l=e.blocks||[];pr(!l||Ki(l)),l=l||[];var c=t.orderMode;if(e.sortBlocks&&c){l=l.slice();var u={valueAsc:"asc",valueDesc:"desc"};if(Sr(u,c)){var d=new fy(u[c],null);l.sort(function(t,e){return d.evaluate(t.sortParam,e.sortParam)})}else"seriesDesc"===c&&l.reverse()}ji(l,function(n,r){var o=e.valueFormatter,l=jy(n)(o?Bi(Bi({},t),{valueFormatter:o}):t,n,r>0?a.html:0,i);null!=l&&s.push(l)});var h="richText"===t.renderMode?s.join(a.richText):Yy(i,s.join(""),o?n:a.html);if(o)return h;var p=tm(e.header,"ordinal",t.useUTC),f=By(i,t.renderMode).nameStyle,g=Hy(i);return"richText"===t.renderMode?Zy(t,p,f)+a.richText+h:Yy(i,'
'+Zr(p)+"
"+h,n)}function Gy(t,e,n,i){var r=t.renderMode,o=e.noName,a=e.noValue,s=!e.markerType,l=e.name,c=t.useUTC,u=e.valueFormatter||t.valueFormatter||function(t){return qi(t=Ki(t)?t:[t],function(t,e){return tm(t,Ki(p)?p[e]:p,c)})};if(!o||!a){var d=s?"":t.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||Tm.color.secondary,r),h=o?"":tm(l,"ordinal",c),p=e.valueType,f=a?[]:u(e.value,e.dataIndex),g=!s||!o,m=!s&&o,v=By(i,r),y=v.nameStyle,_=v.valueStyle;return"richText"===r?(s?"":d)+(o?"":Zy(t,h,y))+(a?"":function(t,e,n,i,r){var o=[r],a=i?10:20;return n&&o.push({padding:[0,0,0,a],align:"right"}),t.markupStyleCreator.wrapRichTextStyle(Ki(e)?e.join(" "):e,o)}(t,f,g,m,_)):Yy(i,(s?"":d)+(o?"":function(t,e,n){return''+Zr(t)+""}(h,!s,y))+(a?"":function(t,e,n,i){var r=n?"10px":"20px",o=e?"float:right;margin-left:"+r:"";return t=Ki(t)?t:[t],''+qi(t,function(t){return Zr(t)}).join("  ")+""}(f,g,m,_)),n)}}function Xy(t,e,n,i,r,o){if(t)return jy(t)({useUTC:r,renderMode:n,orderMode:i,markupStyleCreator:e,valueFormatter:t.valueFormatter},t,0,o)}function Yy(t,e,n){return'
'+e+'
'}function Zy(t,e,n){return t.markupStyleCreator.wrapRichTextStyle(e,n)}function Ky(t,e){var n=t.get("padding");return null!=n?n:"richText"===e?[8,10]:10}var Qy=function(){function t(){this.richTextStyles={},this._nextStyleNameId=ec()}return t.prototype._generateStyleName=function(){return"__EC_aUTo_"+this._nextStyleNameId++},t.prototype.makeTooltipMarker=function(t,e,n){var i="richText"===n?this._generateStyleName():null,r=function(t,e){var n=Ji(t)?{color:t,extraCssText:e}:t||{},i=n.color,r=n.type;e=n.extraCssText;var o=n.renderMode||"html";return i?"html"===o?"subItem"===r?'':'':{renderMode:o,content:"{"+(n.markerId||"markerX")+"|} ",style:"subItem"===r?{width:4,height:4,borderRadius:2,backgroundColor:i}:{width:10,height:10,borderRadius:5,backgroundColor:i}}:""}({color:e,type:t,renderMode:n,markerId:i});return Ji(r)?r:(this.richTextStyles[i]=r.style,r.content)},t.prototype.wrapRichTextStyle=function(t,e){var n={};Ki(e)?ji(e,function(t){return Bi(n,t)}):Bi(n,e);var i=this._generateStyleName();return this.richTextStyles[i]=n,"{"+i+"|"+t+"}"},t}();function Jy(t){var e,n,i,r,o=t.series,a=t.dataIndex,s=t.multipleSeries,l=o.getData(),c=l.mapDimensionsAll("defaultedTooltip"),u=c.length,d=o.getRawValue(a),h=Ki(d),p=function(t,e){return rm(t.getData().getItemVisual(e,"style")[t.visualDrawType])}(o,a);if(u>1||h&&!u){var f=function(t,e,n,i,r){var o=e.getData(),a=Ui(t,function(t,e,n){var i=o.getDimensionInfo(n);return t||i&&!1!==i.tooltip&&null!=i.displayName},!1),s=[],l=[],c=[];function u(t,e){var n=o.getDimensionInfo(e);n&&!1!==n.otherDims.tooltip&&(a?c.push(Vy("nameValue",{markerType:"subItem",markerColor:r,name:n.displayName,value:t,valueType:n.type})):(s.push(t),l.push(n.type)))}return i.length?ji(i,function(t){u(ay(o,n,t),t)}):ji(t,u),{inlineValues:s,inlineValueTypes:l,blocks:c}}(d,o,a,c,p);e=f.inlineValues,n=f.inlineValueTypes,i=f.blocks,r=f.inlineValues[0]}else if(u){var g=l.getDimensionInfo(c[0]);r=e=ay(l,a,c[0]),n=g.type}else r=e=h?d[0]:d;var m=yc(o),v=m&&o.name||"",y=l.getName(a),_=s?v:y;return Vy("section",{header:v,noHeader:s||!m,sortParam:r,blocks:[Vy("nameValue",{markerType:"item",markerColor:p,name:_,noName:!fr(_),value:e,valueType:n,dataIndex:a})].concat(i||[])})}var t_=xc();function e_(t,e){return t.getName(e)||t.getId(e)}var n_=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._selectedDataIndicesMap={},e}var n;return S(e,t),e.prototype.init=function(t,e,n){this.seriesIndex=this.componentIndex,this.dataTask=uy({count:r_,reset:o_}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n),(t_(this).sourceManager=new Ry(this)).prepareSource();var i=this.getInitialData(t,n);s_(i,this),this.dataTask.context.data=i,t_(this).dataBeforeProcessed=i,i_(this),this._initSelectedMapFromData(i)},e.prototype.mergeDefaultAndTheme=function(t,e){var n=wm(this),i=n?Cm(t):{},r=this.subType;Mm.hasClass(r)&&(r+="Series"),Hi(t,e.getTheme().get(this.subType)),Hi(t,this.getDefaultOption()),uc(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&Sm(t,i,n)},e.prototype.mergeOption=function(t,e){t=Hi(this.option,t,!0),this.fillDataTextStyle(t.data);var n=wm(this);n&&Sm(this.option,t,n);var i=t_(this).sourceManager;i.dirty(),i.prepareSource();var r=this.getInitialData(t,e);s_(r,this),this.dataTask.dirty(),this.dataTask.context.data=r,t_(this).dataBeforeProcessed=r,i_(this),this._initSelectedMapFromData(r)},e.prototype.fillDataTextStyle=function(t){if(t&&!rr(t))for(var e=["show"],n=0;n=0&&u<0)&&(c=o,u=r,d=0),r===u&&(l[d++]=e))}),l.length=d,l},e.prototype.formatTooltip=function(t,e,n){return Jy({series:this,dataIndex:t,multipleSeries:e})},e.prototype.isAnimationEnabled=function(){var t=this.ecModel;if(mi.node&&(!t||!t.ssr))return!1;var e=this.getShallow("animation");return e&&this.getData().count()>this.getShallow("animationThreshold")&&(e=!1),!!e},e.prototype.restoreData=function(){this.dataTask.dirty()},e.prototype.getColorFromPalette=function(t,e,n){var i=this.ecModel,r=iv.prototype.getColorFromPalette.call(this,t,e,n);return r||(r=i.getColorFromPalette(t,e,n)),r},e.prototype.coordDimToDataDim=function(t){return this.getRawData().mapDimensionsAll(t)},e.prototype.getProgressive=function(){return this.get("progressive")},e.prototype.getProgressiveThreshold=function(){return this.get("progressiveThreshold")},e.prototype.select=function(t,e){this._innerSelect(this.getData(e),t)},e.prototype.unselect=function(t,e){var n=this.option.selectedMap;if(n){var i=this.option.selectedMode,r=this.getData(e);if("series"===i||"all"===n)return this.option.selectedMap={},void(this._selectedDataIndicesMap={});for(var o=0;o=0&&n.push(r)}return n},e.prototype.isSelected=function(t,e){var n=this.option.selectedMap;if(!n)return!1;var i=this.getData(e);return("all"===n||n[e_(i,t)])&&!i.getItemModel(t).get(["select","disabled"])},e.prototype.isUniversalTransitionEnabled=function(){if(this.__universalTransitionEnabled)return!0;var t=this.option.universalTransition;return!!t&&(!0===t||t&&t.enabled)},e.prototype._innerSelect=function(t,e){var n,i,r=this.option,o=r.selectedMode,a=e.length;if(o&&a)if("series"===o)r.selectedMap="all";else if("multiple"===o){nr(r.selectedMap)||(r.selectedMap={});for(var s=r.selectedMap,l=0;l0&&this._innerSelect(t,e)}},e.registerClass=function(t){return Mm.registerClass(t)},e.protoInitialize=((n=e.prototype).type="series.__base__",n.seriesIndex=0,n.ignoreStyleOnData=!1,n.hasSymbolVisual=!1,n.defaultSymbol="circle",n.visualStyleAccessPath="itemStyle",void(n.visualDrawType="fill")),e}(Mm);function i_(t){var e=t.name;yc(t)||(t.name=function(t){var e=t.getRawData(),n=e.mapDimensionsAll("seriesName"),i=[];return ji(n,function(t){var n=e.getDimensionInfo(t);n.displayName&&i.push(n.displayName)}),i.join(" ")}(t)||e)}function r_(t){return t.model.getRawData().count()}function o_(t){var e=t.model;return e.setData(e.getRawData().cloneShallow()),a_}function a_(t,e){e.outputData&&t.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function s_(t,e){ji(function(t,e){for(var n=new t.constructor(t.length+e.length),i=0;i=0?d():u=setTimeout(d,-r),l=i};return h.clear=function(){u&&(clearTimeout(u),u=null)},h.debounceNextCall=function(t){s=t},h}function C_(t,e,n,i){var r=t[e];if(r){var o=r[b_]||r,a=r[w_];if(r[x_]!==n||a!==i){if(null==n||!i)return t[e]=o;(r=t[e]=S_(o,n,"debounce"===i))[b_]=o,r[w_]=i,r[x_]=n}return r}}function k_(t,e){var n=t[e];n&&n[b_]&&(n.clear&&n.clear(),t[e]=n[b_])}var M_=xc(),T_={itemStyle:zc(og,!0),lineStyle:zc(ng,!0)},A_={lineStyle:"stroke",itemStyle:"fill"};function I_(t,e){var n=t.visualStyleMapper||T_[e];return n||(console.warn("Unknown style type '"+e+"'."),T_.itemStyle)}function D_(t,e){var n=t.visualDrawType||A_[e];return n||(console.warn("Unknown style type '"+e+"'."),"fill")}var P_={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=t.getModel(i),o=I_(t,i)(r),a=r.getShallow("decal");a&&(n.setVisual("decal",a),a.dirty=!0);var s=D_(t,i),l=o[s],c=Qi(l)?l:null,u="auto"===o.fill||"auto"===o.stroke;if(!o[s]||c||u){var d=t.getColorFromPalette(t.name,null,e.getSeriesCount());o[s]||(o[s]=d,n.setVisual("colorFromPalette",!0)),o.fill="auto"===o.fill||Qi(o.fill)?d:o.fill,o.stroke="auto"===o.stroke||Qi(o.stroke)?d:o.stroke}if(n.setVisual("style",o),n.setVisual("drawType",s),!e.isSeriesFiltered(t)&&c)return n.setVisual("colorFromPalette",!1),{dataEach:function(e,n){var i=t.getDataParams(n),r=Bi({},o);r[s]=c(i),e.setItemVisual(n,"style",r)}}}},L_=new lg,E_={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){if(!t.ignoreStyleOnData&&!e.isSeriesFiltered(t)){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=I_(t,i),o=n.getVisual("drawType");return{dataEach:n.hasItemOption?function(t,e){var n=t.getRawDataItem(e);if(n&&n[i]){L_.option=n[i];var a=r(L_);Bi(t.ensureUniqueItemVisual(e,"style"),a),L_.option.decal&&(t.setItemVisual(e,"decal",L_.option.decal),L_.option.decal.dirty=!0),o in a&&t.setItemVisual(e,"colorFromPalette",!1)}}:null}}}},N_={performRawSeries:!0,overallReset:function(t){var e=xr();t.eachSeries(function(t){var n=t.getColorBy();if(!t.isColorBySeries()){var i=t.type+"-"+n,r=e.get(i);r||(r={},e.set(i,r)),M_(t).scope=r}}),t.eachSeries(function(e){if(!e.isColorBySeries()&&!t.isSeriesFiltered(e)){var n=e.getRawData(),i={},r=e.getData(),o=M_(e).scope,a=e.visualStyleAccessPath||"itemStyle",s=D_(e,a);r.each(function(t){var e=r.getRawIndex(t);i[e]=t}),n.each(function(t){var a=i[t];if(r.getItemVisual(a,"colorFromPalette")){var l=r.ensureUniqueItemVisual(a,"style"),c=n.getName(t)||t+"",u=n.count();l[s]=e.getColorFromPalette(c,o,u)}})}})}},R_=Math.PI;var O_=function(){function t(t,e,n,i){this._stageTaskMap=xr(),this.ecInstance=t,this.api=e,n=this._dataProcessorHandlers=n.slice(),i=this._visualHandlers=i.slice(),this._allHandlers=n.concat(i)}return t.prototype.restoreData=function(t,e){t.restoreData(e),this._stageTaskMap.each(function(t){var e=t.overallTask;e&&e.dirty()})},t.prototype.getPerformArgs=function(t,e){if(t.__pipeline){var n=this._pipelineMap.get(t.__pipeline.id),i=n.context,r=!e&&n.progressiveEnabled&&(!i||i.progressiveRender)&&t.__idxInPipeline>n.blockIndex?n.step:null,o=i&&i.modDataCount;return{step:r,modBy:null!=o?Math.ceil(o/r):null,modDataCount:o}}},t.prototype.getPipeline=function(t){return this._pipelineMap.get(t)},t.prototype.updateStreamModes=function(t,e){var n=this._pipelineMap.get(t.uid),i=t.getData().count(),r=n.progressiveEnabled&&e.incrementalPrepareRender&&i>=n.threshold,o=t.get("large")&&i>=t.get("largeThreshold"),a="mod"===t.get("progressiveChunkMode")?i:null;t.pipelineContext=n.context={progressiveRender:r,modDataCount:a,large:o}},t.prototype.restorePipelines=function(t){var e=this,n=e._pipelineMap=xr();t.eachSeries(function(t){var i=t.getProgressive(),r=t.uid;n.set(r,{id:r,head:null,tail:null,threshold:t.getProgressiveThreshold(),progressiveEnabled:i&&!(t.preventIncremental&&t.preventIncremental()),blockIndex:-1,step:Math.round(i||700),count:0}),e._pipe(t,t.dataTask)})},t.prototype.prepareStageTasks=function(){var t=this._stageTaskMap,e=this.api.getModel(),n=this.api;ji(this._allHandlers,function(i){var r=t.get(i.uid)||t.set(i.uid,{});pr(!(i.reset&&i.overallReset),""),i.reset&&this._createSeriesStageTask(i,r,e,n),i.overallReset&&this._createOverallStageTask(i,r,e,n)},this)},t.prototype.prepareView=function(t,e,n,i){var r=t.renderTask,o=r.context;o.model=e,o.ecModel=n,o.api=i,r.__block=!t.incrementalPrepareRender,this._pipe(e,r)},t.prototype.performDataProcessorTasks=function(t,e){this._performStageTasks(this._dataProcessorHandlers,t,e,{block:!0})},t.prototype.performVisualTasks=function(t,e,n){this._performStageTasks(this._visualHandlers,t,e,n)},t.prototype._performStageTasks=function(t,e,n,i){i=i||{};var r=!1,o=this;function a(t,e){return t.setDirty&&(!t.dirtyMap||t.dirtyMap.get(e.__pipeline.id))}ji(t,function(t,s){if(!i.visualType||i.visualType===t.visualType){var l=o._stageTaskMap.get(t.uid),c=l.seriesTaskMap,u=l.overallTask;if(u){var d,h=u.agentStubMap;h.each(function(t){a(i,t)&&(t.dirty(),d=!0)}),d&&u.dirty(),o.updatePayload(u,n);var p=o.getPerformArgs(u,i.block);h.each(function(t){t.perform(p)}),u.perform(p)&&(r=!0)}else c&&c.each(function(s,l){a(i,s)&&s.dirty();var c=o.getPerformArgs(s,i.block);c.skip=!t.performRawSeries&&e.isSeriesFiltered(s.context.model),o.updatePayload(s,n),s.perform(c)&&(r=!0)})}}),this.unfinished=r||this.unfinished},t.prototype.performSeriesTasks=function(t){var e;t.eachSeries(function(t){e=t.dataTask.perform()||e}),this.unfinished=e||this.unfinished},t.prototype.plan=function(){this._pipelineMap.each(function(t){var e=t.tail;do{if(e.__block){t.blockIndex=e.__idxInPipeline;break}e=e.getUpstream()}while(e)})},t.prototype.updatePayload=function(t,e){"remain"!==e&&(t.context.payload=e)},t.prototype._createSeriesStageTask=function(t,e,n,i){var r=this,o=e.seriesTaskMap,a=e.seriesTaskMap=xr(),s=t.seriesType,l=t.getTargetSeries;function c(e){var s=e.uid,l=a.set(s,o&&o.get(s)||uy({plan:$_,reset:V_,count:q_}));l.context={model:e,ecModel:n,api:i,useClearVisual:t.isVisual&&!t.isLayout,plan:t.plan,reset:t.reset,scheduler:r},r._pipe(e,l)}t.createOnAllSeries?n.eachRawSeries(c):s?n.eachRawSeriesByType(s,c):l&&l(n,i).each(c)},t.prototype._createOverallStageTask=function(t,e,n,i){var r=this,o=e.overallTask=e.overallTask||uy({reset:z_});o.context={ecModel:n,api:i,overallReset:t.overallReset,scheduler:r};var a=o.agentStubMap,s=o.agentStubMap=xr(),l=t.seriesType,c=t.getTargetSeries,u=!0,d=!1;function h(t){var e=t.uid,n=s.set(e,a&&a.get(e)||(d=!0,uy({reset:H_,onDirty:F_})));n.context={model:t,overallProgress:u},n.agent=o,n.__block=u,r._pipe(t,n)}pr(!t.createOnAllSeries,""),l?n.eachRawSeriesByType(l,h):c?c(n,i).each(h):(u=!1,ji(n.getSeries(),h)),d&&o.dirty()},t.prototype._pipe=function(t,e){var n=t.uid,i=this._pipelineMap.get(n);!i.head&&(i.head=e),i.tail&&i.tail.pipe(e),i.tail=e,e.__idxInPipeline=i.count++,e.__pipeline=i},t.wrapStageHandler=function(t,e){return Qi(t)&&(t={overallReset:t,seriesType:U_(t)}),t.uid=ug("stageHandler"),e&&(t.visualType=e),t},t}();function z_(t){t.overallReset(t.ecModel,t.api,t.payload)}function H_(t){return t.overallProgress&&B_}function B_(){this.agent.dirty(),this.getDownstream().dirty()}function F_(){this.agent&&this.agent.dirty()}function $_(t){return t.plan?t.plan(t.model,t.ecModel,t.api,t.payload):null}function V_(t){t.useClearVisual&&t.data.clearAllVisual();var e=t.resetDefines=cc(t.reset(t.model,t.ecModel,t.api,t.payload));return e.length>1?qi(e,function(t,e){return j_(e)}):W_}var W_=j_(0);function j_(t){return function(e,n){var i=n.data,r=n.resetDefines[t];if(r&&r.dataEach)for(var o=e.start;o0&&u===r.length-c.length){var d=r.slice(0,u);"data"!==d&&(e.mainType=d,e[c.toLowerCase()]=t,s=!0)}}a.hasOwnProperty(r)&&(n[r]=t,s=!0),s||(i[r]=t)})}return{cptQuery:e,dataQuery:n,otherQuery:i}},t.prototype.filter=function(t,e){var n=this.eventInfo;if(!n)return!0;var i=n.targetEl,r=n.packedEvent,o=n.model,a=n.view;if(!o||!a)return!0;var s=e.cptQuery,l=e.dataQuery;return c(s,o,"mainType")&&c(s,o,"subType")&&c(s,o,"index","componentIndex")&&c(s,o,"name")&&c(s,o,"id")&&c(l,r,"name")&&c(l,r,"dataIndex")&&c(l,r,"dataType")&&(!a.filterForExposedEvent||a.filterForExposedEvent(t,e.otherQuery,i,r));function c(t,e,n,i){return null==t[n]||e[i||n]===t[n]}},t.prototype.afterTrigger=function(){this.eventInfo=null},t}(),rb=["symbol","symbolSize","symbolRotate","symbolOffset"],ob=rb.concat(["symbolKeepAspect"]),ab={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData();if(t.legendIcon&&n.setVisual("legendIcon",t.legendIcon),t.hasSymbolVisual){for(var i={},r={},o=!1,a=0;a=0&&Sb(l)?l:.5,t.createRadialGradient(a,s,0,a,s,l)}(t,e,n):function(t,e,n){var i=null==e.x?0:e.x,r=null==e.x2?1:e.x2,o=null==e.y?0:e.y,a=null==e.y2?0:e.y2;return e.global||(i=i*n.width+n.x,r=r*n.width+n.x,o=o*n.height+n.y,a=a*n.height+n.y),i=Sb(i)?i:0,r=Sb(r)?r:1,o=Sb(o)?o:0,a=Sb(a)?a:0,t.createLinearGradient(i,o,r,a)}(t,e,n),r=e.colorStops,o=0;o0&&(e=i.lineDash,n=i.lineWidth,e&&"solid"!==e&&n>0?"dashed"===e?[4*n,2*n]:"dotted"===e?[n]:er(e)?[e]:Ki(e)?e:null:null),o=i.lineDashOffset;if(r){var a=i.strokeNoScale&&t.getLineScale?t.getLineScale():1;a&&1!==a&&(r=qi(r,function(t){return t/a}),o/=a)}return[r,o]}var Ab=new Xu(!0);function Ib(t){var e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))}function Db(t){return"string"==typeof t&&"none"!==t}function Pb(t){var e=t.fill;return null!=e&&"none"!==e}function Lb(t,e){if(null!=e.fillOpacity&&1!==e.fillOpacity){var n=t.globalAlpha;t.globalAlpha=e.fillOpacity*e.opacity,t.fill(),t.globalAlpha=n}else t.fill()}function Eb(t,e){if(null!=e.strokeOpacity&&1!==e.strokeOpacity){var n=t.globalAlpha;t.globalAlpha=e.strokeOpacity*e.opacity,t.stroke(),t.globalAlpha=n}else t.stroke()}function Nb(t,e,n){var i=Vc(e.image,e.__image,n);if(jc(i)){var r=t.createPattern(i,e.repeat||"repeat");if("function"==typeof DOMMatrix&&r&&r.setTransform){var o=new DOMMatrix;o.translateSelf(e.x||0,e.y||0),o.rotateSelf(0,0,(e.rotation||0)*kr),o.scaleSelf(e.scaleX||1,e.scaleY||1),r.setTransform(o)}return r}}var Rb=["shadowBlur","shadowOffsetX","shadowOffsetY"],Ob=[["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]];function zb(t,e,n,i,r){var o=!1;if(!i&&e===(n=n||{}))return!1;if(i||e.opacity!==n.opacity){Fb(t,r),o=!0;var a=Math.max(Math.min(e.opacity,1),0);t.globalAlpha=isNaN(a)?uu.opacity:a}(i||e.blend!==n.blend)&&(o||(Fb(t,r),o=!0),t.globalCompositeOperation=e.blend||uu.blend);for(var s=0;s0&&t.unfinished);t.unfinished||this._zr.flush()}}},e.prototype.getDom=function(){return this._dom},e.prototype.getId=function(){return this.id},e.prototype.getZr=function(){return this._zr},e.prototype.isSSR=function(){return this._ssr},e.prototype.setOption=function(t,e,n){if(!this[ex])if(this._disposed)this.id;else{var i,r,o;if(nr(e)&&(n=e.lazyUpdate,i=e.silent,r=e.replaceMerge,o=e.transition,e=e.notMerge),this[ex]=!0,Ix(this),!this._model||e){var a=new hv(this._api),s=this._theme,l=this._model=new ov;l.scheduler=this._scheduler,l.ssr=this._ssr,l.init(null,null,null,s,this._locale,a)}this._model.setOption(t,{replaceMerge:r},Bx);var c={seriesTransition:o,optionChanged:!0};if(n)this[ix]={silent:i,updateParams:c},this[ex]=!1,this.getZr().wakeUp();else{try{ux(this),px.update.call(this,null,c)}catch(t){throw this[ix]=null,this[ex]=!1,t}this._ssr||this._zr.flush(),this[ix]=null,this[ex]=!1,vx.call(this,i),yx.call(this,i)}}},e.prototype.setTheme=function(t,e){if(!this[ex])if(this._disposed)this.id;else{var n=this._model;if(n){var i=e&&e.silent,r=null;this[ix]&&(null==i&&(i=this[ix].silent),r=this[ix].updateParams,this[ix]=null),this[ex]=!0,Ix(this);try{this._updateTheme(t),n.setTheme(this._theme),ux(this),px.update.call(this,{type:"setTheme"},r)}catch(t){throw this[ex]=!1,t}this[ex]=!1,vx.call(this,i),yx.call(this,i)}}},e.prototype._updateTheme=function(t){Ji(t)&&(t=$x[t]),t&&((t=zi(t))&&Ev(t,!0),this._theme=t)},e.prototype.getModel=function(){return this._model},e.prototype.getOption=function(){return this._model&&this._model.getOption()},e.prototype.getWidth=function(){return this._zr.getWidth()},e.prototype.getHeight=function(){return this._zr.getHeight()},e.prototype.getDevicePixelRatio=function(){return this._zr.painter.dpr||mi.hasGlobalWindow&&window.devicePixelRatio||1},e.prototype.getRenderedCanvas=function(t){return this.renderToCanvas(t)},e.prototype.renderToCanvas=function(t){return t=t||{},this._zr.painter.getRenderedCanvas({backgroundColor:t.backgroundColor||this._model.get("backgroundColor"),pixelRatio:t.pixelRatio||this.getDevicePixelRatio()})},e.prototype.renderToSVGString=function(t){return t=t||{},this._zr.painter.renderToString({useViewBox:t.useViewBox})},e.prototype.getSvgDataURL=function(){var t=this._zr;return ji(t.storage.getDisplayList(),function(t){t.stopAnimation(null,!0)}),t.painter.toDataURL()},e.prototype.getDataURL=function(t){if(!this._disposed){var e=(t=t||{}).excludeComponents,n=this._model,i=[],r=this;ji(e,function(t){n.eachComponent({mainType:t},function(t){var e=r._componentsMap[t.__viewId];e.group.ignore||(i.push(e),e.group.ignore=!0)})});var o="svg"===this._zr.painter.getType()?this.getSvgDataURL():this.renderToCanvas(t).toDataURL("image/"+(t&&t.type||"png"));return ji(i,function(t){t.group.ignore=!1}),o}this.id},e.prototype.getConnectedDataURL=function(t){if(!this._disposed){var e="svg"===t.type,n=this.group,i=Math.min,r=Math.max,o=1/0;if(jx[n]){var a=o,s=o,l=-1/0,c=-1/0,u=[],d=t&&t.pixelRatio||this.getDevicePixelRatio();ji(Wx,function(o,d){if(o.group===n){var h=e?o.getZr().painter.getSvgDom().innerHTML:o.renderToCanvas(zi(t)),p=o.getDom().getBoundingClientRect();a=i(p.left,a),s=i(p.top,s),l=r(p.right,l),c=r(p.bottom,c),u.push({dom:h,left:p.left,top:p.top})}});var h=(l*=d)-(a*=d),p=(c*=d)-(s*=d),f=wi.createCanvas(),g=zl(f,{renderer:e?"svg":"canvas"});if(g.resize({width:h,height:p}),e){var m="";return ji(u,function(t){var e=t.left-a,n=t.top-s;m+=''+t.dom+""}),g.painter.getSvgRoot().innerHTML=m,t.connectedBackgroundColor&&g.painter.setBackgroundColor(t.connectedBackgroundColor),g.refreshImmediately(),g.painter.toDataURL()}return t.connectedBackgroundColor&&g.add(new Td({shape:{x:0,y:0,width:h,height:p},style:{fill:t.connectedBackgroundColor}})),ji(u,function(t){var e=new bd({style:{x:t.left*d-a,y:t.top*d-s,image:t.dom}});g.add(e)}),g.refreshImmediately(),f.toDataURL("image/"+(t&&t.type||"png"))}return this.getDataURL(t)}this.id},e.prototype.convertToPixel=function(t,e,n){return fx(this,"convertToPixel",t,e,n)},e.prototype.convertToLayout=function(t,e,n){return fx(this,"convertToLayout",t,e,n)},e.prototype.convertFromPixel=function(t,e,n){return fx(this,"convertFromPixel",t,e,n)},e.prototype.containPixel=function(t,e){var n;if(!this._disposed)return ji(Sc(this._model,t),function(t,i){i.indexOf("Models")>=0&&ji(t,function(t){var r=t.coordinateSystem;if(r&&r.containPoint)n=n||!!r.containPoint(e);else if("seriesModels"===i){var o=this._chartsMap[t.__viewId];o&&o.containPoint&&(n=n||o.containPoint(e,t))}},this)},this),!!n;this.id},e.prototype.getVisual=function(t,e){var n=Sc(this._model,t,{defaultMainType:"series"}),i=n.seriesModel.getData(),r=n.hasOwnProperty("dataIndexInside")?n.dataIndexInside:n.hasOwnProperty("dataIndex")?i.indexOfRawIndex(n.dataIndex):null;return null!=r?function(t,e,n){switch(n){case"color":return t.getItemVisual(e,"style")[t.getVisual("drawType")];case"opacity":return t.getItemVisual(e,"style").opacity;case"symbol":case"symbolSize":case"liftZ":return t.getItemVisual(e,n)}}(i,r,e):function(t,e){switch(e){case"color":return t.getVisual("style")[t.getVisual("drawType")];case"opacity":return t.getVisual("style").opacity;case"symbol":case"symbolSize":case"liftZ":return t.getVisual(e)}}(i,e)},e.prototype.getViewOfComponentModel=function(t){return this._componentsMap[t.__viewId]},e.prototype.getViewOfSeriesModel=function(t){return this._chartsMap[t.__viewId]},e.prototype._initEvents=function(){var t=this;ji(Nx,function(e){var n=function(n){var i,r=t.getModel(),o=n.target;if("globalout"===e?i={}:o&&cb(o,function(t){var e=jd(t);if(e&&null!=e.dataIndex){var n=e.dataModel||r.getSeriesByIndex(e.seriesIndex);return i=n&&n.getDataParams(e.dataIndex,e.dataType,o)||{},!0}if(e.eventData)return i=Bi({},e.eventData),!0},!0),i){var a=i.componentType,s=i.componentIndex;"markLine"!==a&&"markPoint"!==a&&"markArea"!==a||(a="series",s=i.seriesIndex);var l=a&&null!=s&&r.getComponent(a,s),c=l&&t["series"===l.mainType?"_chartsMap":"_componentsMap"][l.__viewId];i.event=n,i.type=e,t._$eventProcessor.eventInfo={targetEl:o,packedEvent:i,model:l,view:c},t.trigger(e,i)}};n.zrEventfulCallAtLast=!0,t._zr.on(e,n,t)});var e=this._messageCenter;ji(zx,function(n,i){e.on(i,function(e){t.trigger(i,e)})}),function(t,e,n){t.on("selectchanged",function(t){var i=n.getModel();t.isFromClick?(lb("map","selectchanged",e,i,t),lb("pie","selectchanged",e,i,t)):"select"===t.fromAction?(lb("map","selected",e,i,t),lb("pie","selected",e,i,t)):"unselect"===t.fromAction&&(lb("map","unselected",e,i,t),lb("pie","unselected",e,i,t))})}(e,this,this._api)},e.prototype.isDisposed=function(){return this._disposed},e.prototype.clear=function(){this._disposed?this.id:this.setOption({series:[]},!0)},e.prototype.dispose=function(){if(this._disposed)this.id;else{this._disposed=!0,this.getDom()&&Tc(this.getDom(),Ux,"");var t=this,e=t._api,n=t._model;ji(t._componentsViews,function(t){t.dispose(n,e)}),ji(t._chartsViews,function(t){t.dispose(n,e)}),t._zr.dispose(),t._dom=t._model=t._chartsMap=t._componentsMap=t._chartsViews=t._componentsViews=t._scheduler=t._api=t._zr=t._throttledZrFlush=t._theme=t._coordSysMgr=t._messageCenter=null,delete Wx[t.id]}},e.prototype.resize=function(t){if(!this[ex])if(this._disposed)this.id;else{this._zr.resize(t);var e=this._model;if(this._loadingFX&&this._loadingFX.resize(),e){var n=e.resetOption("media"),i=t&&t.silent;this[ix]&&(null==i&&(i=this[ix].silent),n=!0,this[ix]=null),this[ex]=!0,Ix(this);try{n&&ux(this),px.update.call(this,{type:"resize",animation:Bi({duration:0},t&&t.animation)})}catch(t){throw this[ex]=!1,t}this[ex]=!1,vx.call(this,i),yx.call(this,i)}}},e.prototype.showLoading=function(t,e){if(this._disposed)this.id;else if(nr(t)&&(e=t,t=""),t=t||"default",this.hideLoading(),Vx[t]){var n=Vx[t](this._api,e),i=this._zr;this._loadingFX=n,i.add(n)}},e.prototype.hideLoading=function(){this._disposed?this.id:(this._loadingFX&&this._zr.remove(this._loadingFX),this._loadingFX=null)},e.prototype.makeActionFromEvent=function(t){var e=Bi({},t);return e.type=Ox[t.type],e},e.prototype.dispatchAction=function(t,e){if(this._disposed)this.id;else if(nr(e)||(e={silent:!!e}),Rx[t.type]&&this._model)if(this[ex])this._pendingActions.push(t);else{var n=e.silent;mx.call(this,t,n);var i=e.flush;i?this._zr.flush():!1!==i&&mi.browser.weChat&&this._throttledZrFlush(),vx.call(this,n),yx.call(this,n)}},e.prototype.updateLabelLayout=function(){Zb.trigger("series:layoutlabels",this._model,this._api,{updatedSeries:[]})},e.prototype.appendData=function(t){if(this._disposed)this.id;else{var e=t.seriesIndex;this.getModel().getSeriesByIndex(e).appendData(t),this._scheduler.unfinished=!0,this.getZr().wakeUp()}},e.internalField=function(){function t(t){t.clearColorPalette(),t.eachSeries(function(t){t.clearColorPalette()})}function e(t){for(var e=[],n=t.currentStates,i=0;i0?{duration:o,delay:i.get("delay"),easing:i.get("easing")}:null;n.eachRendered(function(t){if(t.states&&t.states.emphasis){if(nf(t))return;if(t instanceof gd&&function(t){var e=Gd(t);e.normalFill=t.style.fill,e.normalStroke=t.style.stroke;var n=t.states.select||{};e.selectFill=n.style&&n.style.fill||null,e.selectStroke=n.style&&n.style.stroke||null}(t),t.__dirty){var n=t.prevStates;n&&t.useStates(n)}if(r){t.stateTransition=a;var i=t.getTextContent(),o=t.getTextGuideLine();i&&(i.stateTransition=a),o&&(o.stateTransition=a)}t.__dirty&&e(t)}})}ux=function(t){var e=t._scheduler;e.restorePipelines(t._model),e.prepareStageTasks(),dx(t,!0),dx(t,!1),e.plan()},dx=function(t,e){for(var n=t._model,i=t._scheduler,r=e?t._componentsViews:t._chartsViews,o=e?t._componentsMap:t._chartsMap,a=t._zr,s=t._api,l=0;le.get("hoverLayerThreshold")&&!mi.node&&!mi.worker&&e.eachSeries(function(e){if(!e.preventUsingHoverLayer){var n=t._chartsMap[e.__viewId];n.__alive&&n.eachRendered(function(t){t.states.emphasis&&(t.states.emphasis.hoverLayer=!0)})}})}(t,e),Zb.trigger("series:afterupdate",e,o,s)},Tx=function(t){t[rx]=!0,t.getZr().wakeUp()},Ix=function(t){t[nx]=(t[nx]+1)%1e3},Ax=function(t){t[rx]&&(t.getZr().storage.traverse(function(t){nf(t)||e(t)}),t[rx]=!1)},kx=function(t){return new(function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return S(n,e),n.prototype.getCoordinateSystems=function(){return t._coordSysMgr.getCoordinateSystems()},n.prototype.getComponentByElement=function(e){for(;e;){var n=e.__ecComponentInfo;if(null!=n)return t._model.getComponent(n.mainType,n.index);e=e.parent}},n.prototype.enterEmphasis=function(e,n){yh(e,n),Tx(t)},n.prototype.leaveEmphasis=function(e,n){_h(e,n),Tx(t)},n.prototype.enterBlur=function(e){!function(t){hh(t,sh)}(e),Tx(t)},n.prototype.leaveBlur=function(e){bh(e),Tx(t)},n.prototype.enterSelect=function(e){xh(e),Tx(t)},n.prototype.leaveSelect=function(e){wh(e),Tx(t)},n.prototype.getModel=function(){return t.getModel()},n.prototype.getViewOfComponentModel=function(e){return t.getViewOfComponentModel(e)},n.prototype.getViewOfSeriesModel=function(e){return t.getViewOfSeriesModel(e)},n.prototype.getMainProcessVersion=function(){return t[nx]},n}(uv))(t)},Mx=function(t){function e(t,e){for(var n=0;n=0)){tw.push(n);var o=O_.wrapStageHandler(n,r);o.__prio=e,o.__raw=n,t.push(o)}}function nw(t,e){Vx[t]=e}var iw=function(t){var e=(t=zi(t)).type;e||ac("");var n=e.split(":");2!==n.length&&ac("");var i=!1;"echarts"===n[0]&&(e=n[1],i=!0),t.__isBuiltIn=i,by.set(e,t)};function rw(t,e,n,i){return{eventContent:{selected:Ih(n),isFromClick:e.isFromClick||!1}}}function ow(t){return null==t?0:t.length||1}function aw(t){return t}Jx(Qb,P_),Jx(Jb,E_),Jx(Jb,N_),Jx(Qb,ab),Jx(Jb,sb),Jx(7e3,function(t,e){t.eachRawSeries(function(n){if(!t.isSeriesFiltered(n)){var i=n.getData();i.hasItemVisual()&&i.each(function(t){var n=i.getItemVisual(t,"decal");n&&(i.ensureUniqueItemVisual(t,"style").decal=Ub(n,e))});var r=i.getVisual("decal");if(r)i.getVisual("style").decal=Ub(r,e)}})}),Yx(Ev),Zx(900,function(t){var e=xr();t.eachSeries(function(t){var n=t.get("stack");if(n){var i=e.get(n)||e.set(n,[]),r=t.getData(),o={stackResultDimension:r.getCalculationInfo("stackResultDimension"),stackedOverDimension:r.getCalculationInfo("stackedOverDimension"),stackedDimension:r.getCalculationInfo("stackedDimension"),stackedByDimension:r.getCalculationInfo("stackedByDimension"),isStackedByIndex:r.getCalculationInfo("isStackedByIndex"),data:r,seriesModel:t};if(!o.stackedDimension||!o.isStackedByIndex&&!o.stackedByDimension)return;i.push(o)}}),e.each(function(t){0!==t.length&&("seriesDesc"===(t[0].seriesModel.get("stackOrder")||"seriesAsc")&&t.reverse(),ji(t,function(e,n){e.data.setCalculationInfo("stackedOnSeries",n>0?t[n-1].seriesModel:null)}),function(t){ji(t,function(e,n){var i=[],r=[NaN,NaN],o=[e.stackResultDimension,e.stackedOverDimension],a=e.data,s=e.isStackedByIndex,l=e.seriesModel.get("stackStrategy")||"samesign";a.modify(o,function(o,c,u){var d,h,p=a.get(e.stackedDimension,u);if(isNaN(p))return r;s?h=a.getRawIndex(u):d=a.get(e.stackedByDimension,u);for(var f=NaN,g=n-1;g>=0;g--){var m=t[g];if(s||(h=m.data.rawIndexOf(m.stackedByDimension,d)),h>=0){var v=m.data.getByRawIndex(m.stackResultDimension,h);if("all"===l||"positive"===l&&v>0||"negative"===l&&v<0||"samesign"===l&&p>=0&&v>0||"samesign"===l&&p<=0&&v<0){p=Gl(p,v),f=v;break}}}return i[0]=p,i[1]=f,i})})}(t))})}),nw("default",function(t,e){Fi(e=e||{},{text:"loading",textColor:Tm.color.primary,fontSize:12,fontWeight:"normal",fontStyle:"normal",fontFamily:"sans-serif",maskColor:"rgba(255,255,255,0.8)",showSpinner:!0,color:Tm.color.theme[0],spinnerRadius:10,lineWidth:5,zlevel:0});var n=new Ll,i=new Td({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4});n.add(i);var r,o=new Pd({style:{text:e.text,fill:e.textColor,fontSize:e.fontSize,fontWeight:e.fontWeight,fontStyle:e.fontStyle,fontFamily:e.fontFamily},zlevel:e.zlevel,z:10001}),a=new Td({style:{fill:"none"},textContent:o,textConfig:{position:"right",distance:10},zlevel:e.zlevel,z:10001});return n.add(a),e.showSpinner&&((r=new Op({shape:{startAngle:-R_/2,endAngle:-R_/2+.1,r:e.spinnerRadius},style:{stroke:e.color,lineCap:"round",lineWidth:e.lineWidth},zlevel:e.zlevel,z:10001})).animateShape(!0).when(1e3,{endAngle:3*R_/2}).start("circularInOut"),r.animateShape(!0).when(1e3,{startAngle:3*R_/2}).delay(300).start("circularInOut"),n.add(r)),n.resize=function(){var n=o.getBoundingRect().width,s=e.showSpinner?e.spinnerRadius:0,l=(t.getWidth()-2*s-(e.showSpinner&&n?10:0)-n)/2-(e.showSpinner&&n?0:5+n/2)+(e.showSpinner?0:n/2)+(n?0:s),c=t.getHeight()/2;e.showSpinner&&r.setShape({cx:l,cy:c}),a.setShape({x:l-s,y:c-s,width:2*s,height:2*s}),i.setShape({x:0,y:0,width:t.getWidth(),height:t.getHeight()})},n.resize(),n}),Qx({type:Kd,event:Kd,update:Kd},Cr),Qx({type:Qd,event:Qd,update:Qd},Cr),Qx({type:Jd,event:nh,update:Jd,action:Cr,refineEvent:rw,publishNonRefinedEvent:!0}),Qx({type:th,event:nh,update:th,action:Cr,refineEvent:rw,publishNonRefinedEvent:!0}),Qx({type:eh,event:nh,update:eh,action:Cr,refineEvent:rw,publishNonRefinedEvent:!0}),Xx("default",{}),Xx("dark",nb);var sw=function(){function t(t,e,n,i,r,o){this._old=t,this._new=e,this._oldKeyGetter=n||aw,this._newKeyGetter=i||aw,this.context=r,this._diffModeMultiple="multiple"===o}return t.prototype.add=function(t){return this._add=t,this},t.prototype.update=function(t){return this._update=t,this},t.prototype.updateManyToOne=function(t){return this._updateManyToOne=t,this},t.prototype.updateOneToMany=function(t){return this._updateOneToMany=t,this},t.prototype.updateManyToMany=function(t){return this._updateManyToMany=t,this},t.prototype.remove=function(t){return this._remove=t,this},t.prototype.execute=function(){this[this._diffModeMultiple?"_executeMultiple":"_executeOneToOne"]()},t.prototype._executeOneToOne=function(){var t=this._old,e=this._new,n={},i=new Array(t.length),r=new Array(e.length);this._initIndexMap(t,null,i,"_oldKeyGetter"),this._initIndexMap(e,n,r,"_newKeyGetter");for(var o=0;o1){var c=s.shift();1===s.length&&(n[a]=s[0]),this._update&&this._update(c,o)}else 1===l?(n[a]=null,this._update&&this._update(s,o)):this._remove&&this._remove(o)}this._performRestAdd(r,n)},t.prototype._executeMultiple=function(){var t=this._old,e=this._new,n={},i={},r=[],o=[];this._initIndexMap(t,n,r,"_oldKeyGetter"),this._initIndexMap(e,i,o,"_newKeyGetter");for(var a=0;a1&&1===d)this._updateManyToOne&&this._updateManyToOne(c,l),i[s]=null;else if(1===u&&d>1)this._updateOneToMany&&this._updateOneToMany(c,l),i[s]=null;else if(1===u&&1===d)this._update&&this._update(c,l),i[s]=null;else if(u>1&&d>1)this._updateManyToMany&&this._updateManyToMany(c,l),i[s]=null;else if(u>1)for(var h=0;h1)for(var a=0;a30}var yw,_w,bw,xw,ww,Sw,Cw,kw=nr,Mw=qi,Tw="undefined"==typeof Int32Array?Array:Int32Array,Aw=["hasItemOption","_nameList","_idList","_invertedIndicesMap","_dimSummary","userOutput","_rawData","_dimValueGetter","_nameDimIdx","_idDimIdx","_nameRepeatCount"],Iw=["_approximateExtent"],Dw=function(){function t(t,e){var n;this.type="list",this._dimOmitted=!1,this._nameList=[],this._idList=[],this._visual={},this._layout={},this._itemVisuals=[],this._itemLayouts=[],this._graphicEls=[],this._approximateExtent={},this._calculationInfo={},this.hasItemOption=!1,this.TRANSFERABLE_METHODS=["cloneShallow","downSample","minmaxDownSample","lttbDownSample","map"],this.CHANGABLE_METHODS=["filterSelf","selectRange"],this.DOWNSAMPLE_METHODS=["downSample","minmaxDownSample","lttbDownSample"];var i=!1;fw(t)?(n=t.dimensions,this._dimOmitted=t.isDimensionOmitted(),this._schema=t):(i=!0,n=t),n=n||["x","y"];for(var r={},o=[],a={},s=!1,l={},c=0;c=e)){var n=this._store.getProvider();this._updateOrdinalMeta();var i=this._nameList,r=this._idList;if(n.getSource().sourceFormat===zm&&!n.pure)for(var o=[],a=t;a0},t.prototype.ensureUniqueItemVisual=function(t,e){var n=this._itemVisuals,i=n[t];i||(i=n[t]={});var r=i[e];return null==r&&(Ki(r=this.getVisual(e))?r=r.slice():kw(r)&&(r=Bi({},r)),i[e]=r),r},t.prototype.setItemVisual=function(t,e,n){var i=this._itemVisuals[t]||{};this._itemVisuals[t]=i,kw(e)?Bi(i,e):i[e]=n},t.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},t.prototype.setLayout=function(t,e){kw(t)?Bi(this._layout,t):this._layout[t]=e},t.prototype.getLayout=function(t){return this._layout[t]},t.prototype.getItemLayout=function(t){return this._itemLayouts[t]},t.prototype.setItemLayout=function(t,e,n){this._itemLayouts[t]=n?Bi(this._itemLayouts[t]||{},e):e},t.prototype.clearItemLayouts=function(){this._itemLayouts.length=0},t.prototype.setItemGraphicEl=function(t,e){!function(t,e,n,i){if(i){var r=jd(i);r.dataIndex=n,r.dataType=e,r.seriesIndex=t,r.ssrType="chart","group"===i.type&&i.traverse(function(i){var r=jd(i);r.seriesIndex=t,r.dataIndex=n,r.dataType=e,r.ssrType="chart"})}}(this.hostModel&&this.hostModel.seriesIndex,this.dataType,t,e),this._graphicEls[t]=e},t.prototype.getItemGraphicEl=function(t){return this._graphicEls[t]},t.prototype.eachItemGraphicEl=function(t,e){ji(this._graphicEls,function(n,i){n&&t&&t.call(e,n,i)})},t.prototype.cloneShallow=function(e){return e||(e=new t(this._schema?this._schema:Mw(this.dimensions,this._getDimInfo,this),this.hostModel)),ww(e,this),e._store=this._store,e},t.prototype.wrapMethod=function(t,e){var n=this[t];Qi(n)&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(t),this[t]=function(){var t=n.apply(this,arguments);return e.apply(this,[t].concat(dr(arguments)))})},t.internalField=(yw=function(t){var e=t._invertedIndicesMap;ji(e,function(n,i){var r=t._dimInfos[i],o=r.ordinalMeta,a=t._store;if(o){n=e[i]=new Tw(o.categories.length);for(var s=0;s1&&(s+="__ec__"+c),i[e]=s}})),t}();function Pw(t,e){$v(t)||(t=Wv(t));var n=(e=e||{}).coordDimensions||[],i=e.dimensionsDefine||t.dimensionsDefine||[],r=xr(),o=[],a=function(t,e,n,i){var r=Math.max(t.dimensionsDetectedCount||1,e.length,n.length,i||0);return ji(e,function(t){var e;nr(t)&&(e=t.dimsDef)&&(r=Math.max(r,e.length))}),r}(t,n,i,e.dimensionsCount),s=e.canOmitUnusedDimensions&&vw(a),l=i===t.dimensionsDefine,c=l?mw(t):gw(i),u=e.encodeDefine;!u&&e.encodeDefaulter&&(u=e.encodeDefaulter(t,a));for(var d=xr(u),h=new Ty(a),p=0;p0&&(i.name=r+(o-1)),o++,e.set(r,o)}}(o),new pw({source:t,dimensions:o,fullDimensionCount:a,dimensionOmitted:s})}function Lw(t,e,n){if(n||e.hasKey(t)){for(var i=0;e.hasKey(t+i);)i++;t+=i}return e.set(t,!0),t}var Ew=function(t){this.coordSysDims=[],this.axisMap=xr(),this.categoryAxisMap=xr(),this.coordSysName=t};var Nw={cartesian2d:function(t,e,n,i){var r=t.getReferringComponents("xAxis",kc).models[0],o=t.getReferringComponents("yAxis",kc).models[0];e.coordSysDims=["x","y"],n.set("x",r),n.set("y",o),Rw(r)&&(i.set("x",r),e.firstCategoryDimIndex=0),Rw(o)&&(i.set("y",o),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},singleAxis:function(t,e,n,i){var r=t.getReferringComponents("singleAxis",kc).models[0];e.coordSysDims=["single"],n.set("single",r),Rw(r)&&(i.set("single",r),e.firstCategoryDimIndex=0)},polar:function(t,e,n,i){var r=t.getReferringComponents("polar",kc).models[0],o=r.findAxisModel("radiusAxis"),a=r.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],n.set("radius",o),n.set("angle",a),Rw(o)&&(i.set("radius",o),e.firstCategoryDimIndex=0),Rw(a)&&(i.set("angle",a),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},geo:function(t,e,n,i){e.coordSysDims=["lng","lat"]},parallel:function(t,e,n,i){var r=t.ecModel,o=r.getComponent("parallel",t.get("parallelIndex")),a=e.coordSysDims=o.dimensions.slice();ji(o.parallelAxisIndex,function(t,o){var s=r.getComponent("parallelAxis",t),l=a[o];n.set(l,s),Rw(s)&&(i.set(l,s),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=o))})},matrix:function(t,e,n,i){var r=t.getReferringComponents("matrix",kc).models[0];e.coordSysDims=["x","y"];var o=r.getDimensionModel("x"),a=r.getDimensionModel("y");n.set("x",o),n.set("y",a),i.set("x",o),i.set("y",a)}};function Rw(t){return"category"===t.get("type")}function Ow(t,e,n){var i,r,o,a=(n=n||{}).byIndex,s=n.stackedCoordDimension;!function(t){return!fw(t.schema)}(e)?(r=e.schema,i=r.dimensions,o=e.store):i=e;var l,c,u,d,h=!(!t||!t.get("stack"));if(ji(i,function(t,e){Ji(t)&&(i[e]=t={name:t}),h&&!t.isExtraCoord&&(a||l||!t.ordinalMeta||(l=t),c||"ordinal"===t.type||"time"===t.type||s&&s!==t.coordDim||(c=t))}),!c||a||l||(a=!0),c){u="__\0ecstackresult_"+t.id,d="__\0ecstackedover_"+t.id,l&&(l.createInvertedIndices=!0);var p=c.coordDim,f=c.type,g=0;ji(i,function(t){t.coordDim===p&&g++});var m={name:u,coordDim:p,coordDimIndex:g,type:f,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length},v={name:d,coordDim:d,coordDimIndex:g+1,type:f,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length+1};r?(o&&(m.storeDimIndex=o.ensureCalculationDimension(d,f),v.storeDimIndex=o.ensureCalculationDimension(u,f)),r.appendCalculationDimension(m),r.appendCalculationDimension(v)):(i.push(m),i.push(v))}return{stackedDimension:c&&c.name,stackedByDimension:l&&l.name,isStackedByIndex:a,stackedOverDimension:d,stackResultDimension:u}}function zw(t,e){return!!e&&e===t.getCalculationInfo("stackedDimension")}function Hw(t,e,n){n=n||{};var i,r,o=e.getSourceManager();r=(i=o.getSource()).sourceFormat===zm;var a=function(t){var e=t.get("coordinateSystem"),n=new Ew(e),i=Nw[e];if(i)return i(t,n,n.axisMap,n.categoryAxisMap),n}(e),s=function(t,e){var n,i=t.get("coordinateSystem"),r=sm.get(i);return e&&e.coordSysDims&&(n=qi(e.coordSysDims,function(t){var n={name:t},i=e.axisMap.get(t);if(i){var r=i.get("type");n.type=function(t){return"category"===t?"ordinal":"time"===t?"time":"float"}(r)}return n})),n||(n=r&&(r.getDimensionsInfo?r.getDimensionsInfo():r.dimensions.slice())||["x","y"]),n}(e,a),l=n.useEncodeDefaulter,c=Qi(l)?l:l?Zi(Ym,s,e):null,u=Pw(i,{coordDimensions:s,generateCoord:n.generateCoord,encodeDefine:e.getEncode(),encodeDefaulter:c,canOmitUnusedDimensions:!r}),d=function(t,e,n){var i,r;return n&&ji(t,function(t,o){var a=t.coordDim,s=n.categoryAxisMap.get(a);s&&(null==i&&(i=o),t.ordinalMeta=s.getOrdinalMeta(),e&&(t.createInvertedIndices=!0)),null!=t.otherDims.itemName&&(r=!0)}),r||null==i||(t[i].otherDims.itemName=0),i}(u.dimensions,n.createInvertedIndices,a),h=r?null:o.getSharedDataStore(u),p=Ow(e,{schema:u,store:h}),f=new Dw(u,e);f.setCalculationInfo(p);var g=null!=d&&function(t){if(t.sourceFormat===zm){var e=function(t){var e=0;for(;er&&(a=o.interval=r);var s=o.intervalPrecision=Vw(a);return function(t,e){!isFinite(t[0])&&(t[0]=e[0]),!isFinite(t[1])&&(t[1]=e[1]),Ww(t,0,e),Ww(t,1,e),t[0]>t[1]&&(t[0]=t[1])}(o.niceTickExtent=[ql(Math.ceil(t[0]/a)*a,s),ql(Math.floor(t[1]/a)*a,s)],t),o}function $w(t){var e=Math.pow(10,Ql(t)),n=t/e;return n?2===n?n=3:3===n?n=5:n*=2:n=1,ql(n*e)}function Vw(t){return Ul(t)+2}function Ww(t,e,n){t[e]=Math.max(Math.min(t[e],n[1]),n[0])}function jw(t,e){return t>=e[0]&&t<=e[1]}var qw=function(){function t(){this.normalize=Uw,this.scale=Gw}return t.prototype.updateMethods=function(t){t.hasBreaks()?(this.normalize=Yi(t.normalize,t),this.scale=Yi(t.scale,t)):(this.normalize=Uw,this.scale=Gw)},t}();function Uw(t,e){return e[1]===e[0]?.5:(t-e[0])/(e[1]-e[0])}function Gw(t,e){return t*(e[1]-e[0])+e[0]}function Xw(t,e,n){var i=Math.log(t);return[Math.log(n?e[0]:Math.max(0,e[0]))/i,Math.log(n?e[1]:Math.max(0,e[1]))/i]}var Yw=function(){function t(t){this._calculator=new qw,this._setting=t||{},this._extent=[1/0,-1/0]}return t.prototype.getSetting=function(t){return this._setting[t]},t.prototype._innerUnionExtent=function(t){var e=this._extent;this._innerSetExtent(t[0]e[1]?t[1]:e[1])},t.prototype.unionExtentFromData=function(t,e){this._innerUnionExtent(t.getApproximateExtent(e))},t.prototype.getExtent=function(){return this._extent.slice()},t.prototype.setExtent=function(t,e){this._innerSetExtent(t,e)},t.prototype._innerSetExtent=function(t,e){var n=this._extent;isNaN(t)||(n[0]=t),isNaN(e)||(n[1]=e),this._brkCtx&&this._brkCtx.update(n)},t.prototype.setBreaksFromOption=function(t){},t.prototype._innerSetBreak=function(t){this._brkCtx&&(this._brkCtx.setBreaks(t),this._calculator.updateMethods(this._brkCtx),this._brkCtx.update(this._extent))},t.prototype._innerGetBreaks=function(){return this._brkCtx?this._brkCtx.breaks:[]},t.prototype.hasBreaks=function(){return!!this._brkCtx&&this._brkCtx.hasBreaks()},t.prototype._getExtentSpanWithBreaks=function(){return this._brkCtx&&this._brkCtx.hasBreaks()?this._brkCtx.getExtentSpan():this._extent[1]-this._extent[0]},t.prototype.isInExtentRange=function(t){return this._extent[0]<=t&&this._extent[1]>=t},t.prototype.isBlank=function(){return this._isBlank},t.prototype.setBlank=function(t){this._isBlank=t},t}();Oc(Yw);var Zw=0,Kw=function(){function t(t){this.categories=t.categories||[],this._needCollect=t.needCollect,this._deduplication=t.deduplication,this.uid=++Zw,this._onCollect=t.onCollect}return t.createByAxisModel=function(e){var n=e.option,i=n.data,r=i&&qi(i,Qw);return new t({categories:r,needCollect:!r,deduplication:!1!==n.dedplication})},t.prototype.getOrdinal=function(t){return this._getOrCreateMap().get(t)},t.prototype.parseAndCollect=function(t){var e,n=this._needCollect;if(!Ji(t)&&!n)return t;if(n&&!this._deduplication)return e=this.categories.length,this.categories[e]=t,this._onCollect&&this._onCollect(t,e),e;var i=this._getOrCreateMap();return null==(e=i.get(t))&&(n?(e=this.categories.length,this.categories[e]=t,i.set(t,e),this._onCollect&&this._onCollect(t,e)):e=NaN),e},t.prototype._getOrCreateMap=function(){return this._map||(this._map=xr(this.categories))},t}();function Qw(t){return nr(t)&&null!=t.value?t.value:t+""}var Jw=function(t){function e(e){var n=t.call(this,e)||this;n.type="ordinal";var i=n.getSetting("ordinalMeta");return i||(i=new Kw({})),Ki(i)&&(i=new Kw({categories:qi(i,function(t){return nr(t)?t.value:t})})),n._ordinalMeta=i,n._extent=n.getSetting("extent")||[0,i.categories.length-1],n}return S(e,t),e.prototype.parse=function(t){return null==t?NaN:Ji(t)?this._ordinalMeta.getOrdinal(t):Math.round(t)},e.prototype.contain=function(t){return jw(t,this._extent)&&t>=0&&t=0&&t=0&&t=t},e.prototype.getOrdinalMeta=function(){return this._ordinalMeta},e.prototype.calcNiceTicks=function(){},e.prototype.calcNiceExtent=function(){},e.type="ordinal",e}(Yw);Yw.registerClass(Jw);var tS=ql,eS=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="interval",e._interval=0,e._intervalPrecision=2,e}return S(e,t),e.prototype.parse=function(t){return null==t||""===t?NaN:Number(t)},e.prototype.contain=function(t){return jw(t,this._extent)},e.prototype.normalize=function(t){return this._calculator.normalize(t,this._extent)},e.prototype.scale=function(t){return this._calculator.scale(t,this._extent)},e.prototype.getInterval=function(){return this._interval},e.prototype.setInterval=function(t){this._interval=t,this._niceExtent=this._extent.slice(),this._intervalPrecision=Vw(t)},e.prototype.getTicks=function(t){t=t||{};var e=this._interval,n=this._extent,i=this._niceExtent,r=this._intervalPrecision,o=[];if(!e)return o;t.breakTicks;n[0]=0&&(s=tS(s+l*e,r))}if(o.length>0&&s===o[o.length-1].value)break;if(o.length>1e4)return[]}var c=o.length?o[o.length-1].value:i[1];return n[1]>c&&(t.expandToNicedExtent?o.push({value:tS(c+e,r)}):o.push({value:n[1]})),t.breakTicks,o},e.prototype.getMinorTicks=function(t){for(var e=this.getTicks({expandToNicedExtent:!0}),n=[],i=this.getExtent(),r=1;ri[0]&&d0&&(o=null===o?s:Math.min(o,s))}n[i]=o}}return n}(t),n=[];return ji(t,function(t){var i,r=t.coordinateSystem.getBaseAxis(),o=r.getExtent();if("category"===r.type)i=r.getBandWidth();else if("value"===r.type||"time"===r.type){var a=r.dim+"_"+r.index,s=e[a],l=Math.abs(o[1]-o[0]),c=r.scale.getExtent(),u=Math.abs(c[1]-c[0]);i=s?l/u*s:l}else{var d=t.getData();i=Math.abs(o[1]-o[0])/d.count()}var h=Wl(t.get("barWidth"),i),p=Wl(t.get("barMaxWidth"),i),f=Wl(t.get("barMinWidth")||(function(t){return t.pipelineContext&&t.pipelineContext.large}(t)?.5:1),i),g=t.get("barGap"),m=t.get("barCategoryGap"),v=t.get("defaultBarGap");n.push({bandWidth:i,barWidth:h,barMaxWidth:p,barMinWidth:f,barGap:g,barCategoryGap:m,defaultBarGap:v,axisKey:aS(r),stackId:oS(t)})}),function(t){var e={};ji(t,function(t,n){var i=t.axisKey,r=t.bandWidth,o=e[i]||{bandWidth:r,remainedWidth:r,autoWidthCount:0,categoryGap:null,gap:t.defaultBarGap||0,stacks:{}},a=o.stacks;e[i]=o;var s=t.stackId;a[s]||o.autoWidthCount++,a[s]=a[s]||{width:0,maxWidth:0};var l=t.barWidth;l&&!a[s].width&&(a[s].width=l,l=Math.min(o.remainedWidth,l),o.remainedWidth-=l);var c=t.barMaxWidth;c&&(a[s].maxWidth=c);var u=t.barMinWidth;u&&(a[s].minWidth=u);var d=t.barGap;null!=d&&(o.gap=d);var h=t.barCategoryGap;null!=h&&(o.categoryGap=h)});var n={};return ji(e,function(t,e){n[e]={};var i=t.stacks,r=t.bandWidth,o=t.categoryGap;if(null==o){var a=Xi(i).length;o=Math.max(35-4*a,15)+"%"}var s=Wl(o,r),l=Wl(t.gap,1),c=t.remainedWidth,u=t.autoWidthCount,d=(c-s)/(u+(u-1)*l);d=Math.max(d,0),ji(i,function(t){var e=t.maxWidth,n=t.minWidth;if(t.width){i=t.width;e&&(i=Math.min(i,e)),n&&(i=Math.max(i,n)),t.width=i,c-=i+l*i,u--}else{var i=d;e&&ei&&(i=n),i!==d&&(t.width=i,c-=i+l*i,u--)}}),d=(c-s)/(u+(u-1)*l),d=Math.max(d,0);var h,p=0;ji(i,function(t,e){t.width||(t.width=d),h=t,p+=t.width*(1+l)}),h&&(p-=h.width*l);var f=-p/2;ji(i,function(t,i){n[e][i]=n[e][i]||{bandWidth:r,offset:f,width:t.width},f+=t.width*(1+l)})}),n}(n)}var lS=function(t){function e(e){var n=t.call(this,e)||this;return n.type="time",n}return S(e,t),e.prototype.getLabel=function(t){var e=this.getSetting("useUTC");return Ng(t.value,Tg[function(t){switch(t){case"year":case"month":return"day";case"millisecond":return"millisecond";default:return"second"}}(Lg(this._minLevelUnit))]||Tg.second,e,this.getSetting("locale"))},e.prototype.getFormattedLabel=function(t,e,n){var i=this.getSetting("useUTC");return function(t,e,n,i,r){var o=null;if(Ji(n))o=n;else if(Qi(n)){var a={time:t.time,level:t.time.level},s=null;s&&s.makeAxisLabelFormatterParamBreak(a,t.break),o=n(t.value,e,a)}else{var l=t.time;if(l){var c=n[l.lowerTimeUnit][l.upperTimeUnit];o=c[Math.min(l.level,c.length-1)]||""}else{var u=Rg(t.value,r);o=n[u][u][0]}}return Ng(new Date(t.value),o,r,i)}(t,e,n,this.getSetting("locale"),i)},e.prototype.getTicks=function(t){var e=this._interval,n=this._extent,i=[];if(!e)return i;var r=this.getSetting("useUTC"),o=Rg(n[1],r);i.push({value:n[0],time:{level:0,upperTimeUnit:o,lowerTimeUnit:o}});var a=function(t,e,n,i,r,o){var a=1e4,s=Ig,l=0;function c(t,e,n,r,s,c,u){for(var d=function(t,e){var n=new Date(0);n[t](1);var i=n.getTime();n[t](1+e);var r=n.getTime()-i;return function(t,e){return Math.max(0,Math.round((e-t)/r))}}(s,t),h=e,p=new Date(h);ha));)if(p[s](p[r]()+t),h=p.getTime(),o){var f=o.calcNiceTickMultiple(h,d);f>0&&(p[s](p[r]()+f*t),h=p.getTime())}u.push({value:h,notAdd:!0})}function u(t,r,o){var a=[],s=!r.length;if(!function(t,e,n,i){return Og(new Date(e),t,i).getTime()===Og(new Date(n),t,i).getTime()}(Lg(t),i[0],i[1],n)){s&&(r=[{value:gS(i[0],t,n)},{value:i[1]}]);for(var l=0;l=i[0]&&u<=i[1]&&c(h,u,d,p,f,g,a),"year"===t&&o.length>1&&0===l&&o.unshift({value:o[0].value-h})}}for(l=0;l=i[0]&&_<=i[1]&&p++)}var b=r/e;if(p>1.5*b&&f>b/1.5)break;if(d.push(v),p>b||t===s[g])break}h=[]}}var x=Gi(qi(d,function(t){return Gi(t,function(t){return t.value>=i[0]&&t.value<=i[1]&&!t.notAdd})}),function(t){return t.length>0}),w=[],S=x.length-1;for(g=0;gn&&(this._approxInterval=n);var r=cS.length,o=Math.min(function(t,e,n,i){for(;n>>1;t[r][1]16?16:t>7.5?7:t>3.5?4:t>1.5?2:1}function dS(t){return(t/=2592e6)>6?6:t>3?3:t>2?2:1}function hS(t){return(t/=xg)>12?12:t>6?6:t>3.5?4:t>2?2:1}function pS(t,e){return(t/=e?bg:_g)>30?30:t>20?20:t>15?15:t>10?10:t>5?5:t>2?2:1}function fS(t){return Jl(t)}function gS(t,e,n){var i=Math.max(0,$i(Ag,e)-1);return Og(new Date(t),Ag[i],n).getTime()}Yw.registerClass(lS);var mS=ql,vS=Math.floor,yS=Math.ceil,_S=Math.pow,bS=Math.log,xS=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="log",e.base=10,e._originalScale=new eS,e}return S(e,t),e.prototype.getTicks=function(e){e=e||{};var n=this._extent.slice(),i=this._originalScale.getExtent(),r=t.prototype.getTicks.call(this,e),o=this.base;return this._originalScale._innerGetBreaks(),qi(r,function(t){var e=t.value,r=null,a=_S(o,e);return e===n[0]&&this._fixMin?r=i[0]:e===n[1]&&this._fixMax&&(r=i[1]),null!=r&&(a=wS(a,r)),{value:a,break:void 0}},this)},e.prototype._getNonTransBreaks=function(){return this._originalScale._innerGetBreaks()},e.prototype.setExtent=function(e,n){this._originalScale.setExtent(e,n);var i=Xw(this.base,[e,n]);t.prototype.setExtent.call(this,i[0],i[1])},e.prototype.getExtent=function(){var e=this.base,n=t.prototype.getExtent.call(this);n[0]=_S(e,n[0]),n[1]=_S(e,n[1]);var i=this._originalScale.getExtent();return this._fixMin&&(n[0]=wS(n[0],i[0])),this._fixMax&&(n[1]=wS(n[1],i[1])),n},e.prototype.unionExtentFromData=function(t,e){this._originalScale.unionExtentFromData(t,e);var n=Xw(this.base,t.getApproximateExtent(e),!0);this._innerUnionExtent(n)},e.prototype.calcNiceTicks=function(t){t=t||10;var e=this._extent.slice(),n=this._getExtentSpanWithBreaks();if(isFinite(n)&&!(n<=0)){var i,r=(i=n,Math.pow(10,Ql(i)));for(t/n*r<=.5&&(r*=10);!isNaN(r)&&Math.abs(r)<1&&Math.abs(r)>0;)r*=10;var o=[mS(yS(e[0]/r)*r),mS(vS(e[1]/r)*r)];this._interval=r,this._intervalPrecision=Vw(r),this._niceExtent=o}},e.prototype.calcNiceExtent=function(e){t.prototype.calcNiceExtent.call(this,e),this._fixMin=e.fixMin,this._fixMax=e.fixMax},e.prototype.contain=function(e){return e=bS(e)/bS(this.base),t.prototype.contain.call(this,e)},e.prototype.normalize=function(e){return e=bS(e)/bS(this.base),t.prototype.normalize.call(this,e)},e.prototype.scale=function(e){return e=t.prototype.scale.call(this,e),_S(this.base,e)},e.prototype.setBreaksFromOption=function(t){},e.type="log",e}(eS);function wS(t,e){return mS(t,Ul(e))}Yw.registerClass(xS);var SS=function(){function t(t,e,n){this._prepareParams(t,e,n)}return t.prototype._prepareParams=function(t,e,n){n[1]0&&s>0&&!l&&(a=0),a<0&&s<0&&!c&&(s=0));var d=this._determinedMin,h=this._determinedMax;return null!=d&&(a=d,l=!0),null!=h&&(s=h,c=!0),{min:a,max:s,minFixed:l,maxFixed:c,isBlank:u}},t.prototype.modifyDataMinMax=function(t,e){this[kS[t]]=e},t.prototype.setDeterminedMinMax=function(t,e){this[CS[t]]=e},t.prototype.freeze=function(){this.frozen=!0},t}(),CS={min:"_determinedMin",max:"_determinedMax"},kS={min:"_dataMin",max:"_dataMax"};function MS(t,e){return null==e?null:sr(e)?NaN:t.parse(e)}function TS(t,e){var n=t.type,i=function(t,e,n){var i=t.rawExtentInfo;return i||(i=new SS(t,e,n),t.rawExtentInfo=i,i)}(t,e,t.getExtent()).calculate();t.setBlank(i.isBlank);var r=i.min,o=i.max,a=e.ecModel;if(a&&"time"===n){var s=function(t,e){var n=[];return e.eachSeriesByType(t,function(t){(function(t){return t.coordinateSystem&&"cartesian2d"===t.coordinateSystem.type})(t)&&n.push(t)}),n}("bar",a),l=!1;if(ji(s,function(t){l=l||t.getBaseAxis()===e.axis}),l){var c=sS(s),u=function(t,e,n,i){var r=n.axis.getExtent(),o=Math.abs(r[1]-r[0]),a=function(t,e){if(t&&e)return t[aS(e)]}(i,n.axis);if(void 0===a)return{min:t,max:e};var s=1/0;ji(a,function(t){s=Math.min(t.offset,s)});var l=-1/0;ji(a,function(t){l=Math.max(t.offset+t.width,l)}),s=Math.abs(s),l=Math.abs(l);var c=s+l,u=e-t,d=u/(1-(s+l)/o)-u;return e+=d*(l/c),t-=d*(s/c),{min:t,max:e}}(r,o,e,c);r=u.min,o=u.max}}return{extent:[r,o],fixMin:i.minFixed,fixMax:i.maxFixed}}function AS(t,e){var n=e,i=TS(t,n),r=i.extent,o=n.get("splitNumber");t instanceof xS&&(t.base=n.get("logBase"));var a=t.type,s=n.get("interval"),l="interval"===a||"time"===a;t.setBreaksFromOption(OS(n)),t.setExtent(r[0],r[1]),t.calcNiceExtent({splitNumber:o,fixMin:i.fixMin,fixMax:i.fixMax,minInterval:l?n.get("minInterval"):null,maxInterval:l?n.get("maxInterval"):null}),null!=s&&t.setInterval&&t.setInterval(s)}function IS(t){var e=t.getLabelModel().get("formatter");if("time"===t.type){var n=Dg(e);return function(e,i){return t.scale.getFormattedLabel(e,i,n)}}if(Ji(e))return function(n){var i=t.scale.getLabel(n);return e.replace("{value}",null!=i?i:"")};if(Qi(e)){if("category"===t.type)return function(n,i){return e(DS(t,n),n.value-t.scale.getExtent()[0],null)};var i=null;return function(n,r){var o=null;return i&&(o=i.makeAxisLabelFormatterParamBreak(o,n.break)),e(DS(t,n),r,o)}}return function(e){return t.scale.getLabel(e)}}function DS(t,e){return"category"===t.type?t.scale.getLabel(e):e.value}function PS(t){var e=t.get("interval");return null==e?"auto":e}function LS(t){return"category"===t.type&&0===PS(t.getLabelModel())}function ES(t,e){var n={};return ji(t.mapDimensionsAll(e),function(e){n[function(t,e){return zw(t,e)?t.getCalculationInfo("stackResultDimension"):e}(t,e)]=!0}),Xi(n)}function NS(t){return"middle"===t||"center"===t}function RS(t){return t.getShallow("show")}function OS(t){t.get("breaks",!0)}var zS=function(){function t(){}return t.prototype.getNeedCrossZero=function(){return!this.option.scale},t.prototype.getCoordSysModel=function(){},t}(),HS=[],BS={registerPreprocessor:Yx,registerProcessor:Zx,registerPostInit:function(t){Kx("afterinit",t)},registerPostUpdate:function(t){Kx("afterupdate",t)},registerUpdateLifecycle:Kx,registerAction:Qx,registerCoordinateSystem:function(t,e){sm.register(t,e)},registerLayout:function(t,e){ew(Fx,t,e,1e3,"layout")},registerVisual:Jx,registerTransform:iw,registerLoading:nw,registerMap:function(t,e,n){var i=Kb["registerMap"];i&&i(t,e,n)},registerImpl:function(t,e){Kb[t]=e},PRIORITY:tx,ComponentModel:Mm,ComponentView:u_,SeriesModel:n_,ChartView:f_,registerComponentModel:function(t){Mm.registerClass(t)},registerComponentView:function(t){u_.registerClass(t)},registerSeriesModel:function(t){n_.registerClass(t)},registerChartView:function(t){f_.registerClass(t)},registerCustomSeries:function(t,e){},registerSubTypeDefaulter:function(t,e){Mm.registerSubTypeDefaulter(t,e)},registerPainter:function(t,e){var n;n=e,El[t]=n}};function FS(t){Ki(t)?ji(t,function(t){FS(t)}):$i(HS,t)>=0||(HS.push(t),Qi(t)&&(t={install:t}),t.install(BS))}var $S=xc(),VS=xc(),WS=1,jS=2;function qS(t){return{out:{noPxChangeTryDetermine:[]},kind:t}}function US(t,e){var n=qi(e,function(e){return t.scale.parse(e)});return"time"===t.type&&n.length>0&&(n.sort(),n.unshift(n[0]),n.push(n[n.length-1])),n}function GS(t,e){var n=t.getLabelModel().get("customValues");if(n){var i=IS(t),r=t.scale.getExtent();return{labels:qi(Gi(US(t,n),function(t){return t>=r[0]&&t<=r[1]}),function(e){var n={value:e};return{formattedLabel:i(n),rawLabel:t.scale.getLabel(n),tickValue:e,time:void 0,break:void 0}})}}return"category"===t.type?function(t,e){var n=t.getLabelModel(),i=YS(t,n,e);return!n.get("show")||t.scale.isBlank()?{labels:[]}:i}(t,e):function(t){var e=t.scale.getTicks(),n=IS(t);return{labels:qi(e,function(e,i){return{formattedLabel:n(e,i),rawLabel:t.scale.getLabel(e),tickValue:e.value,time:e.time,break:e.break}})}}(t)}function XS(t,e,n){var i=t.getTickModel().get("customValues");if(i){var r=t.scale.getExtent();return{ticks:Gi(US(t,i),function(t){return t>=r[0]&&t<=r[1]})}}return"category"===t.type?function(t,e){var n,i,r=ZS(t),o=PS(e),a=JS(r,o);if(a)return a;e.get("show")&&!t.scale.isBlank()||(n=[]);if(Qi(o))n=rC(t,o,!0);else if("auto"===o){var s=YS(t,t.getLabelModel(),qS(jS));i=s.labelCategoryInterval,n=qi(s.labels,function(t){return t.tickValue})}else n=iC(t,i=o,!0);return tC(r,o,{ticks:n,tickCategoryInterval:i})}(t,e):{ticks:qi(t.scale.getTicks(n),function(t){return t.value})}}function YS(t,e,n){var i,r,o=KS(t),a=PS(e),s=n.kind===WS;if(!s){var l=JS(o,a);if(l)return l}Qi(a)?i=rC(t,a):(r="auto"===a?function(t,e){if(e.kind===WS){var n=t.calculateCategoryInterval(e);return e.out.noPxChangeTryDetermine.push(function(){return VS(t).autoInterval=n,!0}),n}var i=VS(t).autoInterval;return null!=i?i:VS(t).autoInterval=t.calculateCategoryInterval(e)}(t,n):a,i=iC(t,r));var c={labels:i,labelCategoryInterval:r};return s?n.out.noPxChangeTryDetermine.push(function(){return tC(o,a,c),!0}):tC(o,a,c),c}var ZS=QS("axisTick"),KS=QS("axisLabel");function QS(t){return function(e){return VS(e)[t]||(VS(e)[t]={list:[]})}}function JS(t,e){for(var n=0;ne&&i.axisExtent0===r[0]&&i.axisExtent1===r[1])return o;i.lastTickCount=n,i.lastAutoInterval=e,i.axisExtent0=r[0],i.axisExtent1=r[1]}function iC(t,e,n){var i=IS(t),r=t.scale,o=r.getExtent(),a=t.getLabelModel(),s=[],l=Math.max((e||0)+1,1),c=o[0],u=r.count();0!==c&&l>1&&u/l>2&&(c=Math.round(Math.ceil(c/l)*l));var d=LS(t),h=a.get("showMinLabel")||d,p=a.get("showMaxLabel")||d;h&&c!==o[0]&&g(o[0]);for(var f=c;f<=o[1];f+=l)g(f);function g(t){var e={value:t};s.push(n?t:{formattedLabel:i(e),rawLabel:r.getLabel(e),tickValue:t,time:void 0,break:void 0})}return p&&f-l!==o[1]&&g(o[1]),s}function rC(t,e,n){var i=t.scale,r=IS(t),o=[];return ji(i.getTicks(),function(t){var a=i.getLabel(t),s=t.value;e(t.value,a)&&o.push(n?s:{formattedLabel:r(t),rawLabel:a,tickValue:s,time:void 0,break:void 0})}),o}var oC=[0,1],aC=function(){function t(t,e,n){this.onBand=!1,this.inverse=!1,this.dim=t,this.scale=e,this._extent=n||[0,0]}return t.prototype.contain=function(t){var e=this._extent,n=Math.min(e[0],e[1]),i=Math.max(e[0],e[1]);return t>=n&&t<=i},t.prototype.containData=function(t){return this.scale.contain(this.scale.parse(t))},t.prototype.getExtent=function(){return this._extent.slice()},t.prototype.getPixelPrecision=function(t){return function(t,e){var n=Math.log,i=Math.LN10,r=Math.floor(n(t[1]-t[0])/i),o=Math.round(n($l(e[1]-e[0]))/i),a=Math.min(Math.max(-r+o,0),20);return isFinite(a)?a:20}(t||this.scale.getExtent(),this._extent)},t.prototype.setExtent=function(t,e){var n=this._extent;n[0]=t,n[1]=e},t.prototype.dataToCoord=function(t,e){var n=this._extent,i=this.scale;return t=i.normalize(i.parse(t)),this.onBand&&"ordinal"===i.type&&sC(n=n.slice(),i.count()),Vl(t,oC,n,e)},t.prototype.coordToData=function(t,e){var n=this._extent,i=this.scale;this.onBand&&"ordinal"===i.type&&sC(n=n.slice(),i.count());var r=Vl(t,n,oC,e);return this.scale.scale(r)},t.prototype.pointToData=function(t,e){},t.prototype.getTicksCoords=function(t){var e=(t=t||{}).tickModel||this.getTickModel(),n=qi(XS(this,e,{breakTicks:t.breakTicks,pruneByBreak:t.pruneByBreak}).ticks,function(t){return{coord:this.dataToCoord("ordinal"===this.scale.type?this.scale.getRawOrdinalNumber(t):t),tickValue:t}},this);return function(t,e,n,i){var r=e.length;if(!t.onBand||n||!r)return;var o,a,s=t.getExtent();if(1===r)e[0].coord=s[0],e[0].onBand=!0,o=e[1]={coord:s[1],tickValue:e[0].tickValue,onBand:!0};else{var l=e[r-1].tickValue-e[0].tickValue,c=(e[r-1].coord-e[0].coord)/l;ji(e,function(t){t.coord-=c/2,t.onBand=!0});var u=t.scale.getExtent();a=1+u[1]-e[r-1].tickValue,o={coord:e[r-1].coord+c*a,tickValue:u[1]+1,onBand:!0},e.push(o)}var d=s[0]>s[1];h(e[0].coord,s[0])&&(i?e[0].coord=s[0]:e.shift());i&&h(s[0],e[0].coord)&&e.unshift({coord:s[0],onBand:!0});h(s[1],o.coord)&&(i?o.coord=s[1]:e.pop());i&&h(o.coord,s[1])&&e.push({coord:s[1],onBand:!0});function h(t,e){return t=ql(t),e=ql(e),d?t>e:t0&&t<100||(t=5),qi(this.scale.getMinorTicks(t),function(t){return qi(t,function(t){return{coord:this.dataToCoord(t),tickValue:t}},this)},this)},t.prototype.getViewLabels=function(t){return GS(this,t=t||qS(jS)).labels},t.prototype.getLabelModel=function(){return this.model.getModel("axisLabel")},t.prototype.getTickModel=function(){return this.model.getModel("axisTick")},t.prototype.getBandWidth=function(){var t=this._extent,e=this.scale.getExtent(),n=e[1]-e[0]+(this.onBand?1:0);0===n&&(n=1);var i=Math.abs(t[1]-t[0]);return Math.abs(i)/n},t.prototype.calculateCategoryInterval=function(t){return function(t,e){var n=e.kind,i=function(t){var e=t.getLabelModel();return{axisRotate:t.getRotate?t.getRotate():t.isHorizontal&&!t.isHorizontal()?90:0,labelRotate:e.get("rotate")||0,font:e.getFont()}}(t),r=IS(t),o=(i.axisRotate-i.labelRotate)/180*Math.PI,a=t.scale,s=a.getExtent(),l=a.count();if(s[1]-s[0]<1)return 0;var c=1;l>40&&(c=Math.max(1,Math.floor(l/40)));for(var u=s[0],d=t.dataToCoord(u+1)-t.dataToCoord(u),h=Math.abs(d*Math.cos(o)),p=Math.abs(d*Math.sin(o)),f=0,g=0;u<=s[1];u+=c){var m,v,y=gl(r({value:u}),i.font,"center","top");m=1.3*y.width,v=1.3*y.height,f=Math.max(f,m,7),g=Math.max(g,v,7)}var _=f/h,b=g/p;isNaN(_)&&(_=1/0),isNaN(b)&&(b=1/0);var x=Math.max(0,Math.floor(Math.min(_,b)));if(n===WS)return e.out.noPxChangeTryDetermine.push(Yi(eC,null,t,x,l)),x;var w=nC(t,x,l);return null!=w?w:x}(this,t=t||qS(jS))},t}();function sC(t,e){var n=(t[1]-t[0])/e/2;t[0]+=n,t[1]-=n}var lC=["label","labelLine","layoutOption","priority","defaultAttr","marginForce","minMarginForce","marginDefault","suggestIgnore"];function cC(t,e,n){n=n||3,e?t.dirty|=n:t.dirty&=~n}function uC(t,e){return e=e||3,null==t.dirty||!!(t.dirty&e)}function dC(t){if(t)return uC(t)&&function(t,e,n){var i=e.getComputedTransform();t.transform=Ef(t.transform,i);var r=t.localRect=Lf(t.localRect,e.getBoundingRect()),o=e.style,a=o.margin,s=n&&n.marginForce,l=n&&n.minMarginForce,c=n&&n.marginDefault,u=o.__marginType;null==u&&c&&(a=c,u=Kf.textMargin);for(var d=0;d<4;d++)hC[d]=u===Kf.minMargin&&l&&null!=l[d]?l[d]:s&&null!=s[d]?s[d]:a?a[d]:0;u===Kf.textMargin&&Cf(r,hC,!1,!1);var h=t.rect=Lf(t.rect,r);i&&h.applyTransform(i);u===Kf.minMargin&&Cf(h,hC,!1,!1);t.axisAligned=Df(i),(t.label=t.label||{}).ignore=e.ignore,cC(t,!1),cC(t,!0,2)}(t,t.label,t),t}var hC=[0,0,0,0];function pC(t,e){for(var n=0;n-1&&(s.style.stroke=s.style.fill,s.style.fill=Tm.color.neutral00,s.style.lineWidth=2),e},e.type="series.line",e.dependencies=["grid","polar"],e.defaultOption={z:3,coordinateSystem:"cartesian2d",legendHoverLink:!0,clip:!0,label:{position:"top"},endLabel:{show:!1,valueAnimation:!0,distance:8},lineStyle:{width:2,type:"solid"},emphasis:{scale:!0},step:!1,smooth:!1,smoothMonotone:null,symbol:"emptyCircle",symbolSize:6,symbolRotate:null,showSymbol:!0,showAllSymbol:"auto",connectNulls:!1,sampling:"none",animationEasing:"linear",progressive:0,hoverLayerThreshold:1/0,universalTransition:{divideShape:"clone"},triggerLineEvent:!1},e}(n_);function vC(t,e){var n=t.mapDimensionsAll("defaultedLabel"),i=n.length;if(1===i){var r=ay(t,e,n[0]);return null!=r?r+"":null}if(i){for(var o=[],a=0;a0?+h:1;M.scaleX=this._sizeX*T,M.scaleY=this._sizeY*T,this.setSymbolScale(1),Ph(this,l,c,u)},e.prototype.setSymbolScale=function(t){this.scaleX=this.scaleY=t},e.prototype.fadeOut=function(t,e,n){var i=this.childAt(0),r=jd(this).dataIndex,o=n&&n.animation;if(this.silent=i.silent=!0,n&&n.fadeLabel){var a=i.getTextContent();a&&rf(a,{style:{opacity:0}},e,{dataIndex:r,removeOpt:o,cb:function(){i.removeTextContent()}})}else i.removeTextContent();rf(i,{style:{opacity:0},scaleX:0,scaleY:0},e,{dataIndex:r,cb:t,removeOpt:o})},e.getSymbolSize=function(t,e){return Ki(n=t.getItemVisual(e,"symbolSize"))||(n=[+n,+n]),[n[0]||0,n[1]||0];var n},e.getSymbolZ2=function(t,e){return t.getItemVisual(e,"z2")},e}(Ll);function _C(t,e){this.parent.drift(t,e)}function bC(t,e,n,i){return e&&!isNaN(e[0])&&!isNaN(e[1])&&!(i.isIgnore&&i.isIgnore(n))&&!(i.clipShape&&!i.clipShape.contain(e[0],e[1]))&&"none"!==t.getItemVisual(n,"symbol")}function xC(t){return null==t||nr(t)||(t={isIgnore:t}),t||{}}function wC(t){var e=t.hostModel,n=e.getModel("emphasis");return{emphasisItemStyle:n.getModel("itemStyle").getItemStyle(),blurItemStyle:e.getModel(["blur","itemStyle"]).getItemStyle(),selectItemStyle:e.getModel(["select","itemStyle"]).getItemStyle(),focus:n.get("focus"),blurScope:n.get("blurScope"),emphasisDisabled:n.get("disabled"),hoverScale:n.get("scale"),labelStatesModels:$f(e),cursorStyle:e.get("cursor")}}var SC=function(){function t(t){this.group=new Ll,this._SymbolCtor=t||yC}return t.prototype.updateData=function(t,e){this._progressiveEls=null,e=xC(e);var n=this.group,i=t.hostModel,r=this._data,o=this._SymbolCtor,a=e.disableAnimation,s=wC(t),l={disableAnimation:a},c=e.getSymbolPoint||function(e){return t.getItemLayout(e)};r||n.removeAll(),t.diff(r).add(function(i){var r=c(i);if(bC(t,r,i,e)){var a=new o(t,i,s,l);a.setPosition(r),t.setItemGraphicEl(i,a),n.add(a)}}).update(function(u,d){var h=r.getItemGraphicEl(d),p=c(u);if(bC(t,p,u,e)){var f=t.getItemVisual(u,"symbol")||"circle",g=h&&h.getSymbolType&&h.getSymbolType();if(!h||g&&g!==f)n.remove(h),(h=new o(t,u,s,l)).setPosition(p);else{h.updateData(t,u,s,l);var m={x:p[0],y:p[1]};a?h.attr(m):tf(h,m,i)}n.add(h),t.setItemGraphicEl(u,h)}else n.remove(h)}).remove(function(t){var e=r.getItemGraphicEl(t);e&&e.fadeOut(function(){n.remove(e)},i)}).execute(),this._getSymbolPoint=c,this._data=t},t.prototype.updateLayout=function(){var t=this,e=this._data;e&&e.eachItemGraphicEl(function(e,n){var i=t._getSymbolPoint(n);e.setPosition(i),e.markRedraw()})},t.prototype.incrementalPrepareUpdate=function(t){this._seriesScope=wC(t),this._data=null,this.group.removeAll()},t.prototype.incrementalUpdate=function(t,e,n){function i(t){t.isGroup||(t.incremental=!0,t.ensureState("emphasis").hoverLayer=!0)}this._progressiveEls=[],n=xC(n);for(var r=t.start;r0?n=i[0]:i[1]<0&&(n=i[1]);return n}(r,n),a=i.dim,s=r.dim,l=e.mapDimension(s),c=e.mapDimension(a),u="x"===s||"radius"===s?1:0,d=qi(t.dimensions,function(t){return e.mapDimension(t)}),h=!1,p=e.getCalculationInfo("stackResultDimension");return zw(e,d[0])&&(h=!0,d[0]=p),zw(e,d[1])&&(h=!0,d[1]=p),{dataDimsForPoint:d,valueStart:o,valueAxisDim:s,baseAxisDim:a,stacked:!!h,valueDim:l,baseDim:c,baseDataOffset:u,stackedOverDimension:e.getCalculationInfo("stackedOverDimension")}}function kC(t,e,n,i){var r=NaN;t.stacked&&(r=n.get(n.getCalculationInfo("stackedOverDimension"),i)),isNaN(r)&&(r=t.valueStart);var o=t.baseDataOffset,a=[];return a[o]=n.get(t.baseDim,i),a[1-o]=r,e.dataToPoint(a)}var MC=Math.min,TC=Math.max;function AC(t,e){return isNaN(t)||isNaN(e)}function IC(t,e,n,i,r,o,a,s,l){for(var c,u,d,h,p,f,g=n,m=0;m=r||g<0)break;if(AC(v,y)){if(l){g+=o;continue}break}if(g===n)t[o>0?"moveTo":"lineTo"](v,y),d=v,h=y;else{var _=v-c,b=y-u;if(_*_+b*b<.5){g+=o;continue}if(a>0){for(var x=g+o,w=e[2*x],S=e[2*x+1];w===v&&S===y&&m=i||AC(w,S))p=v,f=y;else{M=w-c,T=S-u;var D=v-c,P=w-v,L=y-u,E=S-y,N=void 0,R=void 0;if("x"===s){var O=M>0?1:-1;p=v-O*(N=Math.abs(D))*a,f=y,A=v+O*(R=Math.abs(P))*a,I=y}else if("y"===s){var z=T>0?1:-1;p=v,f=y-z*(N=Math.abs(L))*a,A=v,I=y+z*(R=Math.abs(E))*a}else N=Math.sqrt(D*D+L*L),p=v-M*a*(1-(k=(R=Math.sqrt(P*P+E*E))/(R+N))),f=y-T*a*(1-k),I=y+T*a*k,A=MC(A=v+M*a*k,TC(w,v)),I=MC(I,TC(S,y)),A=TC(A,MC(w,v)),f=y-(T=(I=TC(I,MC(S,y)))-y)*N/R,p=MC(p=v-(M=A-v)*N/R,TC(c,v)),f=MC(f,TC(u,y)),A=v+(M=v-(p=TC(p,MC(c,v))))*R/N,I=y+(T=y-(f=TC(f,MC(u,y))))*R/N}t.bezierCurveTo(d,h,p,f,v,y),d=A,h=I}else t.lineTo(v,y)}c=v,u=y,g+=o}return m}var DC=function(){this.smooth=0,this.smoothConstraint=!0},PC=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polyline",n}return S(e,t),e.prototype.getDefaultStyle=function(){return{stroke:Tm.color.neutral99,fill:null}},e.prototype.getDefaultShape=function(){return new DC},e.prototype.buildPath=function(t,e){var n=e.points,i=0,r=n.length/2;if(e.connectNulls){for(;r>0&&AC(n[2*r-2],n[2*r-1]);r--);for(;i=0){var m=a?(u-i)*g+i:(c-n)*g+n;return a?[t,m]:[m,t]}n=c,i=u;break;case o.C:c=r[l++],u=r[l++],d=r[l++],h=r[l++],p=r[l++],f=r[l++];var v=a?ma(n,c,d,p,t,s):ma(i,u,h,f,t,s);if(v>0)for(var y=0;y=0){m=a?fa(i,u,h,f,_):fa(n,c,d,p,_);return a?[t,m]:[m,t]}}n=p,i=f}}},e}(gd),LC=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e}(DC),EC=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polygon",n}return S(e,t),e.prototype.getDefaultShape=function(){return new LC},e.prototype.buildPath=function(t,e){var n=e.points,i=e.stackedOnPoints,r=0,o=n.length/2,a=e.smoothMonotone;if(e.connectNulls){for(;o>0&&AC(n[2*o-2],n[2*o-1]);o--);for(;r=0&&t<=1){var i=t*(e.length-1),r=Math.floor(i),o=Math.ceil(i),a=Wa(e[r]),s=Wa(e[o]),l=i-r,c=Ga([La(za(a[0],s[0],l)),La(za(a[1],s[1],l)),La(za(a[2],s[2],l)),Ea(za(a[3],s[3],l))],"rgba");return n?{color:c,leftIndex:r,rightIndex:o,value:i}:c}}((n-i)/(e.coord-i),[t.color,e.color])}}for(var s=0;se){i?r.push(a(i,l,e)):n&&r.push(a(n,l,0),a(n,l,e));break}n&&(r.push(a(n,l,0)),n=null),r.push(l),i=l}}return r}function FC(t,e,n){var i=t.get("showAllSymbol"),r="auto"===i;if(!i||r){var o=n.getAxesByScale("ordinal")[0];if(o&&(!r||!function(t,e){var n=t.getExtent(),i=Math.abs(n[1]-n[0])/t.scale.count();isNaN(i)&&(i=0);for(var r=e.count(),o=Math.max(1,Math.round(r/5)),a=0;ai)return!1;return!0}(o,e))){var a=e.mapDimension(o.dim),s={};return ji(o.getViewLabels(),function(t){var e=o.scale.getRawOrdinalNumber(t.tickValue);s[e]=1}),function(t){return!s.hasOwnProperty(e.get(a,t))}}}}function $C(t,e){return isNaN(t)||isNaN(e)}function VC(t,e){return[t[2*e],t[2*e+1]]}function WC(t){if(t.get(["endLabel","show"]))return!0;for(var e=0;e=0;a--){var s=t.getDimensionInfo(i[a].dimension);if("x"===(r=s&&s.coordDim)||"y"===r){o=i[a];break}}if(o){var l=e.getAxis(r),c=qi(o.stops,function(t){return{coord:l.toGlobalCoord(l.dataToCoord(t.value)),color:t.color}}),u=c.length,d=o.outerColors.slice();u&&c[0].coord>c[u-1].coord&&(c.reverse(),d.reverse());var h=BC(c,"x"===r?n.getWidth():n.getHeight()),p=h.length;if(!p&&u)return c[0].coord<0?d[1]?d[1]:c[u-1].color:d[0]?d[0]:c[0].color;var f=h[0].coord-10,g=h[p-1].coord+10,m=g-f;if(m<.001)return"transparent";ji(h,function(t){t.offset=(t.coord-f)/m}),h.push({offset:p?h[p-1].offset:.5,color:d[1]||"transparent"}),h.unshift({offset:p?h[0].offset:.5,color:d[0]||"transparent"});var v=new Bp(0,0,0,0,h,!0);return v[r]=f,v[r+"2"]=g,v}}}(o,i,n)||o.getVisual("style")[o.getVisual("drawType")];if(h&&u.type===i.type&&k===this._step){m&&!p?p=this._newPolygon(l,_):p&&!m&&(f.remove(p),p=this._polygon=null),c||this._initOrUpdateEndLabel(t,i,rm(M));var T=f.getClipPath();if(T)ef(T,{shape:jC(this,i,!1,t).shape},t);else f.setClipPath(jC(this,i,!0,t));b&&d.updateData(o,{isIgnore:w,clipShape:C,disableAnimation:!0,getSymbolPoint:function(t){return[l[2*t],l[2*t+1]]}}),NC(this._stackedOnPoints,_)&&NC(this._points,l)||(g?this._doUpdateAnimation(o,_,i,n,k,v,x):(k&&(_&&(_=HC(_,l,i,k,x)),l=HC(l,null,i,k,x)),h.setShape({points:l}),p&&p.setShape({points:l,stackedOnPoints:_})))}else b&&d.updateData(o,{isIgnore:w,clipShape:C,disableAnimation:!0,getSymbolPoint:function(t){return[l[2*t],l[2*t+1]]}}),g&&this._initSymbolLabelAnimation(o,i,C),k&&(_&&(_=HC(_,l,i,k,x)),l=HC(l,null,i,k,x)),h=this._newPolyline(l),m?p=this._newPolygon(l,_):p&&(f.remove(p),p=this._polygon=null),c||this._initOrUpdateEndLabel(t,i,rm(M)),f.setClipPath(jC(this,i,!0,t));var A=t.getModel("emphasis"),I=A.get("focus"),D=A.get("blurScope"),P=A.get("disabled");(h.useStyle(Fi(a.getLineStyle(),{fill:"none",stroke:M,lineJoin:"bevel"})),Nh(h,t,"lineStyle"),h.style.lineWidth>0&&"bolder"===t.get(["emphasis","lineStyle","width"]))&&(h.getState("emphasis").style.lineWidth=+h.style.lineWidth+1);jd(h).seriesIndex=t.seriesIndex,Ph(h,I,D,P);var L=zC(t.get("smooth")),E=t.get("smoothMonotone");if(h.setShape({smooth:L,smoothMonotone:E,connectNulls:x}),p){var N=o.getCalculationInfo("stackedOnSeries"),R=0;p.useStyle(Fi(s.getAreaStyle(),{fill:M,opacity:.7,lineJoin:"bevel",decal:o.getVisual("style").decal})),N&&(R=zC(N.get("smooth"))),p.setShape({smooth:L,stackedOnSmooth:R,smoothMonotone:E,connectNulls:x}),Nh(p,t,"areaStyle"),jd(p).seriesIndex=t.seriesIndex,Ph(p,I,D,P)}var O=this._changePolyState;o.eachItemGraphicEl(function(t){t&&(t.onHoverStateChange=O)}),this._polyline.onHoverStateChange=O,this._data=o,this._coordSys=i,this._stackedOnPoints=_,this._points=l,this._step=k,this._valueOrigin=v,t.get("triggerLineEvent")&&(this.packEventData(t,h),p&&this.packEventData(t,p))},e.prototype.packEventData=function(t,e){jd(e).eventData={componentType:"series",componentSubType:"line",componentIndex:t.componentIndex,seriesIndex:t.seriesIndex,seriesName:t.name,seriesType:"line"}},e.prototype.highlight=function(t,e,n,i){var r=t.getData(),o=bc(r,i);if(this._changePolyState("emphasis"),!(o instanceof Array)&&null!=o&&o>=0){var a=r.getLayout("points"),s=r.getItemGraphicEl(o);if(!s){var l=a[2*o],c=a[2*o+1];if(isNaN(l)||isNaN(c))return;if(this._clipShapeForSymbol&&!this._clipShapeForSymbol.contain(l,c))return;var u=t.get("zlevel")||0,d=t.get("z")||0;(s=new yC(r,o)).x=l,s.y=c,s.setZ(u,d);var h=s.getSymbolPath().getTextContent();h&&(h.zlevel=u,h.z=d,h.z2=this._polyline.z2+1),s.__temp=!0,r.setItemGraphicEl(o,s),s.stopSymbolAnimation(!0),this.group.add(s)}s.highlight()}else f_.prototype.highlight.call(this,t,e,n,i)},e.prototype.downplay=function(t,e,n,i){var r=t.getData(),o=bc(r,i);if(this._changePolyState("normal"),null!=o&&o>=0){var a=r.getItemGraphicEl(o);a&&(a.__temp?(r.setItemGraphicEl(o,null),this.group.remove(a)):a.downplay())}else f_.prototype.downplay.call(this,t,e,n,i)},e.prototype._changePolyState=function(t){var e=this._polygon;ph(this._polyline,t),e&&ph(e,t)},e.prototype._newPolyline=function(t){var e=this._polyline;return e&&this._lineGroup.remove(e),e=new PC({shape:{points:t},segmentIgnoreThreshold:2,z2:10}),this._lineGroup.add(e),this._polyline=e,e},e.prototype._newPolygon=function(t,e){var n=this._polygon;return n&&this._lineGroup.remove(n),n=new EC({shape:{points:t,stackedOnPoints:e},segmentIgnoreThreshold:2}),this._lineGroup.add(n),this._polygon=n,n},e.prototype._initSymbolLabelAnimation=function(t,e,n){var i,r,o=e.getBaseAxis(),a=o.inverse;"cartesian2d"===e.type?(i=o.isHorizontal(),r=!1):"polar"===e.type&&(i="angle"===o.dim,r=!0);var s=t.hostModel,l=s.get("animationDuration");Qi(l)&&(l=l(null));var c=s.get("animationDelay")||0,u=Qi(c)?c(null):c;t.eachItemGraphicEl(function(t,o){var s=t;if(s){var d=[t.x,t.y],h=void 0,p=void 0,f=void 0;if(n)if(r){var g=n,m=e.pointToCoord(d);i?(h=g.startAngle,p=g.endAngle,f=-m[1]/180*Math.PI):(h=g.r0,p=g.r,f=m[0])}else{var v=n;i?(h=v.x,p=v.x+v.width,f=t.x):(h=v.y+v.height,p=v.y,f=t.y)}var y=p===h?0:(f-h)/(p-h);a&&(y=1-y);var _=Qi(c)?c(o):l*y+u,b=s.getSymbolPath(),x=b.getTextContent();s.attr({scaleX:0,scaleY:0}),s.animateTo({scaleX:1,scaleY:1},{duration:200,setToFinal:!0,delay:_}),x&&x.animateFrom({style:{opacity:0}},{duration:300,delay:_}),b.disableLabelAnimation=!0}})},e.prototype._initOrUpdateEndLabel=function(t,e,n){var i=t.getModel("endLabel");if(WC(t)){var r=t.getData(),o=this._polyline,a=r.getLayout("points");if(!a)return o.removeTextContent(),void(this._endLabel=null);var s=this._endLabel;s||((s=this._endLabel=new Pd({z2:200})).ignoreClip=!0,o.setTextContent(this._endLabel),o.disableLabelAnimation=!0);var l=function(t){for(var e=t.length/2;e>0&&$C(t[2*e-2],t[2*e-1]);e--);return e-1}(a);l>=0&&(Ff(o,$f(t,"endLabel"),{inheritColor:n,labelFetcher:t,labelDataIndex:l,defaultText:function(t,e,n){return null!=n?function(t,e){var n=t.mapDimensionsAll("defaultedLabel");if(!Ki(e))return e+"";for(var i=[],r=0;r=0&&i.push(e[o])}return i.join(" ")}(r,n):vC(r,t)},enableTextSetter:!0},function(t,e){var n=e.getBaseAxis(),i=n.isHorizontal(),r=n.inverse,o=i?r?"right":"left":"center",a=i?"middle":r?"top":"bottom";return{normal:{align:t.get("align")||o,verticalAlign:t.get("verticalAlign")||a}}}(i,e)),o.textConfig.position=null)}else this._endLabel&&(this._polyline.removeTextContent(),this._endLabel=null)},e.prototype._endLabelOnDuring=function(t,e,n,i,r,o,a){var s=this._endLabel,l=this._polyline;if(s){t<1&&null==i.originalX&&(i.originalX=s.x,i.originalY=s.y);var c=n.getLayout("points"),u=n.hostModel,d=u.get("connectNulls"),h=o.get("precision"),p=o.get("distance")||0,f=a.getBaseAxis(),g=f.isHorizontal(),m=f.inverse,v=e.shape,y=m?g?v.x:v.y+v.height:g?v.x+v.width:v.y,_=(g?p:0)*(m?-1:1),b=(g?0:-p)*(m?-1:1),x=g?"x":"y",w=function(t,e,n){for(var i,r,o=t.length/2,a="x"===n?0:1,s=0,l=-1,c=0;c=e||i>=e&&r<=e){l=c;break}s=c,i=r}else i=r;return{range:[s,l],t:(e-i)/(r-i)}}(c,y,x),S=w.range,C=S[1]-S[0],k=void 0;if(C>=1){if(C>1&&!d){var M=VC(c,S[0]);s.attr({x:M[0]+_,y:M[1]+b}),r&&(k=u.getRawValue(S[0]))}else{(M=l.getPointOn(y,x))&&s.attr({x:M[0]+_,y:M[1]+b});var T=u.getRawValue(S[0]),A=u.getRawValue(S[1]);r&&(k=function(t,e,n,i,r){var o=null==e||"auto"===e;if(null==i)return i;if(er(i))return ql(f=sc(n||0,i,r),o?Math.max(Ul(n||0),Ul(i)):e);if(Ji(i))return r<1?n:i;for(var a=[],s=n,l=i,c=Math.max(s?s.length:0,l.length),u=0;u0?S[0]:0;M=VC(c,I);r&&(k=u.getRawValue(I)),s.attr({x:M[0]+_,y:M[1]+b})}if(r){var D=Zf(s);"function"==typeof D.setLabelText&&D.setLabelText(k)}}},e.prototype._doUpdateAnimation=function(t,e,n,i,r,o,a){var s=this._polyline,l=this._polygon,c=t.hostModel,u=function(t,e,n,i,r,o,a){for(var s=function(t,e){var n=[];return e.diff(t).add(function(t){n.push({cmd:"+",idx:t})}).update(function(t,e){n.push({cmd:"=",idx:e,idx1:t})}).remove(function(t){n.push({cmd:"-",idx:t})}).execute(),n}(t,e),l=[],c=[],u=[],d=[],h=[],p=[],f=[],g=CC(r,e,a),m=t.getLayout("points")||[],v=e.getLayout("points")||[],y=0;y3e3||l&&OC(h,f)>3e3)return s.stopAnimation(),s.setShape({points:p}),void(l&&(l.stopAnimation(),l.setShape({points:p,stackedOnPoints:f})));s.shape.__points=u.current,s.shape.points=d;var g={shape:{points:p}};u.current!==d&&(g.shape.__points=u.next),s.stopAnimation(),tf(s,g,c),l&&(l.setShape({points:d,stackedOnPoints:h}),l.stopAnimation(),tf(l,{shape:{stackedOnPoints:f}},c),s.shape.points!==l.shape.points&&(l.shape.points=s.shape.points));for(var m=[],v=u.status,y=0;ye&&(e=t[n]);return isFinite(e)?e:NaN},min:function(t){for(var e=1/0,n=0;ne[1]&&e.reverse(),e},e.prototype.pointToData=function(t,e){return this.coordToData(this.toLocalCoord(t["x"===this.dim?0:1]),e)},e.prototype.setCategorySortInfo=function(t){if("category"!==this.type)return!1;this.model.option.categorySortInfo=t,this.scale.setSortInfo(t)},e}(aC),uk="expandAxisBreak",dk=Math.PI,hk=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],pk=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],fk=xc(),gk=xc(),mk=function(){function t(t){this.recordMap={},this.resolveAxisNameOverlap=t}return t.prototype.ensureRecord=function(t){var e=t.axis.dim,n=t.componentIndex,i=this.recordMap,r=i[e]||(i[e]=[]);return r[n]||(r[n]={ready:{}})},t}();var vk=[1,0,0,1,0,0],yk=new Do(0,0,0,0),_k=function(t,e,n,i,r,o){if(NS(t.nameLocation)){var a=o.stOccupiedRect;a&&bk(function(t,e,n){return t.transform=Ef(t.transform,n),t.localRect=Lf(t.localRect,e),t.rect=Lf(t.rect,e),n&&t.rect.applyTransform(n),t.axisAligned=Df(n),t.obb=void 0,(t.label=t.label||{}).ignore=!1,t}({},a,o.transGroup.transform),i,r)}else xk(o.labelInfoList,o.dirVec,i,r)};function bk(t,e,n){var i=new mo;gC(t,e,i,{direction:Math.atan2(n.y,n.x),bidirectional:!1,touchThreshold:.05})&&function(t,e){if(t){t.label.x+=e.x,t.label.y+=e.y,t.label.markRedraw();var n=t.transform;n&&(n[4]+=e.x,n[5]+=e.y);var i=t.rect;i&&(i.x+=e.x,i.y+=e.y);var r=t.obb;r&&r.fromBoundingRect(t.localRect,n)}}(e,i)}function xk(t,e,n,i){for(var r=mo.dot(i,e)>=0,o=0,a=t.length;o0?"top":"bottom",i="center"):Yl(o-dk)?(r=n>0?"bottom":"top",i="center"):(r="middle",i=o>0&&o0?"right":"left":n>0?"left":"right"),{rotation:o,textAlign:i,textVerticalAlign:r}},t.makeAxisEventDataBase=function(t){var e={componentType:t.mainType,componentIndex:t.componentIndex};return e[t.mainType+"Index"]=t.componentIndex,e},t.isLabelSilent=function(t){var e=t.get("tooltip");return t.get("silent")||!(t.get("triggerEvent")||e&&e.show)},t}(),Sk=["axisLine","axisTickLabelEstimate","axisTickLabelDetermine","axisName"],Ck={axisLine:function(t,e,n,i,r,o,a){var s=i.get(["axisLine","show"]);if("auto"===s&&(s=!0,null!=t.raw.axisLineAutoShow&&(s=!!t.raw.axisLineAutoShow)),s){var l=i.axis.getExtent(),c=o.transform,u=[l[0],0],d=[l[1],0],h=u[0]>d[0];c&&(Rr(u,u,c),Rr(d,d,c));var p=Bi({lineCap:"round"},i.getModel(["axisLine","lineStyle"]).getLineStyle()),f={strokeContainThreshold:t.raw.strokeContainThreshold||5,silent:!0,z2:1,style:p};if(i.get(["axisLine","breakLine"])&&i.axis.scale.hasBreaks())null.buildAxisBreakLine(i,r,o,f);else{var g=new Dp(Bi({shape:{x1:u[0],y1:u[1],x2:d[0],y2:d[1]}},f));mf(g.shape,g.style.lineWidth),g.anid="line",r.add(g)}var m=i.get(["axisLine","symbol"]);if(null!=m){var v=i.get(["axisLine","symbolSize"]);Ji(m)&&(m=[m,m]),(Ji(v)||er(v))&&(v=[v,v]);var y=wb(i.get(["axisLine","symbolOffset"])||0,v),_=v[0],b=v[1];ji([{rotate:t.rotation+Math.PI/2,offset:y[0],r:0},{rotate:t.rotation-Math.PI/2,offset:y[1],r:Math.sqrt((u[0]-d[0])*(u[0]-d[0])+(u[1]-d[1])*(u[1]-d[1]))}],function(e,n){if("none"!==m[n]&&null!=m[n]){var i=xb(m[n],-_/2,-b/2,_,b,p.stroke,!0),o=e.r+e.offset,a=h?d:u;i.attr({rotation:e.rotate,x:a[0]+o*Math.cos(t.rotation),y:a[1]-o*Math.sin(t.rotation),silent:!0,z2:11}),r.add(i)}})}}},axisTickLabelEstimate:function(t,e,n,i,r,o,a,s){Ak(e,r,s)&&kk(t,e,n,i,r,o,a,WS)},axisTickLabelDetermine:function(t,e,n,i,r,o,a,s){Ak(e,r,s)&&kk(t,e,n,i,r,o,a,jS);var l=function(t,e,n,i){var r=i.axis,o=i.getModel("axisTick"),a=o.get("show");"auto"===a&&(a=!0,null!=t.raw.axisTickAutoShow&&(a=!!t.raw.axisTickAutoShow));if(!a||r.scale.isBlank())return[];for(var s=o.getModel("lineStyle"),l=t.tickDirection*o.get("length"),c=Tk(r.getTicksCoords(),n.transform,l,Fi(s.getLineStyle(),{stroke:i.get(["axisLine","lineStyle","color"])}),"ticks"),u=0;ui[1],l="start"===e&&!s||"start"!==e&&s;Yl(a-dk/2)?(o=l?"bottom":"top",r="center"):Yl(a-1.5*dk)?(o=l?"top":"bottom",r="center"):(o="middle",r=a<1.5*dk&&a>dk/2?l?"left":"right":l?"right":"left");return{rotation:a,textAlign:r,textVerticalAlign:o}}(t.rotation,u,x||0,f),null!=(b=t.raw.axisNameAvailableWidth)&&(b=Math.abs(b/Math.sin(_.rotation)),!isFinite(b)&&(b=null)));var w=h.getFont(),S=i.get("nameTruncate",!0)||{},C=S.ellipsis,k=lr(t.raw.nameTruncateMaxWidth,S.maxWidth,b),M=s.nameMarginLevel||0,T=new Pd({x:m.x,y:m.y,rotation:_.rotation,silent:wk.isLabelSilent(i),style:Vf(h,{text:c,font:w,overflow:"truncate",width:k,ellipsis:C,fill:h.getTextColor()||i.get(["axisLine","lineStyle","color"]),align:h.get("align")||_.textAlign,verticalAlign:h.get("verticalAlign")||_.textVerticalAlign}),z2:1});if(Tf({el:T,componentModel:i,itemName:c}),T.__fullText=c,T.anid="name",i.get("triggerEvent")){var A=wk.makeAxisEventDataBase(i);A.targetType="axisName",A.name=c,jd(T).eventData=A}o.add(T),T.updateTransform(),e.nameEl=T;var I=l.nameLayout=dC({label:T,priority:T.z2,defaultAttr:{ignore:T.ignore},marginDefault:NS(u)?hk[M]:pk[M]});if(l.nameLocation=u,r.add(T),T.decomposeTransform(),t.shouldNameMoveOverlap&&I){var D=n.ensureRecord(i);n.resolveAxisNameOverlap(t,n,i,I,v,D)}}}};function kk(t,e,n,i,r,o,a,s){Ik(e)||function(t,e,n,i,r,o){var a=r.axis,s=lr(t.raw.axisLabelShow,r.get(["axisLabel","show"])),l=new Ll;n.add(l);var c=qS(i);if(!s||a.scale.isBlank())return void Dk(e,[],l,c);var u=r.getModel("axisLabel"),d=a.getViewLabels(c),h=(lr(t.raw.labelRotate,u.get("rotate"))||0)*dk/180,p=wk.innerTextLayout(t.rotation,h,t.labelDirection),f=r.getCategories&&r.getCategories(!0),g=[],m=r.get("triggerEvent"),v=1/0,y=-1/0;ji(d,function(t,e){var n,i="ordinal"===a.scale.type?a.scale.getRawOrdinalNumber(t.tickValue):t.tickValue,s=t.formattedLabel,c=t.rawLabel,h=u;if(f&&f[i]){var _=f[i];nr(_)&&_.textStyle&&(h=new lg(_.textStyle,u,r.ecModel))}var b=h.getTextColor()||r.get(["axisLine","lineStyle","color"]),x=h.getShallow("align",!0)||p.textAlign,w=cr(h.getShallow("alignMinLabel",!0),x),S=cr(h.getShallow("alignMaxLabel",!0),x),C=h.getShallow("verticalAlign",!0)||h.getShallow("baseline",!0)||p.textVerticalAlign,k=cr(h.getShallow("verticalAlignMinLabel",!0),C),M=cr(h.getShallow("verticalAlignMaxLabel",!0),C),T=10+((null===(n=t.time)||void 0===n?void 0:n.level)||0);v=Math.min(v,T),y=Math.max(y,T);var A=new Pd({x:0,y:0,rotation:0,silent:wk.isLabelSilent(r),z2:T,style:Vf(h,{text:s,align:0===e?w:e===d.length-1?S:x,verticalAlign:0===e?k:e===d.length-1?M:C,fill:Qi(b)?b("category"===a.type?c:"value"===a.type?i+"":i,e):b})});A.anid="label_"+i;var I=fk(A);if(I.break=t.break,I.tickValue=i,I.layoutRotation=p.rotation,Tf({el:A,componentModel:r,itemName:s,formatterParamsExtra:{isTruncated:function(){return A.isTruncated},value:c,tickIndex:e}}),m){var D=wk.makeAxisEventDataBase(r);D.targetType="axisLabel",D.value=c,D.tickIndex=e,t.break&&(D.break={start:t.break.parsedBreak.vmin,end:t.break.parsedBreak.vmax}),"category"===a.type&&(D.dataIndex=i),jd(A).eventData=D,t.break&&function(t,e,n,i){n.on("click",function(n){var r={type:uk,breaks:[{start:i.parsedBreak.breakOption.start,end:i.parsedBreak.breakOption.end}]};r[t.axis.dim+"AxisIndex"]=t.componentIndex,e.dispatchAction(r)})}(r,o,A,t.break)}g.push(A),l.add(A)});var _=qi(g,function(t){return{label:t,priority:fk(t).break?t.z2+(y-v+1):t.z2,defaultAttr:{ignore:t.ignore}}});Dk(e,_,l,c)}(t,e,r,s,i,a);var l=e.labelLayoutList;!function(t,e,n,i){var r=e.get(["axisLabel","margin"]);ji(n,function(n,o){var a=dC(n);if(a){var s=a.label,l=fk(s);a.suggestIgnore=s.ignore,s.ignore=!1,ll(Pk,Lk),Pk.x=e.axis.dataToCoord(l.tickValue),Pk.y=t.labelOffset+t.labelDirection*r,Pk.rotation=l.layoutRotation,i.add(Pk),Pk.updateTransform(),i.remove(Pk),Pk.decomposeTransform(),ll(s,Pk),s.markRedraw(),cC(a,!0),dC(a)}})}(t,i,l,o),t.rotation;var c=t.optionHideOverlap;!function(t,e,n){if(LS(t.axis))return;function i(t,i,r){var o=dC(e[i]),a=dC(e[r]);if(o&&a)if(!1===t||o.suggestIgnore)Mk(o.label);else if(a.suggestIgnore)Mk(a.label);else{var s=.1;if(!n){var l=[0,0,0,0];o=pC({marginForce:l},o),a=pC({marginForce:l},a)}gC(o,a,null,{touchThreshold:s})&&Mk(t?a.label:o.label)}}var r=t.get(["axisLabel","showMinLabel"]),o=t.get(["axisLabel","showMaxLabel"]),a=e.length;i(r,0,1),i(o,a-1,a-2)}(i,l,c),c&&function(t){var e=[];function n(t){if(!t.ignore){var e=t.ensureState("emphasis");null==e.ignore&&(e.ignore=!1)}t.ignore=!0}t.sort(function(t,e){return(e.suggestIgnore?1:0)-(t.suggestIgnore?1:0)||e.priority-t.priority});for(var i=0;i.1?"x":"y",u=a.transGroup[c];if(s.sort(function(t,e){return Math.abs(t.label[c]-u)-Math.abs(e.label[c]-u)}),l&&r){var d=o.getExtent(),h=Math.min(d[0],d[1]),p=Math.max(d[0],d[1])-h;r.union(new Do(h,0,p,1))}a.stOccupiedRect=r,a.labelInfoList=s}(t,n,i,l)}function Mk(t){t&&(t.ignore=!0)}function Tk(t,e,n,i,r){for(var o=[],a=[],s=[],l=0;l=0;o--){var a=t[+n[o]],s=a.model,l=a.scale;Bw(l)&&s.get("alignTicks")&&null==s.get("interval")?r.push(a):(AS(l,s),Bw(l)&&(e=a))}r.length&&(e||AS((e=r.pop()).scale,e.model),ji(r,function(t){!function(t,e,n){var i=eS.prototype,r=i.getTicks.call(n),o=i.getTicks.call(n,{expandToNicedExtent:!0}),a=r.length-1,s=i.getInterval.call(n),l=TS(t,e),c=l.extent,u=l.fixMin,d=l.fixMax;"log"===t.type&&(c=Xw(t.base,c,!0)),t.setBreaksFromOption(OS(e)),t.setExtent(c[0],c[1]),t.calcNiceExtent({splitNumber:a,fixMin:u,fixMax:d});var h=i.getExtent.call(t);u&&(c[0]=h[0]),d&&(c[1]=h[1]);var p=i.getInterval.call(t),f=c[0],g=c[1];if(u&&d)p=(g-f)/a;else if(u)for(g=c[0]+p*a;gc[0]&&isFinite(f)&&isFinite(c[0]);)p=$w(p),f=c[1]-p*a;else{t.getTicks().length-1>a&&(p=$w(p));var m=p*a;(f=ql((g=Math.ceil(c[1]/p)*p)-m))<0&&c[0]>=0?(f=0,g=ql(m)):g>0&&c[1]<=0&&(g=0,f=-ql(m))}var v=(r[0].value-o[0].value)/s,y=(r[a].value-o[a].value)/s;i.setExtent.call(t,f+p*v,g+p*y),i.setInterval.call(t,p),(v||y)&&i.setNiceExtent.call(t,f+p,g-p)}(t.scale,t.model,e.scale)}))}}this._updateScale(t,this.model),i(n.x),i(n.y);var r={};ji(n.x,function(t){Bk(n,"y",t,r)}),ji(n.y,function(t){Bk(n,"x",t,r)}),this.resize(this.model,e)},t.prototype.resize=function(t,e,n){var i=xm(t,e),r=this._rect=_m(t.getBoxLayoutParams(),i.refContainer),o=this._axesMap,a=this._coordsList,s=t.get("containLabel");if($k(o,r),!n){var l=function(t,e,n,i,r){var o=new mk(qk);return ji(n,function(n){return ji(n,function(n){if(RS(n.model)){var a=!i;n.axisBuilder=function(t,e,n,i,r,o){for(var a=Nk(t,n),s=!1,l=!1,c=0;c0&&i>0||n<0&&i<0)}(t)}function $k(t,e){ji(t.x,function(t){return Vk(t,e.x,e.width)}),ji(t.y,function(t){return Vk(t,e.y,e.height)})}function Vk(t,e,n){var i=[0,n],r=t.inverse?1:0;t.setExtent(i[r],i[1-r]),function(t,e){var n=t.getExtent(),i=n[0]+n[1];t.toGlobalCoord="x"===t.dim?function(t){return t+e}:function(t){return i-t+e},t.toLocalCoord="x"===t.dim?function(t){return t-e}:function(t){return i-t+e}}(t,e)}function Wk(t,e,n,i,r,o,a){jk(i,r,WS,e,!1,a);var s=[0,0,0,0];c(0),c(1),u(i,0,NaN),u(i,1,NaN);var l=null==function(t,e,n){if(t&&e)for(var i=0,r=t.length;i0});return Cf(i,s,!0,!0,n),$k(r,i),l;function c(t){ji(r[sf[t]],function(e){if(RS(e.model)){var n=o.ensureRecord(e.model),i=n.labelInfoList;if(i)for(var r=0;r0&&!sr(e)&&e>1e-4&&(t/=e),t}}function jk(t,e,n,i,r,o){var a=n===jS;ji(e,function(e){return ji(e,function(e){RS(e.model)&&(!function(t,e,n){var i=Nk(e,n);t.updateCfg(i)}(e.axisBuilder,t,e.model),e.axisBuilder.build(a?{axisTickLabelDetermine:!0}:{axisTickLabelEstimate:!0},{noPxChange:r}))})});var s={x:0,y:0};function l(e){s[sf[1-e]]=t[lf[e]]<=.5*o.refContainer[lf[e]]?0:1-e==1?2:1}l(0),l(1),ji(e,function(t,e){return ji(t,function(t){RS(t.model)&&(("all"===i||a)&&t.axisBuilder.build({axisName:!0},{nameMarginLevel:s[e]}),a&&t.axisBuilder.build({axisLine:!0}))})})}var qk=function(t,e,n,i,r,o){var a="x"===n.axis.dim?"y":"x";_k(t,0,0,i,r,o),NS(t.nameLocation)||ji(e.recordMap[a],function(t){t&&t.labelInfoList&&t.dirVec&&xk(t.labelInfoList,t.dirVec,i,r)})};function Uk(t,e){var n={axesInfo:{},seriesInvolved:!1,coordSysAxesInfo:{},coordSysMap:{}};return function(t,e,n){var i=e.getComponent("tooltip"),r=e.getComponent("axisPointer"),o=r.get("link",!0)||[],a=[];ji(n.getCoordinateSystems(),function(n){if(n.axisPointerEnabled){var s=Zk(n.model),l=t.coordSysAxesInfo[s]={};t.coordSysMap[s]=n;var c=n.model.getModel("tooltip",i);if(ji(n.getAxes(),Zi(p,!1,null)),n.getTooltipAxes&&i&&c.get("show")){var u="axis"===c.get("trigger"),d="cross"===c.get(["axisPointer","type"]),h=n.getTooltipAxes(c.get(["axisPointer","axis"]));(u||d)&&ji(h.baseAxes,Zi(p,!d||"cross",u)),d&&ji(h.otherAxes,Zi(p,"cross",!1))}}function p(i,s,u){var d=u.model.getModel("axisPointer",r),h=d.get("show");if(h&&("auto"!==h||i||Yk(d))){null==s&&(s=d.get("triggerTooltip")),d=i?function(t,e,n,i,r,o){var a=e.getModel("axisPointer"),s={};ji(["type","snap","lineStyle","shadowStyle","label","animation","animationDurationUpdate","animationEasingUpdate","z"],function(t){s[t]=zi(a.get(t))}),s.snap="category"!==t.type&&!!o,"cross"===a.get("type")&&(s.type="line");var l=s.label||(s.label={});if(null==l.show&&(l.show=!1),"cross"===r){var c=a.get(["label","show"]);if(l.show=null==c||c,!o){var u=s.lineStyle=a.get("crossStyle");u&&Fi(l,u.textStyle)}}return t.model.getModel("axisPointer",new lg(s,n,i))}(u,c,r,e,i,s):d;var p=d.get("snap"),f=d.get("triggerEmphasis"),g=Zk(u.model),m=s||p||"category"===u.type,v=t.axesInfo[g]={key:g,axis:u,coordSys:n,axisPointerModel:d,triggerTooltip:s,triggerEmphasis:f,involveSeries:m,snap:p,useHandle:Yk(d),seriesModels:[],linkGroup:null};l[g]=v,t.seriesInvolved=t.seriesInvolved||m;var y=function(t,e){for(var n=e.model,i=e.dim,r=0;r=0||t===e}function Xk(t){var e=(t.ecModel.getComponent("axisPointer")||{}).coordSysAxesInfo;return e&&e.axesInfo[Zk(t)]}function Yk(t){return!!t.get(["handle","show"])}function Zk(t){return t.type+"||"+t.id}var Kk={},Qk=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.prototype.render=function(e,n,i,r){this.axisPointerClass&&function(t){var e=Xk(t);if(e){var n=e.axisPointerModel,i=e.axis.scale,r=n.option,o=n.get("status"),a=n.get("value");null!=a&&(a=i.parse(a));var s=Yk(n);null==o&&(r.status=s?"show":"hide");var l=i.getExtent().slice();l[0]>l[1]&&l.reverse(),(null==a||a>l[1])&&(a=l[1]),aa)return!0;if(o){var s=Xk(t).seriesDataCount,l=i.getExtent();return Math.abs(l[0]-l[1])/s>a}return!1}return!0===n},t.prototype.makeElOption=function(t,e,n,i,r){},t.prototype.createPointerEl=function(t,e,n,i){var r=e.pointer;if(r){var o=lM(t).pointerEl=new zf[r.type](cM(e.pointer));t.add(o)}},t.prototype.createLabelEl=function(t,e,n,i){if(e.label){var r=lM(t).labelEl=new Pd(cM(e.label));t.add(r),fM(r,i)}},t.prototype.updatePointerEl=function(t,e,n){var i=lM(t).pointerEl;i&&e.pointer&&(i.setStyle(e.pointer.style),n(i,{shape:e.pointer.shape}))},t.prototype.updateLabelEl=function(t,e,n,i){var r=lM(t).labelEl;r&&(r.setStyle(e.label.style),n(r,{x:e.label.x,y:e.label.y}),fM(r,i))},t.prototype._renderHandle=function(t){if(!this._dragging&&this.updateHandleTransform){var e,n=this._axisPointerModel,i=this._api.getZr(),r=this._handle,o=n.getModel("handle"),a=n.get("status");if(!o.get("show")||!a||"hide"===a)return r&&i.remove(r),void(this._handle=null);this._handle||(e=!0,r=this._handle=xf(o.get("icon"),{cursor:"move",draggable:!0,onmousemove:function(t){oo(t.event)},onmousedown:uM(this._onHandleDragMove,this,0,0),drift:uM(this._onHandleDragMove,this),ondragend:uM(this._onHandleDragEnd,this)}),i.add(r)),mM(r,n,!1),r.setStyle(o.getItemStyle(null,["color","borderColor","borderWidth","opacity","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]));var s=o.get("size");Ki(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,C_(this,"_doDispatchAxisPointer",o.get("throttle")||0,"fixRate"),this._moveHandleToValue(t,e)}},t.prototype._moveHandleToValue=function(t,e){hM(this._axisPointerModel,!e&&this._moveAnimation,this._handle,gM(this.getHandleTransform(t,this._axisModel,this._axisPointerModel)))},t.prototype._onHandleDragMove=function(t,e){var n=this._handle;if(n){this._dragging=!0;var i=this.updateHandleTransform(gM(n),[t,e],this._axisModel,this._axisPointerModel);this._payloadInfo=i,n.stopAnimation(),n.attr(gM(i)),lM(n).lastProp=null,this._doDispatchAxisPointer()}},t.prototype._doDispatchAxisPointer=function(){if(this._handle){var t=this._payloadInfo,e=this._axisModel;this._api.dispatchAction({type:"updateAxisPointer",x:t.cursorPoint[0],y:t.cursorPoint[1],tooltipOption:t.tooltipOption,axesInfo:[{axisDim:e.axis.dim,axisIndex:e.componentIndex}]})}},t.prototype._onHandleDragEnd=function(){if(this._dragging=!1,this._handle){var t=this._axisPointerModel.get("value");this._moveHandleToValue(t),this._api.dispatchAction({type:"hideTip"})}},t.prototype.clear=function(t){this._lastValue=null,this._lastStatus=null;var e=t.getZr(),n=this._group,i=this._handle;e&&n&&(this._lastGraphicKey=null,n&&e.remove(n),i&&e.remove(i),this._group=null,this._handle=null,this._payloadInfo=null),k_(this,"_doDispatchAxisPointer")},t.prototype.doClear=function(){},t.prototype.buildLabel=function(t,e,n){return{x:t[n=n||0],y:t[1-n],width:e[n],height:e[1-n]}},t}();function hM(t,e,n,i){pM(lM(n).lastProp,i)||(lM(n).lastProp=i,e?tf(n,i,t):(n.stopAnimation(),n.attr(i)))}function pM(t,e){if(nr(t)&&nr(e)){var n=!0;return ji(e,function(e,i){n=n&&pM(t[i],e)}),!!n}return t===e}function fM(t,e){t[e.get(["label","show"])?"show":"hide"]()}function gM(t){return{x:t.x||0,y:t.y||0,rotation:t.rotation||0}}function mM(t,e,n){var i=e.get("z"),r=e.get("zlevel");t&&t.traverse(function(t){"group"!==t.type&&(null!=i&&(t.z=i),null!=r&&(t.zlevel=r),t.silent=n)})}function vM(t,e,n,i,r){var o=yM(n.get("value"),e.axis,e.ecModel,n.get("seriesDataIndices"),{precision:n.get(["label","precision"]),formatter:n.get(["label","formatter"])}),a=n.getModel("label"),s=Jg(a.get("padding")||0),l=a.getFont(),c=gl(o,l),u=r.position,d=c.width+s[1]+s[3],h=c.height+s[0]+s[2],p=r.align;"right"===p&&(u[0]-=d),"center"===p&&(u[0]-=d/2);var f=r.verticalAlign;"bottom"===f&&(u[1]-=h),"middle"===f&&(u[1]-=h/2),function(t,e,n,i){var r=i.getWidth(),o=i.getHeight();t[0]=Math.min(t[0]+e,r)-e,t[1]=Math.min(t[1]+n,o)-n,t[0]=Math.max(t[0],0),t[1]=Math.max(t[1],0)}(u,d,h,i);var g=a.get("backgroundColor");g&&"auto"!==g||(g=e.get(["axisLine","lineStyle","color"])),t.label={x:u[0],y:u[1],style:Vf(a,{text:o,font:l,fill:a.getTextColor(),padding:s,backgroundColor:g}),z2:10}}function yM(t,e,n,i,r){t=e.scale.parse(t);var o=e.scale.getLabel({value:t},{precision:r.precision}),a=r.formatter;if(a){var s={value:DS(e,{value:t}),axisDimension:e.dim,axisIndex:e.index,seriesData:[]};ji(i,function(t){var e=n.getSeriesByIndex(t.seriesIndex),i=t.dataIndexInside,r=e&&e.getDataParams(i);r&&s.seriesData.push(r)}),Ji(a)?o=a.replace("{value}",o):Qi(a)&&(o=a(s))}return o}function _M(t,e,n){var i=[1,0,0,1,0,0];return fo(i,i,n.rotation),po(i,i,n.position),yf([t.dataToCoord(e),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],i)}var bM=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e.prototype.makeElOption=function(t,e,n,i,r){var o=n.axis,a=o.grid,s=i.get("type"),l=xM(a,o).getOtherAxis(o).getGlobalExtent(),c=o.toGlobalCoord(o.dataToCoord(e,!0));if(s&&"none"!==s){var u=function(t){var e,n=t.get("type"),i=t.getModel(n+"Style");return"line"===n?(e=i.getLineStyle()).fill=null:"shadow"===n&&((e=i.getAreaStyle()).stroke=null),e}(i),d=wM[s](o,c,l);d.style=u,t.graphicKey=d.type,t.pointer=d}!function(t,e,n,i,r,o){var a=wk.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=r.get(["label","margin"]),vM(e,i,r,o,{position:_M(i.axis,t,n),align:a.textAlign,verticalAlign:a.textVerticalAlign})}(e,t,Nk(a.getRect(),n),n,i,r)},e.prototype.getHandleTransform=function(t,e,n){var i=Nk(e.axis.grid.getRect(),e,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var r=_M(e.axis,t,i);return{x:r[0],y:r[1],rotation:i.rotation+(i.labelDirection<0?Math.PI:0)}},e.prototype.updateHandleTransform=function(t,e,n,i){var r=n.axis,o=r.grid,a=r.getGlobalExtent(!0),s=xM(o,r).getOtherAxis(r).getGlobalExtent(),l="x"===r.dim?0:1,c=[t.x,t.y];c[l]+=e[l],c[l]=Math.min(a[1],c[l]),c[l]=Math.max(a[0],c[l]);var u=(s[1]+s[0])/2,d=[u,u];d[l]=c[l];return{x:c[0],y:c[1],rotation:t.rotation,cursorPoint:d,tooltipOption:[{verticalAlign:"middle"},{align:"center"}][l]}},e}(dM);function xM(t,e){var n={};return n[e.dim+"AxisIndex"]=e.index,t.getCartesian(n)}var wM={line:function(t,e,n){var i,r,o;return{type:"Line",subPixelOptimize:!0,shape:(i=[e,n[0]],r=[e,n[1]],o=SM(t),{x1:i[o=o||0],y1:i[1-o],x2:r[o],y2:r[1-o]})}},shadow:function(t,e,n){var i,r,o,a=Math.max(1,t.getBandWidth()),s=n[1]-n[0];return{type:"Rect",shape:(i=[e-a/2,n[0]],r=[a,s],o=SM(t),{x:i[o=o||0],y:i[1-o],width:r[o],height:r[1-o]})}}};function SM(t){return"x"===t.dim?0:1}var CM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.type="axisPointer",e.defaultOption={show:"auto",z:50,type:"line",snap:!1,triggerTooltip:!0,triggerEmphasis:!0,value:null,status:null,link:[],animation:null,animationDurationUpdate:200,lineStyle:{color:Tm.color.border,width:1,type:"dashed"},shadowStyle:{color:Tm.color.shadowTint},label:{show:!0,formatter:null,precision:"auto",margin:3,color:Tm.color.neutral00,padding:[5,7,5,7],backgroundColor:Tm.color.accent60,borderColor:null,borderWidth:0,borderRadius:3},handle:{show:!1,icon:"M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z",size:45,margin:50,color:Tm.color.accent40,throttle:40}},e}(Mm),kM=xc(),MM=ji;function TM(t,e,n){if(!mi.node){var i=e.getZr();kM(i).records||(kM(i).records={}),function(t,e){if(kM(t).initialized)return;function n(n,i){t.on(n,function(n){var r=function(t){var e={showTip:[],hideTip:[]},n=function(i){var r=e[i.type];r?r.push(i):(i.dispatchAction=n,t.dispatchAction(i))};return{dispatchAction:n,pendings:e}}(e);MM(kM(t).records,function(t){t&&i(t,n,r.dispatchAction)}),function(t,e){var n,i=t.showTip.length,r=t.hideTip.length;i?n=t.showTip[i-1]:r&&(n=t.hideTip[r-1]);n&&(n.dispatchAction=null,e.dispatchAction(n))}(r.pendings,e)})}kM(t).initialized=!0,n("click",Zi(IM,"click")),n("mousemove",Zi(IM,"mousemove")),n("globalout",AM)}(i,e),(kM(i).records[t]||(kM(i).records[t]={})).handler=n}}function AM(t,e,n){t.handler("leave",null,n)}function IM(t,e,n,i){e.handler(t,n,i)}function DM(t,e){if(!mi.node){var n=e.getZr();(kM(n).records||{})[t]&&(kM(n).records[t]=null)}}var PM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.prototype.render=function(t,e,n){var i=e.getComponent("tooltip"),r=t.get("triggerOn")||i&&i.get("triggerOn")||"mousemove|click";TM("axisPointer",n,function(t,e,n){"none"!==r&&("leave"===t||r.indexOf(t)>=0)&&n({type:"updateAxisPointer",currTrigger:t,x:e&&e.offsetX,y:e&&e.offsetY})})},e.prototype.remove=function(t,e){DM("axisPointer",e)},e.prototype.dispose=function(t,e){DM("axisPointer",e)},e.type="axisPointer",e}(u_);function LM(t,e){var n,i=[],r=t.seriesIndex;if(null==r||!(n=e.getSeriesByIndex(r)))return{point:[]};var o=n.getData(),a=bc(o,t);if(null==a||a<0||Ki(a))return{point:[]};var s=o.getItemGraphicEl(a),l=n.coordinateSystem;if(n.getTooltipPosition)i=n.getTooltipPosition(a)||[];else if(l&&l.dataToPoint)if(t.isStacked){var c=l.getBaseAxis(),u=l.getOtherAxis(c).dim,d=c.dim,h="x"===u||"radius"===u?1:0,p=o.mapDimension(d),f=[];f[h]=o.get(p,a),f[1-h]=o.get(o.getCalculationInfo("stackResultDimension"),a),i=l.dataToPoint(f)||[]}else i=l.dataToPoint(o.getValues(qi(l.dimensions,function(t){return o.mapDimension(t)}),a))||[];else if(s){var g=s.getBoundingRect().clone();g.applyTransform(s.transform),i=[g.x+g.width/2,g.y+g.height/2]}return{point:i,el:s}}var EM=xc();function NM(t,e,n){var i=t.currTrigger,r=[t.x,t.y],o=t,a=t.dispatchAction||Yi(n.dispatchAction,n),s=e.getComponent("axisPointer").coordSysAxesInfo;if(s){BM(r)&&(r=LM({seriesIndex:o.seriesIndex,dataIndex:o.dataIndex},e).point);var l=BM(r),c=o.axesInfo,u=s.axesInfo,d="leave"===i||BM(r),h={},p={},f={list:[],map:{}},g={showPointer:Zi(OM,p),showTooltip:Zi(zM,f)};ji(s.coordSysMap,function(t,e){var n=l||t.containPoint(r);ji(s.coordSysAxesInfo[e],function(t,e){var i=t.axis,o=function(t,e){for(var n=0;n<(t||[]).length;n++){var i=t[n];if(e.axis.dim===i.axisDim&&e.axis.model.componentIndex===i.axisIndex)return i}}(c,t);if(!d&&n&&(!c||o)){var a=o&&o.value;null!=a||l||(a=i.pointToData(r)),null!=a&&RM(t,a,g,!1,h)}})});var m={};return ji(u,function(t,e){var n=t.linkGroup;n&&!p[e]&&ji(n.axesInfo,function(e,i){var r=p[i];if(e!==t&&r){var o=r.value;n.mapper&&(o=t.axis.scale.parse(n.mapper(o,HM(e),HM(t)))),m[t.key]=o}})}),ji(m,function(t,e){RM(u[e],t,g,!0,h)}),function(t,e,n){var i=n.axesInfo=[];ji(e,function(e,n){var r=e.axisPointerModel.option,o=t[n];o?(!e.useHandle&&(r.status="show"),r.value=o.value,r.seriesDataIndices=(o.payloadBatch||[]).slice()):!e.useHandle&&(r.status="hide"),"show"===r.status&&i.push({axisDim:e.axis.dim,axisIndex:e.axis.model.componentIndex,value:r.value})})}(p,u,h),function(t,e,n,i){if(BM(e)||!t.list.length)return void i({type:"hideTip"});var r=((t.list[0].dataByAxis[0]||{}).seriesDataIndices||[])[0]||{};i({type:"showTip",escapeConnect:!0,x:e[0],y:e[1],tooltipOption:n.tooltipOption,position:n.position,dataIndexInside:r.dataIndexInside,dataIndex:r.dataIndex,seriesIndex:r.seriesIndex,dataByCoordSys:t.list})}(f,r,t,a),function(t,e,n){var i=n.getZr(),r="axisPointerLastHighlights",o=EM(i)[r]||{},a=EM(i)[r]={};ji(t,function(t,e){var n=t.axisPointerModel.option;"show"===n.status&&t.triggerEmphasis&&ji(n.seriesDataIndices,function(t){var e=t.seriesIndex+" | "+t.dataIndex;a[e]=t})});var s=[],l=[];ji(o,function(t,e){!a[e]&&l.push(t)}),ji(a,function(t,e){!o[e]&&s.push(t)}),l.length&&n.dispatchAction({type:"downplay",escapeConnect:!0,notBlur:!0,batch:l}),s.length&&n.dispatchAction({type:"highlight",escapeConnect:!0,notBlur:!0,batch:s})}(u,0,n),h}}function RM(t,e,n,i,r){var o=t.axis;if(!o.scale.isBlank()&&o.containData(e))if(t.involveSeries){var a=function(t,e){var n=e.axis,i=n.dim,r=t,o=[],a=Number.MAX_VALUE,s=-1;return ji(e.seriesModels,function(e,l){var c,u,d=e.getData().mapDimensionsAll(i);if(e.getAxisTooltipData){var h=e.getAxisTooltipData(d,t,n);u=h.dataIndices,c=h.nestestValue}else{if(!(u=e.indicesOfNearest(i,d[0],t,"category"===n.type?.5:null)).length)return;c=e.getData().get(d[0],u[0])}if(null!=c&&isFinite(c)){var p=t-c,f=Math.abs(p);f<=a&&((f=0&&s<0)&&(a=f,s=p,r=c,o.length=0),ji(u,function(t){o.push({seriesIndex:e.seriesIndex,dataIndexInside:t,dataIndex:e.getData().getRawIndex(t)})}))}}),{payloadBatch:o,snapToValue:r}}(e,t),s=a.payloadBatch,l=a.snapToValue;s[0]&&null==r.seriesIndex&&Bi(r,s[0]),!i&&t.snap&&o.containData(l)&&null!=l&&(e=l),n.showPointer(t,e,s),n.showTooltip(t,a,l)}else n.showPointer(t,e)}function OM(t,e,n,i){t[e.key]={value:n,payloadBatch:i}}function zM(t,e,n,i){var r=n.payloadBatch,o=e.axis,a=o.model,s=e.axisPointerModel;if(e.triggerTooltip&&r.length){var l=e.coordSys.model,c=Zk(l),u=t.map[c];u||(u=t.map[c]={coordSysId:l.id,coordSysIndex:l.componentIndex,coordSysType:l.type,coordSysMainType:l.mainType,dataByAxis:[]},t.list.push(u)),u.dataByAxis.push({axisDim:o.dim,axisIndex:a.componentIndex,axisType:a.type,axisId:a.id,value:i,valueLabelOpt:{precision:s.get(["label","precision"]),formatter:s.get(["label","formatter"])},seriesDataIndices:r.slice()})}}function HM(t){var e=t.axis.model,n={},i=n.axisDim=t.axis.dim;return n.axisIndex=n[i+"AxisIndex"]=e.componentIndex,n.axisName=n[i+"AxisName"]=e.name,n.axisId=n[i+"AxisId"]=e.id,n}function BM(t){return!t||null==t[0]||isNaN(t[0])||null==t[1]||isNaN(t[1])}function FM(t){Qk.registerAxisPointerClass("CartesianAxisPointer",bM),t.registerComponentModel(CM),t.registerComponentView(PM),t.registerPreprocessor(function(t){if(t){(!t.axisPointer||0===t.axisPointer.length)&&(t.axisPointer={});var e=t.axisPointer.link;e&&!Ki(e)&&(t.axisPointer.link=[e])}}),t.registerProcessor(t.PRIORITY.PROCESSOR.STATISTIC,function(t,e){t.getComponent("axisPointer").coordSysAxesInfo=Uk(t,e)}),t.registerAction({type:"updateAxisPointer",event:"updateAxisPointer",update:":updateAxisPointer"},NM)}var $M=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.type="tooltip",e.dependencies=["axisPointer"],e.defaultOption={z:60,show:!0,showContent:!0,trigger:"item",triggerOn:"mousemove|click",alwaysShowContent:!1,renderMode:"auto",confine:null,showDelay:0,hideDelay:100,transitionDuration:.4,displayTransition:!0,enterable:!1,backgroundColor:Tm.color.neutral00,shadowBlur:10,shadowColor:"rgba(0, 0, 0, .2)",shadowOffsetX:1,shadowOffsetY:2,borderRadius:4,borderWidth:1,defaultBorderColor:Tm.color.border,padding:null,extraCssText:"",axisPointer:{type:"line",axis:"auto",animation:"auto",animationDurationUpdate:200,animationEasingUpdate:"exponentialOut",crossStyle:{color:Tm.color.borderShade,width:1,type:"dashed",textStyle:{}}},textStyle:{color:Tm.color.tertiary,fontSize:14}},e}(Mm);function VM(t){var e=t.get("confine");return null!=e?!!e:"richText"===t.get("renderMode")}function WM(t){if(mi.domSupported)for(var e=document.documentElement.style,n=0,i=t.length;n0&&r.push(function(t,e,n){var i="cubic-bezier(0.23,1,0.32,1)",r="",o="";return n&&(o="opacity"+(r=" "+t/2+"s "+i)+",visibility"+r),e||(r=" "+t+"s "+i,o+=(o.length?",":"")+(mi.transformSupported?""+GM+r:",left"+r+",top"+r)),UM+":"+o}(o,n,i)),a&&r.push("background-color:"+a),ji(["width","color","radius"],function(e){var n="border-"+e,i=Qg(n),o=t.get(i);null!=o&&r.push(n+":"+o+("color"===e?"":"px"))}),r.push(function(t){var e=[],n=t.get("fontSize"),i=t.getTextColor();i&&e.push("color:"+i),e.push("font:"+t.getFont());var r=cr(t.get("lineHeight"),Math.round(3*n/2));n&&e.push("line-height:"+r+"px");var o=t.get("textShadowColor"),a=t.get("textShadowBlur")||0,s=t.get("textShadowOffsetX")||0,l=t.get("textShadowOffsetY")||0;return o&&a&&e.push("text-shadow:"+s+"px "+l+"px "+a+"px "+o),ji(["decoration","align"],function(n){var i=t.get(n);i&&e.push("text-"+n+":"+i)}),e.join(";")}(d)),null!=h&&r.push("padding:"+Jg(h).join("px ")+"px"),r.join(";")+";"}function KM(t,e,n,i,r){var o=e&&e.painter;if(n){var a=o&&o.getViewportRoot();a&&function(t,e,n,i,r){Ur(qr,e,i,r,!0)&&Ur(t,n,qr[0],qr[1])}(t,a,n,i,r)}else{t[0]=i,t[1]=r;var s=o&&o.getViewportRootOffset();s&&(t[0]+=s.offsetLeft,t[1]+=s.offsetTop)}t[2]=t[0]/e.getWidth(),t[3]=t[1]/e.getHeight()}var QM=function(){function t(t,e){if(this._show=!1,this._styleCoord=[0,0,0,0],this._enterable=!0,this._alwaysShowContent=!1,this._firstShow=!0,this._longHide=!0,mi.wxa)return null;var n=document.createElement("div");n.domBelongToZr=!0,this.el=n;var i=this._zr=t.getZr(),r=e.appendTo,o=r&&(Ji(r)?document.querySelector(r):or(r)?r:Qi(r)&&r(t.getDom()));KM(this._styleCoord,i,o,t.getWidth()/2,t.getHeight()/2),(o||t.getDom()).appendChild(n),this._api=t,this._container=o;var a=this;n.onmouseenter=function(){a._enterable&&(clearTimeout(a._hideTimeout),a._show=!0),a._inContent=!0},n.onmousemove=function(t){if(t=t||window.event,!a._enterable){var e=i.handler;io(i.painter.getViewportRoot(),t,!0),e.dispatch("mousemove",t)}},n.onmouseleave=function(){a._inContent=!1,a._enterable&&a._show&&a.hideLater(a._hideDelay)}}return t.prototype.update=function(t){if(!this._container){var e=this._api.getDom(),n=(o="position",(a=(r=e).currentStyle||document.defaultView&&document.defaultView.getComputedStyle(r))?a[o]:null),i=e.style;"absolute"!==i.position&&"absolute"!==n&&(i.position="relative")}var r,o,a,s=t.get("alwaysShowContent");s&&this._moveIfResized(),this._alwaysShowContent=s,this._enableDisplayTransition=t.get("displayTransition")&&t.get("transitionDuration")>0,this.el.className=t.get("className")||""},t.prototype.show=function(t,e){clearTimeout(this._hideTimeout),clearTimeout(this._longHideTimeout);var n=this.el,i=n.style,r=this._styleCoord;n.innerHTML?i.cssText=XM+ZM(t,!this._firstShow,this._longHide,this._enableDisplayTransition)+YM(r[0],r[1],!0)+"border-color:"+rm(e)+";"+(t.get("extraCssText")||"")+";pointer-events:"+(this._enterable?"auto":"none"):i.display="none",this._show=!0,this._firstShow=!1,this._longHide=!1},t.prototype.setContent=function(t,e,n,i,r){var o=this.el;if(null!=t){var a="";if(Ji(r)&&"item"===n.get("trigger")&&!VM(n)&&(a=function(t,e,n){if(!Ji(n)||"inside"===n)return"";var i=t.get("backgroundColor"),r=t.get("borderWidth");e=rm(e);var o,a,s="left"===(o=n)?"right":"right"===o?"left":"top"===o?"bottom":"top",l=Math.max(1.5*Math.round(r),6),c="",u=GM+":";$i(["left","right"],s)>-1?(c+="top:50%",u+="translateY(-50%) rotate("+(a="left"===s?-225:-45)+"deg)"):(c+="left:50%",u+="translateX(-50%) rotate("+(a="top"===s?225:45)+"deg)");var d=a*Math.PI/180,h=l+r,p=h*Math.abs(Math.cos(d))+h*Math.abs(Math.sin(d)),f=e+" solid "+r+"px;";return'
'}(n,i,r)),Ji(t))o.innerHTML=t+a;else if(t){o.innerHTML="",Ki(t)||(t=[t]);for(var s=0;s=0?this._tryShow(n,i):"leave"===e&&this._hide(i))},this))},e.prototype._keepShow=function(){var t=this._tooltipModel,e=this._ecModel,n=this._api,i=t.get("triggerOn");if(null!=this._lastX&&null!=this._lastY&&"none"!==i&&"click"!==i){var r=this;clearTimeout(this._refreshUpdateTimeout),this._refreshUpdateTimeout=setTimeout(function(){!n.isDisposed()&&r.manuallyShowTip(t,e,n,{x:r._lastX,y:r._lastY,dataByCoordSys:r._lastDataByCoordSys})})}},e.prototype.manuallyShowTip=function(t,e,n,i){if(i.from!==this.uid&&!mi.node&&n.getDom()){var r=aT(i,n);this._ticket="";var o=i.dataByCoordSys,a=function(t,e,n){var i=Cc(t).queryOptionMap,r=i.keys()[0];if(!r||"series"===r)return;var o=Mc(e,r,i.get(r),{useDefault:!1,enableAll:!1,enableNone:!1}),a=o.models[0];if(!a)return;var s,l=n.getViewOfComponentModel(a);if(l.group.traverse(function(e){var n=jd(e).tooltipConfig;if(n&&n.name===t.name)return s=e,!0}),s)return{componentMainType:r,componentIndex:a.componentIndex,el:s}}(i,e,n);if(a){var s=a.el.getBoundingRect().clone();s.applyTransform(a.el.transform),this._tryShow({offsetX:s.x+s.width/2,offsetY:s.y+s.height/2,target:a.el,position:i.position,positionDefault:"bottom"},r)}else if(i.tooltip&&null!=i.x&&null!=i.y){var l=iT;l.x=i.x,l.y=i.y,l.update(),jd(l).tooltipConfig={name:null,option:i.tooltip},this._tryShow({offsetX:i.x,offsetY:i.y,target:l},r)}else if(o)this._tryShow({offsetX:i.x,offsetY:i.y,position:i.position,dataByCoordSys:o,tooltipOption:i.tooltipOption},r);else if(null!=i.seriesIndex){if(this._manuallyAxisShowTip(t,e,n,i))return;var c=LM(i,e),u=c.point[0],d=c.point[1];null!=u&&null!=d&&this._tryShow({offsetX:u,offsetY:d,target:c.el,position:i.position,positionDefault:"bottom"},r)}else null!=i.x&&null!=i.y&&(n.dispatchAction({type:"updateAxisPointer",x:i.x,y:i.y}),this._tryShow({offsetX:i.x,offsetY:i.y,position:i.position,target:n.getZr().findHover(i.x,i.y).target},r))}},e.prototype.manuallyHideTip=function(t,e,n,i){var r=this._tooltipContent;this._tooltipModel&&r.hideLater(this._tooltipModel.get("hideDelay")),this._lastX=this._lastY=this._lastDataByCoordSys=null,i.from!==this.uid&&this._hide(aT(i,n))},e.prototype._manuallyAxisShowTip=function(t,e,n,i){var r=i.seriesIndex,o=i.dataIndex,a=e.getComponent("axisPointer").coordSysAxesInfo;if(null!=r&&null!=o&&null!=a){var s=e.getSeriesByIndex(r);if(s)if("axis"===oT([s.getData().getItemModel(o),s,(s.coordinateSystem||{}).model],this._tooltipModel).get("trigger"))return n.dispatchAction({type:"updateAxisPointer",seriesIndex:r,dataIndex:o,position:i.position}),!0}},e.prototype._tryShow=function(t,e){var n=t.target;if(this._tooltipModel){this._lastX=t.offsetX,this._lastY=t.offsetY;var i=t.dataByCoordSys;if(i&&i.length)this._showAxisTooltip(i,t);else if(n){var r,o;if("legend"===jd(n).ssrType)return;this._lastDataByCoordSys=null,cb(n,function(t){if(t.tooltipDisabled)return r=o=null,!0;r||o||(null!=jd(t).dataIndex?r=t:null!=jd(t).tooltipConfig&&(o=t))},!0),r?this._showSeriesItemTooltip(t,r,e):o?this._showComponentItemTooltip(t,o,e):this._hide(e)}else this._lastDataByCoordSys=null,this._hide(e)}},e.prototype._showOrMove=function(t,e){var n=t.get("showDelay");e=Yi(e,this),clearTimeout(this._showTimout),n>0?this._showTimout=setTimeout(e,n):e()},e.prototype._showAxisTooltip=function(t,e){var n=this._ecModel,i=this._tooltipModel,r=[e.offsetX,e.offsetY],o=oT([e.tooltipOption],i),a=this._renderMode,s=[],l=Vy("section",{blocks:[],noHeader:!0}),c=[],u=new Qy;ji(t,function(t){ji(t.dataByAxis,function(t){var e=n.getComponent(t.axisDim+"Axis",t.axisIndex),r=t.value;if(e&&null!=r){var o=yM(r,e.axis,n,t.seriesDataIndices,t.valueLabelOpt),d=Vy("section",{header:o,noHeader:!fr(o),sortBlocks:!0,blocks:[]});l.blocks.push(d),ji(t.seriesDataIndices,function(l){var h=n.getSeriesByIndex(l.seriesIndex),p=l.dataIndexInside,f=h.getDataParams(p);if(!(f.dataIndex<0)){f.axisDim=t.axisDim,f.axisIndex=t.axisIndex,f.axisType=t.axisType,f.axisId=t.axisId,f.axisValue=DS(e.axis,{value:r}),f.axisValueLabel=o,f.marker=u.makeTooltipMarker("item",rm(f.color),a);var g=cy(h.formatTooltip(p,!0,null)),m=g.frag;if(m){var v=oT([h],i).get("valueFormatter");d.blocks.push(v?Bi({valueFormatter:v},m):m)}g.text&&c.push(g.text),s.push(f)}})}})}),l.blocks.reverse(),c.reverse();var d=e.position,h=o.get("order"),p=Xy(l,u,a,h,n.get("useUTC"),o.get("textStyle"));p&&c.unshift(p);var f="richText"===a?"\n\n":"
",g=c.join(f);this._showOrMove(o,function(){this._updateContentNotChangedOnAxis(t,s)?this._updatePosition(o,d,r[0],r[1],this._tooltipContent,s):this._showTooltipContent(o,g,s,Math.random()+"",r[0],r[1],d,null,u)})},e.prototype._showSeriesItemTooltip=function(t,e,n){var i=this._ecModel,r=jd(e),o=r.seriesIndex,a=i.getSeriesByIndex(o),s=r.dataModel||a,l=r.dataIndex,c=r.dataType,u=s.getData(c),d=this._renderMode,h=t.positionDefault,p=oT([u.getItemModel(l),s,a&&(a.coordinateSystem||{}).model],this._tooltipModel,h?{position:h}:null),f=p.get("trigger");if(null==f||"item"===f){var g=s.getDataParams(l,c),m=new Qy;g.marker=m.makeTooltipMarker("item",rm(g.color),d);var v=cy(s.formatTooltip(l,!1,c)),y=p.get("order"),_=p.get("valueFormatter"),b=v.frag,x=b?Xy(_?Bi({valueFormatter:_},b):b,m,d,y,i.get("useUTC"),p.get("textStyle")):v.text,w="item_"+s.name+"_"+l;this._showOrMove(p,function(){this._showTooltipContent(p,x,g,w,t.offsetX,t.offsetY,t.position,t.target,m)}),n({type:"showTip",dataIndexInside:l,dataIndex:u.getRawIndex(l),seriesIndex:o,from:this.uid})}},e.prototype._showComponentItemTooltip=function(t,e,n){var i="html"===this._renderMode,r=jd(e),o=r.tooltipConfig.option||{},a=o.encodeHTMLContent;if(Ji(o)){o={content:o,formatter:o},a=!0}a&&i&&o.content&&((o=zi(o)).content=Zr(o.content));var s=[o],l=this._ecModel.getComponent(r.componentMainType,r.componentIndex);l&&s.push(l),s.push({formatter:o.content});var c=t.positionDefault,u=oT(s,this._tooltipModel,c?{position:c}:null),d=u.get("content"),h=Math.random()+"",p=new Qy;this._showOrMove(u,function(){var n=zi(u.get("formatterParams")||{});this._showTooltipContent(u,d,n,h,t.offsetX,t.offsetY,t.position,e,p)}),n({type:"showTip",from:this.uid})},e.prototype._showTooltipContent=function(t,e,n,i,r,o,a,s,l){if(this._ticket="",t.get("showContent")&&t.get("show")){var c=this._tooltipContent;c.setEnterable(t.get("enterable"));var u=t.get("formatter");a=a||t.get("position");var d=e,h=this._getNearestPoint([r,o],n,t.get("trigger"),t.get("borderColor"),t.get("defaultBorderColor",!0)).color;if(u)if(Ji(u)){var p=t.ecModel.get("useUTC"),f=Ki(n)?n[0]:n;d=u,f&&f.axisType&&f.axisType.indexOf("time")>=0&&(d=Ng(f.axisValue,d,p)),d=im(d,n,!0)}else if(Qi(u)){var g=Yi(function(e,i){e===this._ticket&&(c.setContent(i,l,t,h,a),this._updatePosition(t,a,r,o,c,n,s))},this);this._ticket=i,d=u(n,i,g)}else d=u;c.setContent(d,l,t,h,a),c.show(t,h),this._updatePosition(t,a,r,o,c,n,s)}},e.prototype._getNearestPoint=function(t,e,n,i,r){return"axis"===n||Ki(e)?{color:i||r}:Ki(e)?void 0:{color:i||e.color||e.borderColor}},e.prototype._updatePosition=function(t,e,n,i,r,o,a){var s=this._api.getWidth(),l=this._api.getHeight();e=e||t.get("position");var c=r.getSize(),u=t.get("align"),d=t.get("verticalAlign"),h=a&&a.getBoundingRect().clone();if(a&&h.applyTransform(a.transform),Qi(e)&&(e=e([n,i],o,r.el,h,{viewSize:[s,l],contentSize:c.slice()})),Ki(e))n=Wl(e[0],s),i=Wl(e[1],l);else if(nr(e)){var p=e;p.width=c[0],p.height=c[1];var f=_m(p,{width:s,height:l});n=f.x,i=f.y,u=null,d=null}else if(Ji(e)&&a){var g=function(t,e,n,i){var r=n[0],o=n[1],a=Math.ceil(Math.SQRT2*i)+8,s=0,l=0,c=e.width,u=e.height;switch(t){case"inside":s=e.x+c/2-r/2,l=e.y+u/2-o/2;break;case"top":s=e.x+c/2-r/2,l=e.y-o-a;break;case"bottom":s=e.x+c/2-r/2,l=e.y+u+a;break;case"left":s=e.x-r-a,l=e.y+u/2-o/2;break;case"right":s=e.x+c+a,l=e.y+u/2-o/2}return[s,l]}(e,h,c,t.get("borderWidth"));n=g[0],i=g[1]}else{g=function(t,e,n,i,r,o,a){var s=n.getSize(),l=s[0],c=s[1];null!=o&&(t+l+o+2>i?t-=l+o:t+=o);null!=a&&(e+c+a>r?e-=c+a:e+=a);return[t,e]}(n,i,r,s,l,u?null:20,d?null:20);n=g[0],i=g[1]}if(u&&(n-=sT(u)?c[0]/2:"right"===u?c[0]:0),d&&(i-=sT(d)?c[1]/2:"bottom"===d?c[1]:0),VM(t)){g=function(t,e,n,i,r){var o=n.getSize(),a=o[0],s=o[1];return t=Math.min(t+a,i)-a,e=Math.min(e+s,r)-s,t=Math.max(t,0),e=Math.max(e,0),[t,e]}(n,i,r,s,l);n=g[0],i=g[1]}r.moveTo(n,i)},e.prototype._updateContentNotChangedOnAxis=function(t,e){var n=this._lastDataByCoordSys,i=this._cbParamsList,r=!!n&&n.length===t.length;return r&&ji(n,function(n,o){var a=n.dataByAxis||[],s=(t[o]||{}).dataByAxis||[];(r=r&&a.length===s.length)&&ji(a,function(t,n){var o=s[n]||{},a=t.seriesDataIndices||[],l=o.seriesDataIndices||[];(r=r&&t.value===o.value&&t.axisType===o.axisType&&t.axisId===o.axisId&&a.length===l.length)&&ji(a,function(t,e){var n=l[e];r=r&&t.seriesIndex===n.seriesIndex&&t.dataIndex===n.dataIndex}),i&&ji(t.seriesDataIndices,function(t){var n=t.seriesIndex,o=e[n],a=i[n];o&&a&&a.data!==o.data&&(r=!1)})})}),this._lastDataByCoordSys=t,this._cbParamsList=e,!!r},e.prototype._hide=function(t){this._lastDataByCoordSys=null,t({type:"hideTip",from:this.uid})},e.prototype.dispose=function(t,e){!mi.node&&e.getDom()&&(k_(this,"_updatePosition"),this._tooltipContent.dispose(),DM("itemTooltip",e))},e.type="tooltip",e}(u_);function oT(t,e,n){var i,r=e.ecModel;n?(i=new lg(n,r,r),i=new lg(e.option,i,r)):i=e;for(var o=t.length-1;o>=0;o--){var a=t[o];a&&(a instanceof lg&&(a=a.get("tooltip",!0)),Ji(a)&&(a={formatter:a}),a&&(i=new lg(a,i,r)))}return i}function aT(t,e){return t.dispatchAction||Yi(e.dispatchAction,e)}function sT(t){return"center"===t||"middle"===t}var lT=Math.sin,cT=Math.cos,uT=Math.PI,dT=2*Math.PI,hT=180/uT,pT=function(){function t(){}return t.prototype.reset=function(t){this._start=!0,this._d=[],this._str="",this._p=Math.pow(10,t||4)},t.prototype.moveTo=function(t,e){this._add("M",t,e)},t.prototype.lineTo=function(t,e){this._add("L",t,e)},t.prototype.bezierCurveTo=function(t,e,n,i,r,o){this._add("C",t,e,n,i,r,o)},t.prototype.quadraticCurveTo=function(t,e,n,i){this._add("Q",t,e,n,i)},t.prototype.arc=function(t,e,n,i,r,o){this.ellipse(t,e,n,n,0,i,r,o)},t.prototype.ellipse=function(t,e,n,i,r,o,a,s){var l=a-o,c=!s,u=Math.abs(l),d=ts(u-dT)||(c?l>=dT:-l>=dT),h=l>0?l%dT:l%dT+dT,p=!1;p=!!d||!ts(u)&&h>=uT==!!c;var f=t+n*cT(o),g=e+i*lT(o);this._start&&this._add("M",f,g);var m=Math.round(r*hT);if(d){var v=1/this._p,y=(c?1:-1)*(dT-v);this._add("A",n,i,m,1,+c,t+n*cT(o+y),e+i*lT(o+y)),v>.01&&this._add("A",n,i,m,0,+c,f,g)}else{var _=t+n*cT(a),b=e+i*lT(a);this._add("A",n,i,m,+p,+c,_,b)}},t.prototype.rect=function(t,e,n,i){this._add("M",t,e),this._add("l",n,0),this._add("l",0,i),this._add("l",-n,0),this._add("Z")},t.prototype.closePath=function(){this._d.length>0&&this._add("Z")},t.prototype._add=function(t,e,n,i,r,o,a,s,l){for(var c=[],u=this._p,d=1;d"}(r,o)+("style"!==r?Zr(a):a||"")+(i?""+n+qi(i,function(e){return t(e)}).join(n)+n:"")+("")}(t)}function kT(t){return{zrId:t,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function MT(t,e,n,i){return ST("svg","root",{width:t,height:e,xmlns:_T,"xmlns:xlink":bT,version:"1.1",baseProfile:"full",viewBox:!!i&&"0 0 "+t+" "+e},n)}var TT=0;function AT(){return TT++}var IT={cubicIn:"0.32,0,0.67,0",cubicOut:"0.33,1,0.68,1",cubicInOut:"0.65,0,0.35,1",quadraticIn:"0.11,0,0.5,0",quadraticOut:"0.5,1,0.89,1",quadraticInOut:"0.45,0,0.55,1",quarticIn:"0.5,0,0.75,0",quarticOut:"0.25,1,0.5,1",quarticInOut:"0.76,0,0.24,1",quinticIn:"0.64,0,0.78,0",quinticOut:"0.22,1,0.36,1",quinticInOut:"0.83,0,0.17,1",sinusoidalIn:"0.12,0,0.39,0",sinusoidalOut:"0.61,1,0.88,1",sinusoidalInOut:"0.37,0,0.63,1",exponentialIn:"0.7,0,0.84,0",exponentialOut:"0.16,1,0.3,1",exponentialInOut:"0.87,0,0.13,1",circularIn:"0.55,0,1,0.45",circularOut:"0,0.55,0.45,1",circularInOut:"0.85,0,0.15,1"},DT="transform-origin";function PT(t,e,n){var i=Bi({},t.shape);Bi(i,e),t.buildPath(n,i);var r=new pT;return r.reset(us(t)),n.rebuildPath(r,1),r.generateStr(),r.getStr()}function LT(t,e){var n=e.originX,i=e.originY;(n||i)&&(t[DT]=n+"px "+i+"px")}var ET={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function NT(t,e){var n=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[n]=t,n}function RT(t){return Ji(t)?IT[t]?"cubic-bezier("+IT[t]+")":Ma(t)?t:"":""}function OT(t,e,n,i){var r=t.animators,o=r.length,a=[];if(t instanceof zp){var s=function(t,e,n){var i,r,o=t.shape.paths,a={};if(ji(o,function(t){var e=kT(n.zrId);e.animation=!0,OT(t,{},e,!0);var o=e.cssAnims,s=e.cssNodes,l=Xi(o),c=l.length;if(c){var u=o[r=l[c-1]];for(var d in u){var h=u[d];a[d]=a[d]||{d:""},a[d].d+=h.d||""}for(var p in s){var f=s[p].animation;f.indexOf(r)>=0&&(i=f)}}}),i){e.d=!1;var s=NT(a,n);return i.replace(r,s)}}(t,e,n);if(s)a.push(s);else if(!o)return}else if(!o)return;for(var l={},c=0;c0}).length)return NT(u,n)+" "+r[0]+" both"}for(var m in l){(s=g(l[m]))&&a.push(s)}if(a.length){var v=n.zrId+"-cls-"+AT();n.cssNodes["."+v]={animation:a.join(",")},e.class=v}}function zT(t,e,n,i){var r=JSON.stringify(t),o=n.cssStyleCache[r];o||(o=n.zrId+"-cls-"+AT(),n.cssStyleCache[r]=o,n.cssNodes["."+o+":hover"]=t),e.class=e.class?e.class+" "+o:o}var HT=Math.round;function BT(t){return t&&Ji(t.src)}function FT(t){return t&&Qi(t.toDataURL)}function $T(t,e,n,i){yT(function(r,o){var a="fill"===r||"stroke"===r;a&&ls(o)?QT(e,t,r,i):a&&os(o)?JT(n,t,r,i):t[r]=o,a&&i.ssr&&"none"===o&&(t["pointer-events"]="visible")},e,n,!1),function(t,e,n){var i=t.style;if(function(t){return t&&(t.shadowBlur||t.shadowOffsetX||t.shadowOffsetY)}(i)){var r=function(t){var e=t.style,n=t.getGlobalScale();return[e.shadowColor,(e.shadowBlur||0).toFixed(2),(e.shadowOffsetX||0).toFixed(2),(e.shadowOffsetY||0).toFixed(2),n[0],n[1]].join(",")}(t),o=n.shadowCache,a=o[r];if(!a){var s=t.getGlobalScale(),l=s[0],c=s[1];if(!l||!c)return;var u=i.shadowOffsetX||0,d=i.shadowOffsetY||0,h=i.shadowBlur,p=Qa(i.shadowColor),f=p.opacity,g=p.color,m=h/2/l+" "+h/2/c;a=n.zrId+"-s"+n.shadowIdx++,n.defs[a]=ST("filter",a,{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},[ST("feDropShadow","",{dx:u/l,dy:d/c,stdDeviation:m,"flood-color":g,"flood-opacity":f})]),o[r]=a}e.filter=cs(a)}}(n,t,i)}function VT(t,e){var n=function(t){if("function"==typeof Rl)return Rl(t)}(e);n&&(n.each(function(e,n){null!=e&&(t[(xT+n).toLowerCase()]=e+"")}),e.isSilent()&&(t[xT+"silent"]="true"))}function WT(t){return ts(t[0]-1)&&ts(t[1])&&ts(t[2])&&ts(t[3]-1)}function jT(t,e,n){if(e&&(!function(t){return ts(t[4])&&ts(t[5])}(e)||!WT(e))){var i=1e4;t.transform=WT(e)?"translate("+HT(e[4]*i)/i+" "+HT(e[5]*i)/i+")":function(t){return"matrix("+es(t[0])+","+es(t[1])+","+es(t[2])+","+es(t[3])+","+ns(t[4])+","+ns(t[5])+")"}(e)}}function qT(t,e,n){for(var i=t.points,r=[],o=0;o=0&&a||o;s&&(r=Za(s))}var l=i.lineWidth;l&&(l/=!i.strokeNoScale&&t.transform?t.transform[0]:1);var c={cursor:"pointer"};r&&(c.fill=r),i.stroke&&(c.stroke=i.stroke),l&&(c["stroke-width"]=l),zT(c,e,n)}}(t,o,e),ST(s,t.id+"",o)}function KT(t,e){return t instanceof gd?ZT(t,e):t instanceof bd?function(t,e){var n=t.style,i=n.image;if(i&&!Ji(i)&&(BT(i)?i=i.src:FT(i)&&(i=i.toDataURL())),i){var r=n.x||0,o=n.y||0,a={href:i,width:n.width,height:n.height};return r&&(a.x=r),o&&(a.y=o),jT(a,t.transform),$T(a,n,t,e),VT(a,t),e.animation&&OT(t,a,e),ST("image",t.id+"",a)}}(t,e):t instanceof vd?function(t,e){var n=t.style,i=n.text;if(null!=i&&(i+=""),i&&!isNaN(n.x)&&!isNaN(n.y)){var r=n.font||yi,o=n.x||0,a=function(t,e,n){return"top"===n?t+=e/2:"bottom"===n&&(t-=e/2),t}(n.y||0,yl(r),n.textBaseline),s={"dominant-baseline":"central","text-anchor":is[n.textAlign]||n.textAlign};if(zd(n)){var l="",c=n.fontStyle,u=Rd(n.fontSize);if(!parseFloat(u))return;var d=n.fontFamily||vi,h=n.fontWeight;l+="font-size:"+u+";font-family:"+d+";",c&&"normal"!==c&&(l+="font-style:"+c+";"),h&&"normal"!==h&&(l+="font-weight:"+h+";"),s.style=l}else s.style="font: "+r;return i.match(/\s/)&&(s["xml:space"]="preserve"),o&&(s.x=o),a&&(s.y=a),jT(s,t.transform),$T(s,n,t,e),VT(s,t),e.animation&&OT(t,s,e),ST("text",t.id+"",s,void 0,i)}}(t,e):void 0}function QT(t,e,n,i){var r,o=t[n],a={gradientUnits:o.global?"userSpaceOnUse":"objectBoundingBox"};if(as(o))r="linearGradient",a.x1=o.x,a.y1=o.y,a.x2=o.x2,a.y2=o.y2;else{if(!ss(o))return;r="radialGradient",a.cx=cr(o.x,.5),a.cy=cr(o.y,.5),a.r=cr(o.r,.5)}for(var s=o.colorStops,l=[],c=0,u=s.length;cl?fA(t,null==n[d+1]?null:n[d+1].elm,n,s,d):gA(t,e,a,l))}(n,i,r):uA(r)?(uA(t.text)&&sA(n,""),fA(n,null,r,0,r.length-1)):uA(i)?gA(n,i,0,i.length-1):uA(t.text)&&sA(n,""):t.text!==e.text&&(uA(i)&&gA(n,i,0,i.length-1),sA(n,e.text)))}var yA=0,_A=function(){function t(t,e,n){if(this.type="svg",this.refreshHover=function(){},this.configLayer=function(){},this.storage=e,this._opts=n=Bi({},n),this.root=t,this._id="zr"+yA++,this._oldVNode=MT(n.width,n.height),t&&!n.ssr){var i=this._viewport=document.createElement("div");i.style.cssText="position:relative;overflow:hidden";var r=this._svgDom=this._oldVNode.elm=wT("svg");mA(null,this._oldVNode),i.appendChild(r),t.appendChild(i)}this.resize(n.width,n.height)}return t.prototype.getType=function(){return this.type},t.prototype.getViewportRoot=function(){return this._viewport},t.prototype.getViewportRootOffset=function(){var t=this.getViewportRoot();if(t)return{offsetLeft:t.offsetLeft||0,offsetTop:t.offsetTop||0}},t.prototype.getSvgDom=function(){return this._svgDom},t.prototype.refresh=function(){if(this.root){var t=this.renderToVNode({willUpdate:!0});t.attrs.style="position:absolute;left:0;top:0;user-select:none",function(t,e){if(hA(t,e))vA(t,e);else{var n=t.elm,i=oA(n);pA(e),null!==i&&(nA(i,e.elm,aA(n)),gA(i,[t],0,0))}}(this._oldVNode,t),this._oldVNode=t}},t.prototype.renderOneToVNode=function(t){return KT(t,kT(this._id))},t.prototype.renderToVNode=function(t){t=t||{};var e=this.storage.getDisplayList(!0),n=this._width,i=this._height,r=kT(this._id);r.animation=t.animation,r.willUpdate=t.willUpdate,r.compress=t.compress,r.emphasis=t.emphasis,r.ssr=this._opts.ssr;var o=[],a=this._bgVNode=function(t,e,n,i){var r;if(n&&"none"!==n)if(r=ST("rect","bg",{width:t,height:e,x:"0",y:"0"}),ls(n))QT({fill:n},r.attrs,"fill",i);else if(os(n))JT({style:{fill:n},dirty:Cr,getBoundingRect:function(){return{width:t,height:e}}},r.attrs,"fill",i);else{var o=Qa(n),a=o.color,s=o.opacity;r.attrs.fill=a,s<1&&(r.attrs["fill-opacity"]=s)}return r}(n,i,this._backgroundColor,r);a&&o.push(a);var s=t.compress?null:this._mainVNode=ST("g","main",{},[]);this._paintList(e,r,s?s.children:o),s&&o.push(s);var l=qi(Xi(r.defs),function(t){return r.defs[t]});if(l.length&&o.push(ST("defs","defs",{},l)),t.animation){var c=function(t,e,n){var i=(n=n||{}).newline?"\n":"",r=" {"+i,o=i+"}",a=qi(Xi(t),function(e){return e+r+qi(Xi(t[e]),function(n){return n+":"+t[e][n]+";"}).join(i)+o}).join(i),s=qi(Xi(e),function(t){return"@keyframes "+t+r+qi(Xi(e[t]),function(n){return n+r+qi(Xi(e[t][n]),function(i){var r=e[t][n][i];return"d"===i&&(r='path("'+r+'")'),i+":"+r+";"}).join(i)+o}).join(i)+o}).join(i);return a||s?[""].join(i):""}(r.cssNodes,r.cssAnims,{newline:!0});if(c){var u=ST("style","stl",{},[],c);o.push(u)}}return MT(n,i,o,t.useViewBox)},t.prototype.renderToString=function(t){return t=t||{},CT(this.renderToVNode({animation:cr(t.cssAnimation,!0),emphasis:cr(t.cssEmphasis,!0),willUpdate:!1,compress:!0,useViewBox:cr(t.useViewBox,!0)}),{newline:!0})},t.prototype.setBackgroundColor=function(t){this._backgroundColor=t},t.prototype.getSvgRoot=function(){return this._mainVNode&&this._mainVNode.elm},t.prototype._paintList=function(t,e,n){for(var i,r,o=t.length,a=[],s=0,l=0,c=0;c=0&&(!d||!r||d[f]!==r[f]);f--);for(var g=p-1;g>f;g--)i=a[--s-1];for(var m=f+1;m10&&"cartesian2d"===o.type&&r){var s=o.getBaseAxis(),l=o.getOtherAxis(s),c=s.getExtent(),u=n.getDevicePixelRatio(),d=Math.abs(c[1]-c[0])*(u||1),h=Math.round(a/d);if(isFinite(h)&&h>1){"lttb"===r?t.setData(i.lttbDownSample(i.mapDimension(l.dim),1/h)):"minmax"===r&&t.setData(i.minmaxDownSample(i.mapDimension(l.dim),1/h));var p=void 0;Ji(r)?p=UC[r]:Qi(r)&&(p=r),p&&t.setData(i.downSample(i.mapDimension(l.dim),1/h,p,GC))}}}}}("line"))},function(t){FS(sM),FS(FM)},function(t){FS(FM),t.registerComponentModel($M),t.registerComponentView(rT),t.registerAction({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},Cr),t.registerAction({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},Cr)},function(t){t.registerPainter("svg",_A)}]);class bA extends Nt{constructor(){super(...arguments),this.options=null,this.data=[],this.height="120px",this._chart=null,this._resizeObserver=null}render(){return gt`
`}connectedCallback(){super.connectedCallback(),this.hasUpdated&&!this._chart&&this.options&&(this._mount(),this._observeResize())}firstUpdated(){this._mount(),this._observeResize()}updated(t){(t.has("options")||t.has("data"))&&(this._chart&&this.options?this._chart.setOption(this._mergedOptions(),!0):!this._chart&&this.options&&this._mount()),t.has("height")&&this._chart&&this._chart.resize()}disconnectedCallback(){this._destroy(),super.disconnectedCallback()}_mount(){if(!this.options)return;const t=this.shadowRoot?.querySelector(".chart-host");t&&(this._chart=Gx(t,void 0,{renderer:"svg"}),this._chart.setOption(this._mergedOptions(),!0))}_mergedOptions(){if(!this.options)throw new Error("span-chart: options not set");return{...this.options,series:this.data}}_observeResize(){if("undefined"==typeof ResizeObserver)return;this._resizeObserver=new ResizeObserver(()=>{this._chart&&this._chart.resize()});const t=this.shadowRoot?.querySelector(".chart-host");t&&this._resizeObserver.observe(t)}_destroy(){this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),this._chart&&(this._chart.dispose(),this._chart=null)}}bA.styles=P` :host { display: block; width: 100%; @@ -55,13 +55,13 @@ var Rl={},Ol={};var zl,Hl=function(){function t(t,e,n){var i=this;this._sleepAft width: 100%; height: 100%; } - `,C([Ht({attribute:!1})],wA.prototype,"options",void 0),C([Ht({attribute:!1})],wA.prototype,"data",void 0),C([Ht({type:String})],wA.prototype,"height",void 0);try{customElements.get("span-chart")||customElements.define("span-chart",wA)}catch{}function SA(t,e,n,i,r,a,s,l,c){const{options:u,series:d}=function(t,e,n,i,r,a=!1){n||(n=y[o]);const s=i?"140, 160, 220":"77, 217, 175",l=`rgb(${s})`,c=Date.now(),u=c-e,d=void 0!==n.fixedMin&&void 0!==n.fixedMax,h=(t??[]).filter(t=>t.time>=u).map(t=>[t.time,Math.abs(t.value)]),p=[{type:"line",data:h,showSymbol:!1,smooth:!1,...a?{}:{step:"end"},lineStyle:{width:1.5,color:l},areaStyle:{color:{type:"linear",x:0,y:0,x2:0,y2:1,colorStops:[{offset:0,color:`rgba(${s}, 0.18)`},{offset:1,color:`rgba(${s}, 0.18)`}]}},itemStyle:{color:l}}],f=h.length>0?function(t){let e=0;for(const n of t)n[1]>e&&(e=n[1]);return e}(h):0,g={type:"value",splitNumber:4,axisLabel:{fontSize:10,formatter:f<10?t=>0===t?"0":t.toFixed(1):t=>n.format(t)},splitLine:{lineStyle:{opacity:.15}}};if(d?(g.min=n.fixedMin,g.max=n.fixedMax):f<1&&(g.min=0,g.max=1),r&&"current"===n.entityRole){const t=r.ratingA*r.continuousPct/100,e=r.ratingA*r.spikePct/100;g.min=0,g.max=Math.ceil(1.25*Math.max(t,e,f)),p.push({type:"line",data:[[u,t],[c,t]],showSymbol:!1,lineStyle:{width:1,color:"rgba(255, 200, 40, 0.6)",type:"dashed"},itemStyle:{color:"transparent"},tooltip:{show:!1}}),p.push({type:"line",data:[[u,e],[c,e]],showSymbol:!1,lineStyle:{width:1.5,color:"rgba(255, 60, 60, 0.7)",type:"solid"},itemStyle:{color:"transparent"},tooltip:{show:!1}})}const m={xAxis:{type:"time",min:u,max:c,axisLabel:{fontSize:10},splitLine:{show:!1}},yAxis:g,grid:{top:8,right:4,bottom:0,left:0,containLabel:!0},tooltip:{trigger:"axis",axisPointer:{type:"line",lineStyle:{type:"dashed"}},formatter:t=>{if(!t||0===t.length)return"";const e=t[0],i=new Date(e.value[0]).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}),r=parseFloat(e.value[1].toFixed(2));return`
${i}
${n.format(r)} ${n.unit(r)}
`}},animation:!1};return{options:m,series:p}}(n,i,r,a,l,c),h=s??120;t.style.minHeight=h+"px";let p=t.querySelector("span-chart");p||(p=document.createElement("span-chart"),p.style.display="block",p.style.width="100%",t.innerHTML="",t.appendChild(p));const f=t.clientHeight;p.height=(f>0?f:h)+"px",p.options=u,p.data=d}function CA(t){return null===t?Xt:function(t){return(Math.abs(t)/1e3).toFixed(1)}(t)}function kA(t,e,n,i,r){const o=t.querySelector(".panel-stats");o&&function(t,e,n,i,r){const o="current"===(i.chart_metric||"power"),a=t.querySelector(".stat-consumption .stat-value"),s=t.querySelector(".stat-consumption .stat-unit");if(o){const t=n.panel_entities?.site_power,i=t?e.states[t]:null,r=i?parseFloat(i.attributes?.amperage):NaN;a&&(a.textContent=Number.isFinite(r)?Math.abs(r).toFixed(1):Xt,a.classList.remove("stat-partial")),s&&(s.textContent="A")}else{let t=r;const i=n.panel_entities?.site_power,o=i?e.states[i]:void 0;o&&(t={total:qt(o),partial:!1}),a&&(a.textContent=CA(t?.total??null),a.classList.toggle("stat-partial",t?.partial??!1)),s&&(s.textContent="kW")}const l=t.querySelector(".stat-upstream .stat-value"),c=t.querySelector(".stat-upstream .stat-unit");if(l){const t=n.panel_entities?.current_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;l.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):Xt,c&&(c.textContent="A")}else l.textContent=CA(qt(i)),c&&(c.textContent="kW")}const u=t.querySelector(".stat-downstream .stat-value"),d=t.querySelector(".stat-downstream .stat-unit");if(u){const t=n.panel_entities?.feedthrough_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;u.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):Xt,d&&(d.textContent="A")}else u.textContent=CA(qt(i)),d&&(d.textContent="kW")}const h=t.querySelector(".stat-solar .stat-value"),p=t.querySelector(".stat-solar .stat-unit");if(h){const t=n.panel_entities?.pv_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;h.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):Xt,p&&(p.textContent="A")}else h.textContent=CA(qt(i)),p&&(p.textContent="kW")}const f=t.querySelector(".stat-battery .stat-value");if(f){const t=n.panel_entities?.battery_level,i=qt(t?e.states[t]:void 0);f.textContent=null===i?Xt:`${Math.round(i)}`}const g=t.querySelector(".stat-grid-state .stat-value");if(g){const t=n.panel_entities?.dsm_state,i=t?e.states[t]:null;g.textContent=i?e.formatEntityState?.(i)||i.state:Xt}}(o,e,n,i,r)}function MA(t,e,n,i){const{hass:r,powerHistory:o,horizonMap:a,defaultDurationMs:s,chartMetric:l,monitoringStatus:c}=i,u=cn(n,r),d=hn(n,u),h=ln(n,r),p=t.querySelector(".power-value");p&&(p.innerHTML="current"===l.entityRole?te(un(n,r)):Jt(u)),kn(t,h,_n(n,r),ge(i.topology,e)),t.classList.toggle("circuit-off",!h),t.classList.toggle("circuit-producer",d),In(t,wn(n,r));const f=t.querySelector(".chart-container");if(f){const i=o.get(e)||[],r=t.classList.contains("circuit-col-span")?200:100,u=a?.has(e)?si(a.get(e)):s,h=dn(n),p=Ze(c,n),g=nn(n,p);SA(f,0,i,u,l,d,r,g?{ratingA:g,...Ke(p)}:void 0,h)}}class TA{get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this._retry=t?new Ue(t):null}constructor(){this._errorStore=null,this._retry=null,this._settings=null,this._lastFetch=0,this._fetching=!1}async fetch(t,e){const n=Date.now();if(this._fetching)return this._settings;if(this._settings&&n-this._lastFetch<3e4)return this._settings;this._fetching=!0;try{const n={};e&&(n.config_entry_id=e);const r={type:"call_service",domain:l,service:"get_graph_settings",service_data:n,return_response:!0},o=this._retry?await this._retry.callWS(t,r,{errorId:"fetch:graph_settings",errorMessage:i("error.graph_settings_failed")}):await t.callWS(r);this._settings=o?.response??null,this._lastFetch=Date.now()}catch(t){console.warn("SPAN Panel: graph settings fetch failed",t),this._settings=null,this._retry||this._errorStore?.add({key:"fetch:graph_settings",level:"warning",message:i("error.graph_settings_failed"),persistent:!1})}finally{this._fetching=!1}return this._settings}invalidate(){this._lastFetch=0}get settings(){return this._settings}clear(){this._settings=null,this._lastFetch=0}}function AA(t,e){if(!t)return a;const n=t.circuits?.[e];return n?.has_override?n.horizon:t.global_horizon??a}function IA(t,e){if(!t)return a;const n=t.sub_devices?.[e];return n?.has_override?n.horizon:t.global_horizon??a}function DA(t,e,n){return{members:t?ze(t):[{uuid:e,circuit:n}],capacityA:t&&t.members.length>1?t.circuit.breaker_rating_a??null:null}}class PA{constructor(){this.powerHistory=new Map,this.horizonMap=new Map,this.subDeviceHorizonMap=new Map,this.monitoringCache=new Xe,this.monitoringMultiCache=new Ye,this.graphSettingsCache=new TA,this._errorStore=null,this._hass=null,this._topology=null,this._config=null,this._configEntryId=null,this._favRefs=null,this._favoritesMonitoringStatus=null,this._perPanelInfo=new Map,this._panelFavorites=null,this._showMonitoring=!1,this._updateInterval=null,this._recorderRefreshInterval=null,this._resizeObserver=null,this._lastWidth=0,this._resizeDebounce=null}get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this.monitoringCache.errorStore=t,this.graphSettingsCache.errorStore=t,this.monitoringMultiCache.errorStore=t}get hass(){return this._hass}set hass(t){this._hass=t}get topology(){return this._topology}get config(){return this._config}set showMonitoring(t){this._showMonitoring=t}init(t,e,n,i){this._topology=t,this._config=e,this._hass=n,this._configEntryId=i}setFavoriteRefs(t){this._favRefs=t}clearFavoriteRefs(){this._favRefs=null,this._favoritesMonitoringStatus=null}get monitoringStatus(){return this._favRefs?this._favoritesMonitoringStatus:this.monitoringCache.status}setPanelFavorites(t){this._panelFavorites=t}setFavoritesPerPanelInfo(t){this._perPanelInfo=t??new Map}get _inFavoritesView(){return null!==this._favRefs}get showFavorites(){return this._inFavoritesView||null!==this._panelFavorites}setConfig(t){this._config=t}buildHorizonMaps(t){if(this.horizonMap.clear(),this.subDeviceHorizonMap.clear(),t&&this._topology?.circuits)for(const e of Object.keys(this._topology.circuits))this.horizonMap.set(e,AA(t,e));if(t&&this._topology?.sub_devices)for(const e of Object.keys(this._topology.sub_devices))this.subDeviceHorizonMap.set(e,IA(t,e))}async fetchAndBuildHorizonMaps(){try{this._favRefs?await this._buildFavoritesHorizonMaps():(await this.graphSettingsCache.fetch(this._hass,this._configEntryId),this.buildHorizonMaps(this.graphSettingsCache.settings))}catch(t){console.warn("SPAN Panel: graph settings fetch failed",t),this.graphSettingsCache.errorStore||this._errorStore?.add({key:"fetch:graph_settings",level:"warning",message:i("error.graph_settings_failed"),persistent:!1})}}async fetchMergedMonitoringStatus(t){if(!this._hass||0===t.length)return null;const e=this._hass,n=function(t){let e=!1;const n={},i={};for(const r of t)r&&(e=!0,r.circuits&&Object.assign(n,r.circuits),r.mains&&Object.assign(i,r.mains));return e?{circuits:n,mains:i}:null}(await Promise.all(t.map(t=>this.monitoringMultiCache.fetchOne(e,t))));return this._favoritesMonitoringStatus=n,n}async _buildFavoritesHorizonMaps(){if(!this._hass||!this._favRefs||!this._topology)return;const t=new Set;for(const e of Object.values(this._favRefs))e.configEntryId&&t.add(e.configEntryId);const e=new Map;await Promise.all(Array.from(t).map(async t=>{e.set(t,await this._fetchGraphSettingsFresh(t))})),this.horizonMap.clear(),this.subDeviceHorizonMap.clear();for(const t of Object.keys(this._topology.circuits)){const n=this._favRefs[t],i=n?.configEntryId?e.get(n.configEntryId)??null:null,r=n?.targetId??t;this.horizonMap.set(t,AA(i,r))}if(this._topology.sub_devices)for(const t of Object.keys(this._topology.sub_devices)){const n=this._favRefs[t],i=n?.configEntryId?e.get(n.configEntryId)??null:null,r=n?.targetId??t;this.subDeviceHorizonMap.set(t,IA(i,r))}}async loadHistory(){await mi(this._hass,this._topology,this._config,this.powerHistory,this.horizonMap,this.subDeviceHorizonMap)}recordSamples(){if(!this._topology||!this._hass||!this._config)return;const t=Date.now();for(const[e,n]of Object.entries(this._topology.circuits)){const i=this.horizonMap.get(e)??a;if(!s[i]?.useRealtime)continue;const r=Oe(n,this._config);if(!r)continue;const o=qt(this._hass.states[r]);if(null===o)continue;const l=si(i),c=li(l),u=ci(l),d=t-l,h=this.powerHistory.get(e)??[];h.length>0&&t-h[h.length-1].time0&&t-h[h.length-1].time0&&this._topology)for(const{key:t,devId:e}of gi(this._topology))n.has(e)&&r.add(t);const o=new Map;try{await mi(this._hass,this._topology,this._config,o,e,n);for(const t of e.keys()){const e=o.get(t);e?this.powerHistory.set(t,e):this.powerHistory.delete(t)}for(const t of r){const e=o.get(t);e?this.powerHistory.set(t,e):this.powerHistory.delete(t)}this.updateDOM(t)}catch(t){console.warn("SPAN Panel: history refresh failed",t),this._errorStore?.add({key:"fetch:history",level:"warning",message:i("error.history_failed"),persistent:!1})}}updateDOM(t){this._hass&&this._topology&&this._config&&(function(t,e,n,i,r,o,a){if(!t||!n||!e)return;const s=ai(i),l=$e(n),c=[];for(const{circuit:t}of l){if(!t.entities?.power||dn(t)||Ie(t))continue;const n=cn(t,e);c.push(null===n?null:Math.abs(n))}kA(t,e,n,i,function(t){let e=null,n=!1;for(const i of t)null===i?n=!0:e=null===e?i:e+i;return{total:e,partial:n&&null!==e}}(c));const u={hass:e,topology:n,powerHistory:r,horizonMap:o,defaultDurationMs:s,chartMetric:Re(i),monitoringStatus:a};for(const e of l)for(const n of ze(e)){const i=t.querySelector(`.circuit-slot[data-uuid="${Ln(n.uuid)}"]`);if(!i)continue;const r=n.uuid===e.uuid?e.circuit:Be(n.circuit,e);MA(i,n.uuid,r,u)}}(t,this._hass,this._topology,this._config,this.powerHistory,this.horizonMap,this.monitoringStatus),function(t,e,n,i,r,o){if(!n.sub_devices)return;const a=ai(i);for(const[i,s]of Object.entries(n.sub_devices)){const n=t.querySelector(`[data-subdev="${Ln(i)}"]`);if(!n)continue;const l=Wn(s);if(l.headlineEid){const t=n.querySelector(".sub-power-value");t&&(t.innerHTML=Qt(Un(e,l.headlineEid)))}if(l.siteTotalEid){const t=Un(e,l.siteTotalEid),i=n.querySelector(".sub-site-total-value");i&&(i.innerHTML=Qt(t));const r=i?.closest(".sub-entity");r&&(r.hidden=null===t)}const c=n.querySelectorAll("[data-chart-key]");for(const t of c){const e=t.dataset.chartKey;if(!e)continue;const n=r.get(e)||[];let s=_.power;e.endsWith("_soc")?s=_.soc:e.endsWith("_soe")&&(s=_.soe);const l=!!t.closest(".bess-chart-col");SA(t,0,n,o?.has(i)?si(o.get(i)):a,s,!1,l?120:150,void 0,e.endsWith("_soc")||e.endsWith("_soe"))}for(const t of Object.keys(s.entities||{})){const i=n.querySelector(`[data-eid="${Ln(t)}"]`);if(!i)continue;const r=e.states[t];if(r){let t;if(e.formatEntityState)t=e.formatEntityState(r);else{t=r.state;const e=r.attributes.unit_of_measurement||"";e&&(t+=" "+e)}if("Wh"===(r.attributes.unit_of_measurement||"")){const e=qt(r);null!==e&&(t=(e/1e3).toFixed(1)+" kWh")}i.textContent=t}}}}(t,this._hass,this._topology,this._config,this.powerHistory,this.subDeviceHorizonMap),function(t,e,n,i){for(const[r,o]of En(n)){const n=t.querySelector(`.meter-tile[data-meter-uuid="${Ln(r)}"] .meter-readings`);n&&(n.innerHTML=On(o,e,i))}}(t,this._hass,this._topology,this._config))}async onGraphSettingsChanged(t){if(this._hass){this._favRefs?await this._buildFavoritesHorizonMaps():(this.graphSettingsCache.invalidate(),await this.graphSettingsCache.fetch(this._hass,this._configEntryId),this.buildHorizonMaps(this.graphSettingsCache.settings)),this.powerHistory.clear();try{await this.loadHistory()}catch{}this.updateDOM(t)}}onToggleClick(t,e){const n=t.target,i=n?.closest(".toggle-pill");if(!i)return;const r=e.querySelector(".slide-confirm");if(!r||!r.classList.contains("confirmed"))return;t.stopPropagation(),t.preventDefault();const o=i.closest("[data-uuid]");if(!o||!this._topology||!this._hass)return;const a=o.dataset.uuid;if(!a)return;const s=this._topology.circuits[a];if(!s)return;const l=s.entities?.switch;if(!l)return;if("operable"!==_n(s,this._hass))return;const c=ge(this._topology,a);if(!c.mayOperate)return void this._errorStore?.add({key:"service:relay",level:"warning",message:_e(c),persistent:!1});const u=this._hass;xe(u,c).setRelay(l,"on"!==u.states[l]?.state).catch(t=>Ce(u,this._errorStore,t,"relay"))}async onGearClick(t,e){const n=t.target,i=n?.closest(".gear-icon");if(!i)return;const r=e.querySelector("span-side-panel");if(!r||!this._hass)return;if(r.hass=this._hass,r.errorStore=this.errorStore,i.classList.contains("panel-gear")){if(this._inFavoritesView){const t=await this._buildFavoritesSections();if(0===t.length)return;return void r.open({favoritesMode:!0,perPanelSections:t})}if(!this._topology)return;return await this.graphSettingsCache.fetch(this._hass,this._configEntryId),void r.open({panelMode:!0,topology:this._topology,graphSettings:this.graphSettingsCache.settings,showFavorites:null!==this._panelFavorites,favoritePanelDeviceId:this._panelFavorites?.panelDeviceId,favoriteCircuitUuids:this._panelFavorites?.circuitUuids,favoriteSubDeviceIds:this._panelFavorites?.subDeviceIds,configEntryId:this._configEntryId})}const o=i.dataset.uuid;if(o&&this._topology){const t=this._topology.circuits[o];if(t){const e=this._favRefs?.[o]??null,n=e&&"circuit"===e.kind?e.targetId:o,i=e?.configEntryId??this._configEntryId;let s,l;e?[s,l]=await Promise.all([this._fetchGraphSettingsFresh(i),this._fetchMonitoringStatusFresh(i)]):(await Promise.all([this.graphSettingsCache.fetch(this._hass,i),this.monitoringCache.fetch(this._hass,i)]),s=this.graphSettingsCache.settings,l=this.monitoringCache.status);const c=Ze(l,t),u=s?.global_horizon??a,d=s?.circuits?.[n],h=d?{...d,globalHorizon:u}:{horizon:u,has_override:!1,globalHorizon:u},p=e?.panelDeviceId??this._panelFavorites?.panelDeviceId,f=null!==e||(this._panelFavorites?.circuitUuids.has(n)??!1),g=this._sidePanelSlot(o,e),m=e?this._perPanelInfo.get(e.panelDeviceId)?.topology:this._topology,v={uuid:n,name:t.name,entities:t.entities,...DA(g,n,t),is_user_controllable:t.is_user_controllable,always_on:t.always_on,relay_state:t.relay_state,priority:t.priority,device_type:t.device_type,monitoringInfo:c,monitoringGlobals:l?.global_settings??null,showMonitoring:this._showMonitoring,monitoringRatingOffered:!0===m?.monitoring_rating_offered,graphHorizonInfo:h,showFavorites:this.showFavorites,favoritePanelDeviceId:p,isFavorite:f,configEntryId:i,controlAccess:ge(this._topology,o)};return void r.open(v)}}const s=i.dataset.subdevId;if(s&&this._topology?.sub_devices?.[s]){const t=this._topology.sub_devices[s],e=this._favRefs?.[s]??null,n=e&&"sub_device"===e.kind?e.targetId:s,i=e?.configEntryId??this._configEntryId;let o;e?o=await this._fetchGraphSettingsFresh(i):(await this.graphSettingsCache.fetch(this._hass,i),o=this.graphSettingsCache.settings);const l=o?.global_horizon??a,c=o?.sub_devices?.[n],u=c?{...c,globalHorizon:l}:{horizon:l,has_override:!1,globalHorizon:l},d=e?.panelDeviceId??this._panelFavorites?.panelDeviceId,h=null!==e||(this._panelFavorites?.subDeviceIds.has(n)??!1);r.open({subDeviceMode:!0,subDeviceId:n,name:t.name??n,deviceType:t.type??"",entities:t.entities,hasChart:qn(t).length>0,graphHorizonInfo:u,showFavorites:this.showFavorites,favoritePanelDeviceId:d,isFavorite:h,configEntryId:i})}}_sidePanelSlot(t,e){const n="circuit"===e?.kind?this._perPanelInfo.get(e.panelDeviceId)?.topology:void 0;return n&&e?He($e(n)).get(e.targetId):this._topology?He($e(this._topology)).get(t):void 0}async refreshCircuitSidePanel(t,e,n,i=null){const r=t.querySelector("span-side-panel"),o=r?.openCircuit;if(!r||!o||o.configEntryId!==e)return;const a=n.circuits[o.uuid];if(!a)return;const s=He($e(n)).get(o.uuid);if(i&&!(s?.memberIds??[o.uuid]).some(t=>i.has(t)))return;const l=await this._fetchMonitoringStatusFresh(e);if(r.openCircuit?.uuid!==o.uuid)return;const c=Ze(l,a);r.refreshRating({...DA(s,o.uuid,a),monitoringInfo:c,monitoringGlobals:l?.global_settings??null})}refreshCircuitControlAccess(t,e,n){const i=t.querySelector("span-side-panel"),r=i?.openCircuit;i&&r&&r.configEntryId===e&&i.refreshControlAccess(pe(n))}async _buildFavoritesSections(){if(!this._hass||!this._favRefs)return[];const t=function(t,e){const n=new Map;for(const i of Object.values(t)){if("circuit"!==i.kind)continue;const t=e.get(i.panelDeviceId);if(void 0===t)continue;let r=n.get(i.panelDeviceId);void 0===r&&(r={panelDeviceId:i.panelDeviceId,panelName:t.panelName,topology:t.topology,configEntryId:t.configEntryId,favoriteCircuitUuids:new Set},n.set(i.panelDeviceId,r)),r.favoriteCircuitUuids.add(i.targetId)}return Array.from(n.values()).sort((t,e)=>t.panelName.localeCompare(e.panelName))}(this._favRefs,this._perPanelInfo);if(0===t.length)return[];return await Promise.all(t.map(async t=>({panelDeviceId:t.panelDeviceId,panelName:t.panelName,topology:t.topology,graphSettings:await this._fetchGraphSettingsFresh(t.configEntryId),favoriteCircuitUuids:t.favoriteCircuitUuids,configEntryId:t.configEntryId})))}async _fetchGraphSettingsFresh(t){if(!this._hass)return null;try{const e={};t&&(e.config_entry_id=t);const n={type:"call_service",domain:l,service:"get_graph_settings",service_data:e,return_response:!0},r=this._errorStore?new Ue(this._errorStore):null,o=r?await r.callWS(this._hass,n,{errorId:"fetch:graph_settings",errorMessage:i("error.graph_settings_failed")}):await this._hass.callWS(n);return o?.response??null}catch(t){return console.warn("SPAN Panel: fresh graph settings fetch failed",t),null}}async _fetchMonitoringStatusFresh(t){if(!this._hass)return null;try{const e={};t&&(e.config_entry_id=t);const n={type:"call_service",domain:l,service:"get_monitoring_status",service_data:e,return_response:!0},r=this._errorStore?new Ue(this._errorStore):null,o=r?await r.callWS(this._hass,n,{errorId:"fetch:monitoring",errorMessage:i("error.monitoring_failed")}):await this._hass.callWS(n);return Ge(o?.response)}catch(t){return console.warn("SPAN Panel: fresh monitoring status fetch failed",t),null}}bindSlideConfirm(t,e){if(t.classList.contains("slide-confirm-forbidden"))return;const n=t.querySelector(".slide-confirm-knob"),i=t.querySelector(".slide-confirm-text");if(!n||!i)return;let r=!1,o=0,a=0;const s=e=>{t.classList.contains("confirmed")||(r=!0,o=e-n.offsetLeft,a=t.offsetWidth-n.offsetWidth-4,n.classList.remove("snapping"))},l=t=>{if(!r)return;const e=Math.max(2,Math.min(t-o,a));n.style.left=e+"px"},c=()=>{if(!r)return;r=!1;(n.offsetLeft-2)/a>=.9?(n.style.left=a+"px",t.classList.add("confirmed"),n.querySelector("span-icon")?.setAttribute("icon","mdi:lock-open"),i.textContent=t.dataset.textOn??"",e&&e.classList.remove("switches-disabled")):(n.classList.add("snapping"),n.style.left="2px")};n.addEventListener("mousedown",t=>{t.preventDefault(),s(t.clientX)}),t.addEventListener("mousemove",t=>l(t.clientX)),t.addEventListener("mouseup",c),t.addEventListener("mouseleave",c),n.addEventListener("touchstart",t=>{t.preventDefault(),s(t.touches[0].clientX)},{passive:!1}),t.addEventListener("touchmove",t=>l(t.touches[0].clientX),{passive:!0}),t.addEventListener("touchend",c),t.addEventListener("touchcancel",c),t.addEventListener("click",()=>{t.classList.contains("confirmed")&&(t.classList.remove("confirmed"),n.classList.add("snapping"),n.style.left="2px",n.querySelector("span-icon")?.setAttribute("icon","mdi:lock"),i.textContent=t.dataset.textOff??"",e&&e.classList.add("switches-disabled"))})}startIntervals(t,e){this._updateInterval=setInterval(()=>{this.recordSamples(),this.updateDOM(t),e&&e()},1e3),this._recorderRefreshInterval=setInterval(()=>{this.refreshRecorderData(t)},3e4)}stopIntervals(){this._updateInterval&&(clearInterval(this._updateInterval),this._updateInterval=null),this._recorderRefreshInterval&&(clearInterval(this._recorderRefreshInterval),this._recorderRefreshInterval=null),this.cleanupResizeObserver()}setupResizeObserver(t,e){this.cleanupResizeObserver(),e&&(this._lastWidth=e.clientWidth,this._resizeObserver=new ResizeObserver(e=>{const n=e[0];if(!n)return;const i=n.contentRect.width;Math.abs(i-this._lastWidth)<5||(this._lastWidth=i,this._resizeDebounce&&clearTimeout(this._resizeDebounce),this._resizeDebounce=setTimeout(()=>{for(const e of t.querySelectorAll(".chart-container")){const t=e.querySelector("span-chart");t&&t.remove()}this.updateDOM(t)},150))}),this._resizeObserver.observe(e))}cleanupResizeObserver(){this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),this._resizeDebounce&&(clearTimeout(this._resizeDebounce),this._resizeDebounce=null)}reset(){this.powerHistory.clear(),this.horizonMap.clear(),this.subDeviceHorizonMap.clear(),this.monitoringCache.clear(),this.monitoringMultiCache.clear(),this.graphSettingsCache.clear()}}function LA(t=""){const e=t?` value="${Ft(t)}"`:"",n=t?"":"display:none;";return`\n
\n \n \n
\n `}function EA(t,e,n,r,o,a,s,l,c){const u=ln(e,n),d=_n(e,n),h=Ve([e]),p=Ft(e.name||i("grid.unknown")),f="current"===Re(r).entityRole;let g;g=u?f?te(un(e,n)):Jt(cn(e,n)):"";const m=An(a||"unknown");let v="";const y=pn(l,n,o);null!==y&&(v=`${Math.round(y)}%`);const _=``,b=Ie(e)?"":"none"===d?`${u?"ON":"OFF"}`:Cn(u,d,c);return`\n
\n ${h?`${h}`:""}\n ${v}\n ${p}\n ${m}\n ${b}\n \n ${g}\n \n ${_}\n \n
\n `}function NA(t,e,n,i,r){const o=hn(e,cn(e,n)),a=sn(0,r,ln(e,n),o),s=Ft(t);return`\n
\n
\n
\n
\n
\n `}function RA(t){return`
${Ft(t)}
`}function OA(t,e){const n=e.hysteresisPx??48,i=new WeakSet;let r=null;const o=t=>{const n=t.querySelector(e.nameSelector);return!!n&&(0!==t.clientWidth&&(n.clientWidth<1||n.scrollWidth>n.clientWidth+1))},a=()=>{const i=t.querySelectorAll(e.rowSelector);if(0===i.length)return;const a=i[0].clientWidth;if(0===a)return;if(null!==r){if(a>r+n){for(const t of i)t.classList.remove(e.foldClass);r=null}else for(const t of i)t.classList.add(e.foldClass);return}let s=!1;for(const t of i)if(o(t)){s=!0;break}if(s){for(const t of i)t.classList.add(e.foldClass);r=a}},s=new ResizeObserver(()=>a()),l=()=>{const n=t.querySelectorAll(e.rowSelector);for(const t of n)i.has(t)||(i.add(t),s.observe(t));requestAnimationFrame(()=>a())};l();const c=new MutationObserver(t=>{(t=>{const n=t=>{for(const n of t)if(n instanceof Element){if(n.matches(e.rowSelector))return!0;if(n.querySelector(e.rowSelector))return!0}return!1};for(const e of t)if(n(e.addedNodes)||n(e.removedNodes))return!0;return!1})(t)&&l()});return c.observe(t,{childList:!0,subtree:!0}),()=>{s.disconnect(),c.disconnect()}}function zA(t,e,n){return{isOn:ln(t,e),value:"current"===(n.chart_metric||"power")?un(t,e):cn(t,e)}}function HA(t,e,n,i){const r=zA(t,n,i),o=zA(e,n,i);return r.isOn&&!o.isOn?-1:!r.isOn&&o.isOn?1:null===r.value||null===o.value?r.value===o.value?0:null===r.value?1:-1:Math.abs(o.value)-Math.abs(r.value)}function BA(t,e,n){return t.sort((t,i)=>HA(t[1],i[1],e,n))}class $A{constructor(t){this._expandedUuids=new Set,this._searchQuery="",this._container=null,this._clickHandler=null,this._inputHandler=null,this._graphSettingsHandler=null,this._hass=null,this._topology=null,this._config=null,this._monitoringStatus=null,this._viewName=null,this._columns=1,this._foldUnobserve=null,this._ctrl=t}setColumns(t){const e=Math.max(1,Math.min(3,Math.floor(t)));this._columns=e}setInitialExpansion(t){this._expandedUuids=new Set(t)}setInitialSearchQuery(t){this._searchQuery=t}setViewName(t){this._viewName=t}renderActivityView(t,e,n,i,r,o){this._unbindEvents(),this._hass=e,this._topology=n,this._config=i,this._monitoringStatus=r;const a=BA(Object.entries(n.circuits),e,i),s=He($e(n));let l=o+LA(this._searchQuery);l+=`
`;for(const[t,o]of a){const a=Ze(r,o),c=wn(o,e),u=this._expandedUuids.has(t);l+=`
`,l+=EA(t,o,e,i,a,c,u,Be(o,s.get(t)),ge(n,t)),u&&(l+=NA(t,o,e,0,a)),l+="
"}l+="
",l+="",t.innerHTML=l;const c=t.querySelector("span-side-panel");c&&(c.hass=e,c.errorStore=this._ctrl.errorStore),this._bindEvents(t),this._searchQuery&&this._applyFilter(t),this._ctrl.updateDOM(t),this._attachFoldObserver(t)}renderAreaView(t,e,n,r,o,a){this._unbindEvents(),this._hass=e,this._topology=n,this._config=r,this._monitoringStatus=o;const s=i("list.unassigned_area"),l=He($e(n)),c=new Map;for(const[t,e]of Object.entries(n.circuits)){const n=e.area??s,i=c.get(n);i?i.push([t,e]):c.set(n,[[t,e]])}const u=[...c.keys()].sort((t,e)=>t===s?1:e===s?-1:t.localeCompare(e));let d=a+LA(this._searchQuery);d+=`
`;for(const t of u){const i=c.get(t);if(!i)continue;const a=BA(i,e,r);d+=RA(t);for(const[t,i]of a){const a=Ze(o,i),s=wn(i,e),c=this._expandedUuids.has(t);d+=`
`,d+=EA(t,i,e,r,a,s,c,Be(i,l.get(t)),ge(n,t)),c&&(d+=NA(t,i,e,0,a)),d+="
"}}d+="
",d+="",t.innerHTML=d;const h=t.querySelector("span-side-panel");h&&(h.hass=e,h.errorStore=this._ctrl.errorStore),this._bindEvents(t),this._searchQuery&&this._applyFilter(t),this._ctrl.updateDOM(t),this._attachFoldObserver(t)}updateCollapsedRows(t,e,n,i){const r="current"===Re(i).entityRole,o=t.querySelectorAll(".list-row[data-row-uuid]");for(const t of o){const o=t.dataset.rowUuid;if(!o)continue;const a=n.circuits[o];if(!a)continue;const{isOn:s,value:l}=zA(a,e,i),c=t.querySelector(".list-power-value");c&&(c.innerHTML=s?r?te(l):Jt(l):""),kn(t,s,_n(a,e),ge(n,o)),In(t,wn(a,e));const u=t.querySelector(".list-status-badge");u&&(u.textContent=s?"ON":"OFF",u.classList.toggle("list-status-on",s),u.classList.toggle("list-status-off",!s)),t.classList.toggle("circuit-off",!s)}!function(t,e,n,i){const r=t.querySelector(".list-view");if(r)for(const t of function(t,e){let n={anchor:null,units:[]};const i=[n];for(const r of[...t.children])if(r.classList.contains("area-header"))n={anchor:r,units:[]},i.push(n);else if(r.classList.contains("list-cell")){const t=r.dataset.cellUuid,i=t?e.circuits[t]:void 0;t&&i&&n.units.push({cell:r,uuid:t,circuit:i})}return i}(r,n)){if(t.units.length<2)continue;const n=[...t.units].sort((t,n)=>HA(t.circuit,n.circuit,e,i));if(!n.some((e,n)=>e.uuid!==t.units[n].uuid))continue;let o=t.anchor;for(const t of n)o?o.after(t.cell):r.prepend(t.cell),o=t.cell}}(t,e,n,i)}stop(){this._unbindEvents(),null===this._viewName&&(this._expandedUuids.clear(),this._searchQuery=""),this._hass=null,this._topology=null,this._config=null,this._monitoringStatus=null}_dispatchFavoritesViewState(){if(!this._viewName||!this._container)return;const t={view:this._viewName,expanded:[...this._expandedUuids],searchQuery:this._searchQuery};this._container.dispatchEvent(new CustomEvent("favorites-view-state-changed",{detail:t,bubbles:!0,composed:!0}))}_bindEvents(t){this._container=t,this._clickHandler=e=>{const n=e.target;if(!n)return;const i=n.closest(".list-expand-toggle");if(i){const t=i.dataset.expandUuid;return void(t&&this._toggleExpand(t))}if(n.closest(".gear-icon"))return void this._ctrl.onGearClick(e,t);if(n.closest(".toggle-pill"))return void this._ctrl.onToggleClick(e,t);if(n.closest(".list-search-clear")){const e=t.querySelector(".list-search");return void(e&&(e.value="",e.dispatchEvent(new Event("input",{bubbles:!0}))))}const r=n.closest(".unit-btn");if(r){const e=r.dataset.unit;e&&t.dispatchEvent(new CustomEvent("unit-changed",{detail:e,bubbles:!0,composed:!0}))}},this._inputHandler=e=>{const n=e.target;n&&n.classList.contains("list-search")&&(this._searchQuery=n.value.toLowerCase(),this._applyFilter(t),this._dispatchFavoritesViewState())},this._graphSettingsHandler=()=>{this._ctrl.onGraphSettingsChanged(t).then(()=>{this._ctrl.updateDOM(t)}).catch(()=>{})},t.addEventListener("click",this._clickHandler),t.addEventListener("input",this._inputHandler),t.addEventListener("graph-settings-changed",this._graphSettingsHandler);const e=t.querySelector(".slide-confirm");e&&(this._ctrl.bindSlideConfirm(e,t),t.classList.add("switches-disabled"))}_unbindEvents(){this._container&&(this._clickHandler&&this._container.removeEventListener("click",this._clickHandler),this._inputHandler&&this._container.removeEventListener("input",this._inputHandler),this._graphSettingsHandler&&this._container.removeEventListener("graph-settings-changed",this._graphSettingsHandler)),this._foldUnobserve&&(this._foldUnobserve(),this._foldUnobserve=null),this._container=null,this._clickHandler=null,this._inputHandler=null,this._graphSettingsHandler=null}_attachFoldObserver(t){this._foldUnobserve&&(this._foldUnobserve(),this._foldUnobserve=null),this._foldUnobserve=OA(t,{rowSelector:".list-row",nameSelector:".list-circuit-name",foldClass:"is-folded"})}_applyFilter(t){const e=t.querySelector(".list-search-clear");e&&(e.style.display=this._searchQuery?"":"none");const n=t.querySelectorAll(".list-cell[data-cell-uuid]");for(const t of n){const e=t.querySelector(".list-circuit-name"),n=(e?.textContent?.toLowerCase()??"").includes(this._searchQuery);t.style.display=n?"":"none"}const i=t.querySelectorAll(".area-header");for(const t of i){let e=!1,n=t.nextElementSibling;for(;n&&!n.classList.contains("area-header");){if(n.classList.contains("list-cell")&&"none"!==n.style.display){e=!0;break}n=n.nextElementSibling}t.style.display=e?"":"none"}}_toggleExpand(t){if(!(this._container&&this._hass&&this._topology&&this._config))return;const e=Ln(t),n=this._container.querySelector(`.list-cell[data-cell-uuid="${e}"]`);if(!n)return;const i=n.querySelector(`.list-row[data-row-uuid="${e}"]`),r=n.querySelector(`.list-expand-toggle[data-expand-uuid="${e}"]`);if(i){if(this._expandedUuids.has(t)){this._expandedUuids.delete(t);const o=n.querySelector(`.list-expanded-content[data-expanded-uuid="${e}"]`);o&&o.remove(),r&&r.classList.remove("expanded"),i.classList.remove("list-row-expanded")}else{this._expandedUuids.add(t);const e=this._topology.circuits[t];if(!e)return;const n=Ze(this._monitoringStatus,e),o=NA(t,e,this._hass,this._config,n);i.insertAdjacentHTML("afterend",o),r&&r.classList.add("expanded"),i.classList.add("list-row-expanded"),this._ctrl.updateDOM(this._container)}this._dispatchFavoritesViewState()}}}const FA=["entity_registry_updated","area_registry_updated","device_registry_updated"];async function VA(t,e){const[n,i,r]=await Promise.all([t.callWS({type:"config/area_registry/list"}),t.callWS({type:"config/entity_registry/list"}),t.callWS({type:"config/device_registry/list"})]),o=new Map;for(const t of n)o.set(t.area_id,t.name);const a=new Map,s=new Map;for(const t of i)t.area_id&&a.set(t.entity_id,t.area_id),t.device_id&&s.set(t.entity_id,t.device_id);const l=new Map;for(const t of r)t.area_id&&l.set(t.id,t.area_id);const c=e.panel_device_id??e.device_id,u=t=>t?l.get(t):void 0;for(const t of Object.values(e.circuits)){const e=Object.values(t.entities).filter(t=>!!t),n=[u(t.device_id),...e.map(t=>a.get(t)),...e.map(t=>u(s.get(t))),u(c)];t.area=n.map(t=>t?o.get(t):void 0).find(t=>!!t)}}const WA=["name","name_by_user"];async function jA(t,e,n){const i=t.connection;return i?i.subscribeEvents(t=>{const i=function(t){if("object"!=typeof t||null===t||!("data"in t))return null;const{data:e}=t;if("object"!=typeof e||null===e)return null;if(!("action"in e)||"update"!==e.action)return null;if(!("device_id"in e)||"string"!=typeof e.device_id)return null;if(!("changes"in e))return null;const{changes:n}=e;return"object"!=typeof n||null===n?null:WA.some(t=>t in n)?e.device_id:null}(t),r=i?e():null;i&&r&&function(t,e){return(t.panel_device_id??t.device_id)===e||!!Object.keys(t.sub_devices??{}).includes(e)||Object.values(t.circuits).some(t=>t.device_id===e)}(r,i)&&n()},"device_registry_updated"):()=>{}}const qA="loaded";function UA(t){if("object"!=typeof t||null===t||!("data"in t))return null;const{data:e}=t;return"object"==typeof e&&null!==e?e:null}async function GA(t,e,n){const i=t.connection;return i?i.subscribeEvents(t=>{(function(t){const e=UA(t);return e&&"config_entry_id"in e&&"string"==typeof e.config_entry_id?e.config_entry_id:null})(t)===e&&n(function(t){const e=UA(t);if(!e||!("circuit_ids"in e)||!Array.isArray(e.circuit_ids))return null;const n=e.circuit_ids;return n.every(t=>"string"==typeof t)?new Set(n):null}(t))},"span_panel_package_ratings_changed"):()=>{}}class XA{constructor(){this._persistent=new Map,this._transient=null,this._transientTimer=null,this._subscribers=new Set,this._watchedPanels=new Map}add(t){const e={...t,timestamp:Date.now()};if(e.persistent)this._persistent.set(e.key,e);else{this._clearTransient(),this._transient=e;const t=e.ttl??5e3;this._transientTimer=setTimeout(()=>{this._transient=null,this._transientTimer=null,this._notify()},t)}this._notify()}remove(t){if(this._persistent.has(t))return this._persistent.delete(t),void this._notify();this._transient?.key===t&&(this._clearTransient(),this._notify())}clear(t){void 0===t?(this._persistent.clear(),this._clearTransient(),this._watchedPanels.clear()):!0===t.persistent?this._persistent.clear():!1===t.persistent&&this._clearTransient(),this._notify()}get active(){const t=[...this._persistent.values()];return null!==this._transient&&t.push(this._transient),t}hasPersistent(t){return this._persistent.has(t)}hasAnyPanelOffline(){for(const t of this._persistent.keys())if("panel-offline"===t||t.startsWith("panel-offline:"))return!0;return!1}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}watchPanelStatus(t){this.watchPanelStatuses([{entityId:t,panelName:null}])}watchPanelStatuses(t){const e=this._watchedPanels,n=new Map;for(const i of t){const t=e.get(i.entityId);n.set(i.entityId,{panelName:i.panelName??null,wasOffline:t?.wasOffline??!1})}const i=this._isSingleUnnamed(e),r=this._isSingleUnnamed(n);for(const t of e.keys()){n.has(t)&&i===r||this._persistent.delete(this._offlineKey(t,i))}this._watchedPanels=n,this._notify()}clearPanelStatusWatch(){if(0===this._watchedPanels.size)return;const t=this._isSingleUnnamed(this._watchedPanels);for(const e of this._watchedPanels.keys())this._persistent.delete(this._offlineKey(e,t));this._watchedPanels.clear(),this._notify()}updateHass(t){if(0===this._watchedPanels.size)return;const e=this._isSingleUnnamed(this._watchedPanels);for(const[n,o]of this._watchedPanels){const a=t.states[n]?.state,s="on"===a,l=this._offlineKey(n,e),c=this._reconnectKey(n,e);if(s){const t=o.wasOffline;o.wasOffline=!1,this.remove(l),t&&this.add({key:c,level:"info",message:null===o.panelName?i("error.panel_reconnected"):r("error.panel_reconnected_named",{name:o.panelName}),persistent:!1})}else o.wasOffline=!0,this.hasPersistent(l)||this.add({key:l,level:"error",message:null===o.panelName?i("error.panel_offline"):r("error.panel_offline_named",{name:o.panelName}),persistent:!0})}}dispose(){this._clearTransient(),this._persistent.clear(),this._subscribers.clear(),this._watchedPanels.clear()}_isSingleUnnamed(t){if(1!==t.size)return!1;for(const e of t.values())return null===e.panelName;return!1}_offlineKey(t,e){return e?"panel-offline":`panel-offline:${t}`}_reconnectKey(t,e){return e?"panel-reconnected":`panel-reconnected:${t}`}_clearTransient(){null!==this._transientTimer&&(clearTimeout(this._transientTimer),this._transientTimer=null),this._transient=null}_notify(){for(const t of this._subscribers)try{t()}catch(t){console.warn("SPAN Panel: error-store subscriber threw",t)}}}async function YA(t,e,n){if(!e)throw new Error(i("card.device_not_found"));const r={type:`${l}/panel_topology`,device_id:e},o=n?await n.callWS(t,r,{errorId:"fetch:topology"}):await t.callWS(r),a=Ae(o.panel_size)?o.panel_size:ZA(o.circuits);if(!De(o,a))throw new Error(i("card.topology_error"));const s={type:"config/device_registry/list"},c=n?await n.callWS(t,s,{errorId:"fetch:topology"}):await t.callWS(s),u=o.panel_device_id??e,d=c.find(t=>t.id===u)??null;return function(t,e){const n=new Map(e.map(t=>[t.id,t]));for(const e of Object.values(t)){const t=e.device_id?n.get(e.device_id):void 0,i=t?Qn(t):"";i&&(e.name=i)}}(o.circuits,c),await VA(t,o),{topology:o,panelDevice:d,panelSize:a}}function ZA(t){let e=0;for(const n of Object.values(t))if(n&&!Ie(n))for(const t of n.tabs)t>e&&(e=t);return e>0?e+e%2:0}const KA="_power",QA="Power";function JA(t,e){if(!t.endsWith(KA))return null;const n=`span_${e.toLowerCase()}_`,i=e&&t.startsWith(n)?t.slice(n.length,-6):t.split("_").slice(2,-1).join("_");return i?{circuitId:i,panelPrefix:t.slice(0,-(i.length+6+1))}:null}function tI(t,e){return`${t}_circuit_${e}`}function eI(t){if("string"!=typeof t||!t.startsWith("tabs ["))return null;const e=t.slice(6,-1),n=e.includes(":")?e.split(":").map(Number):[Number(e)];return n.every(Number.isFinite)?n:null}function nI(t,e){const n=e.filter(e=>t.startsWith(`${e} `)).sort((t,e)=>e.length-t.length)[0];return void 0===n?t:t.slice(n.length+1)}function iI(t,e){if(t===QA)return"";return nI(t.endsWith(` ${QA}`)?t.slice(0,-6):t,e)}function rI(t,e){const n=(t.model??"").toLowerCase(),i=n.includes("battery")||(t.identifiers??[]).some(t=>t[1].toLowerCase().includes("bess")),r=n.includes("drive")||(t.identifiers??[]).some(t=>t[1].toLowerCase().includes("evse")),o={};for(const t of e){const e={domain:t.entity_id.split(".")[0]??"",unique_id:t.unique_id},n=Jn(t);n&&(e.original_name=n),o[t.entity_id]=e}return{name:Qn(t),type:i?"bess":r?"evse":"unknown",entities:o}}async function oI(t,e,n){const r={type:"config/device_registry/list"},o={type:"config/entity_registry/list"},[a,s]=await Promise.all([n?n.callWS(t,r,{errorId:"fetch:topology"}):t.callWS(r),n?n.callWS(t,o,{errorId:"fetch:topology"}):t.callWS(o)]),c=a.find(t=>t.id===e);if(!c)return{topology:null,panelDevice:null,panelSize:0};const u=function(t){let e="";for(const n of t.identifiers??[]){if(!Array.isArray(n)||n.length<2)continue;const[t,i]=n;t===l&&"string"==typeof i&&(e=i)}return e}(c),d=Qn(c),h=function(t){return[t.name_by_user,t.name].flatMap(t=>t?.trim()?[t.trim()]:[])}(c),p=a.filter(t=>t.parent_device_id===c.id&&Kn(t,c)),f=a.filter(t=>t.via_device_id===c.id&&Kn(t,c)),g=new Set(p.map(t=>t.id)),m=new Map([c,...p,...f].map(t=>[t.id,t])),v=new Map;for(const t of p)for(const e of t.identifiers??[])e[0]===l&&v.set(e[1],t);const y=new Map;for(const t of s){if("string"!=typeof t.device_id||!m.has(t.device_id))continue;const e=y.get(t.device_id);e?e.push(t):y.set(t.device_id,[t])}const _=y.get(c.id)??[],b=[...y.values()].flat(),x=new Map,w=new Map;for(const t of b)t.entity_id.startsWith("sensor.")?x.set(t.unique_id,t.entity_id):t.entity_id.startsWith("switch.")&&w.set(t.unique_id.toLowerCase(),t.entity_id);const S={};for(const e of b){const n=t.states[e.entity_id];if(!n)continue;const i=n.attributes,r=eI(i.tabs);if(!r)continue;const o=JA(e.unique_id,u);if(!o)continue;const{circuitId:a,panelPrefix:s}=o,l="string"==typeof e.device_id?m.get(e.device_id):void 0,d=l&&g.has(l.id)?l:v.get(tI(u,a)),p=(d?Qn(d):"")||iI(Jn(e),h)||(l&&l!==c?nI(Qn(l),h):"")||e.entity_id,f="number"==typeof i.voltage?i.voltage:2===r.length?240:120,y={power:e.entity_id},_=w.get(`${s}_relay_${a}`.toLowerCase());_&&(y.switch=_);const b=x.get(`${s}_${a}_breaker_rating`);b&&(y.breaker_rating=b);const C={tabs:r,name:p,voltage:f,device_type:"string"==typeof i.device_type?i.device_type:"circuit",relay_state:"string"==typeof i.relay_state?i.relay_state:"UNKNOWN",is_user_controllable:!0,breaker_rating_a:null,entities:y};d&&(C.device_id=d.id),S[a]=C}let C=0;for(const e of _){const n=t.states[e.entity_id];if(n&&Ae(n.attributes.panel_size)){C=n.attributes.panel_size;break}}if(C||(C=ZA(S)),!C)throw new Error(i("card.panel_size_error"));const k={};for(const t of f)k[t.id]=rI(t,y.get(t.id)??[]);const M={serial:u,firmware:c.sw_version??"",panel_size:C,device_id:e,device_name:d||i("header.default_name"),circuits:S,sub_devices:k};return await VA(t,M),{topology:M,panelDevice:c,panelSize:C}}function aI(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function sI(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((t,n)=>sI(t,e[n]));if(!aI(t)||!aI(e))return!1;const n=Object.keys(t).filter(e=>void 0!==t[e]),i=Object.keys(e).filter(t=>void 0!==e[t]);return n.length===i.length&&n.every(n=>sI(t[n],e[n]))}function lI(t){const e={...t};for(const t of le)delete e[t];return e}function cI(t){const e=Object.fromEntries(Object.entries(t.circuits).map(([t,e])=>[t,lI(e)]));return{...t,circuits:e}}function uI(t){const e=t.getRootNode();return e instanceof Document||e instanceof ShadowRoot?e.activeElement:null}function dI(t){return null!==t&&uI(t)===t}function hI(t){if(!t)return!1;const e=uI(t);return null!==e&&t.contains(e)}function pI(t){return function(t){if(!t)return null;const e=uI(t);return e instanceof HTMLElement&&t.contains(e)?e:null}(t)?.dataset.role??null}function fI(t,e){t.addEventListener("blur",()=>{queueMicrotask(()=>{t.isConnected&&e()})})}const gI={continuous_threshold_pct:{min:1,max:200},spike_threshold_pct:{min:1,max:200},window_duration_m:{min:1,max:180},cooldown_duration_m:{min:1,max:180}};function mI(t){t.addEventListener("wheel",e=>{dI(t)&&e.preventDefault()},{passive:!1})}function vI(t){if(!t?.offered)return null;const[e,...n]=t.members;if(!e||n.length>0)return null;const i=e.circuit.package_ratings_form,r=e.circuit.breaker_rating_a;return"one_space"!==i&&"two_spaces"!==i||null==r?null:{kind:i,member:e,panelA:r}}function yI(t){return t.circuit.package_ratings_a?.[1]??null}class _I{constructor(t){this._host=t,this._section=null,this._field=null}get element(){return this._section}mount(t){this._field=null;const e=vI(this._host.ratingsView);this._section=e?this._build(e):null,this._section&&t.after(this._section)}sync(t){const e=vI(this._host.ratingsView),n=this._section;if(n&&e&&n.dataset.kind===e.kind&&n.dataset.uuid===e.member.uuid)return void this._patch(n,e);const i=pI(n);this._field=null;const r=e?this._build(e):null;if(n&&r?n.replaceWith(r):n?n.remove():r&&t.after(r),this._section=r,null===i)return;const o=r?.querySelector(`[data-role="${i}"]`)??r?.querySelector('[data-role="rating-input"]');o?o.focus():this._host.focusAfterRatingsEditor()}_build(t){const e=document.createElement("div");e.dataset.role="rating-section",e.dataset.kind=t.kind,e.dataset.uuid=t.member.uuid,e.className="rating-section";const n=document.createElement("div");n.className="section-label",n.textContent=i("monitoringRating.title"),e.appendChild(n);const r=document.createElement("div");r.className="field-label",r.id="rating-guidance",r.dataset.role="rating-guidance",r.textContent=i("one_space"===t.kind?"monitoringRating.guidance":"monitoringRating.guidance_two_spaces"),e.appendChild(r);const o=document.createElement("div");o.className="field-label rating-feedback",o.id="rating-feedback",o.dataset.role="rating-feedback",o.setAttribute("aria-live","polite"),e.appendChild(this._buildRow(t,o)),e.appendChild(o);const a=document.createElement("div");return a.dataset.role="rating-warning-region",a.setAttribute("aria-live","polite"),e.appendChild(a),this._syncWarning(e,t.member),e}_buildRow(t,e){const{member:n}=t,o=document.createElement("div");o.className="field-row rating-row",o.dataset.role="rating-row",o.dataset.uuid=n.uuid;const a=document.createElement("span");a.className="field-label",a.id="rating-panel-rating",a.dataset.role="rating-panel-rating",a.textContent=r("monitoringRating.panel_rating",{panel:String(t.panelA)});const s=document.createElement("span");s.className="field-label",s.textContent=i("monitoringRating.other_breaker");const l=document.createElement("input");l.type="number",l.min="1",l.step="1",l.inputMode="numeric";const c=yI(n);return l.value=null!==c?String(c):"",l.setAttribute("aria-label",r("monitoringRating.other_breaker_label",{circuit:n.circuit.name})),l.setAttribute("aria-describedby","rating-panel-rating rating-guidance rating-feedback"),l.dataset.role="rating-input",this._field=function(t,e){mI(t);let n=!1,r=null;const o=n=>{n?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),e.report(n)},a=()=>{n=!1,r=null,o(null);const i=e.stored();t.value=null!==i?String(i):""},s=()=>{if(!n)return;const s=t.value.trim();if(""===s&&t.validity?.badInput)return void o(i("monitoringRating.invalid_other"));if(""===s)return void a();const l=Number(s);!Number.isSafeInteger(l)||l<1?o(i("monitoringRating.invalid_other")):(n=!1,o(null),l!==e.stored()&&(r=l,e.save(l)))};return t.addEventListener("input",()=>{n=!0,r=null,o(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&s()}),fI(t,s),{get dirty(){return n},revert:a,answerRefusal:t=>r===t&&(a(),!0)}}(l,{report:t=>{e.textContent=t??""},stored:()=>this._storedInForce(),save:t=>this._save(t)}),o.append(a,s,l),null!==c&&o.appendChild(this._buildReset(n.uuid)),o}_buildReset(t){const e=document.createElement("button");return e.type="button",e.className="text-btn",e.dataset.role="rating-reset",e.textContent=i("monitoringRating.reset"),e.addEventListener("click",()=>{this._field?.revert(),this._host.clearPackageRatings(t).catch(t=>this._host.reportRatingsFailure(t))}),e}_patch(t,e){const{member:n}=e,i=yI(n),o=t.querySelector('[data-role="rating-panel-rating"]');o&&(o.textContent=r("monitoringRating.panel_rating",{panel:String(e.panelA)}));const a=t.querySelector('[data-role="rating-input"]');this._field&&!this._field.dirty&&this._field.revert();const s=t.querySelector('[data-role="rating-row"]'),l=t.querySelector('[data-role="rating-reset"]');null===i&&l?(dI(l)&&a?.focus(),l.remove()):null!==i&&!l&&s&&s.appendChild(this._buildReset(n.uuid)),this._syncWarning(t,n)}_storedInForce(){const t=vI(this._host.ratingsView);return t?yI(t.member):null}_save(t){const e=vI(this._host.ratingsView);if(!e)return;const{member:n,panelA:i}=e;this._host.setPackageRatings(n.uuid,[i,t]).catch(e=>{this._host.reportRatingsFailure(e),this._answerRefusal(n.uuid,t)})}_answerRefusal(t,e){const n=this._section,i=n?.querySelector('[data-role="rating-input"]'),r=this._field;n&&i&&r&&n.dataset.uuid===t&&vI(this._host.ratingsView)?.member.uuid===t&&r.answerRefusal(e)&&(null===document.activeElement||document.activeElement===document.body||hI(n))&&i.focus()}_syncWarning(t,e){const n=t.querySelector('[data-role="rating-warning-region"]');if(!n)return;const i=on(e.circuit,this._host.ratingsView?.monitoringInfo??null),r=n.firstElementChild instanceof HTMLElement?n.firstElementChild:null;if(r&&r.dataset.kind===i)return;const o=hI(r);r?.remove(),i&&n.appendChild("averaged_legs"===i?this._buildAveragedLegsWarning():this._buildThresholdWarning(i)),o&&this._host.focusAfterRatingsEditor()}_buildThresholdWarning(t){const e="own"===t?i("monitoringRating.threshold_warning"):r("monitoringRating.threshold_warning_global",{settings:i("monitoring.global_settings"),tab:i("tab.monitoring")}),n=this._buildWarning("rating-threshold-warning",t,e);return"own"===t&&n.appendChild(this._buildActionButton("rating-threshold-reset",i("monitoringRating.use_global_thresholds"),()=>this._host.useGlobalThresholds())),n}_buildAveragedLegsWarning(){const t=this._buildWarning("rating-averaged-legs-warning","averaged_legs",i("monitoringRating.averaged_legs"));return t.appendChild(this._buildActionButton("rating-turn-off-monitoring",i("monitoringRating.turn_off_monitoring"),()=>this._host.turnOffMonitoring())),t}_buildWarning(t,e,n){const i=document.createElement("div");i.className="field-label rating-warning",i.dataset.role=t,i.dataset.kind=e,i.setAttribute("role","note");const r=document.createElement("span");return r.textContent=n,i.appendChild(r),i}_buildActionButton(t,e,n){const i=document.createElement("button");return i.type="button",i.className="text-btn",i.dataset.role=t,i.textContent=e,i.addEventListener("click",()=>{"true"!==i.getAttribute("aria-disabled")&&(i.setAttribute("aria-disabled","true"),n().then(t=>{t||i.removeAttribute("aria-disabled")}))}),i}}function bI(t){return!0===t?.user?.is_admin}function xI(){return i("monitoring.admin_only")}class wI extends Error{constructor(){super(xI()),this.name="MonitoringChangeRefused"}}function SI(t){const e=e=>n=>async function(t,e,n){if(!t||!bI(t))throw new wI;try{await t.callWS({type:"call_service",domain:l,service:e,service_data:n})}catch(t){throw ie(t)?new wI:t}}(t,e,n);return{setGlobalMonitoring:e("set_global_monitoring"),testNotification:e("test_notification"),setCircuitThreshold:e("set_circuit_threshold"),clearCircuitThreshold:e("clear_circuit_threshold"),setMainsThreshold:e("set_mains_threshold"),clearMainsThreshold:e("clear_mains_threshold"),setCircuitPackageRatings:e("set_circuit_package_ratings"),clearCircuitPackageRatings:e("clear_circuit_package_ratings")}}function CI(t,e){return t instanceof wI?t.message:e}function kI(t,e,n){console.warn(`SPAN Panel: ${n} failed`,e),t?.add({key:"service:monitoring",level:"error",message:CI(e,i("error.threshold_failed")),persistent:!1})}const MI=new Set(["number","text"]);function TI(t){for(let e=t;e;e=e.parentElement)if(""!==e.style.opacity&&Number(e.style.opacity)<1)return!0;return!1}const AI="favorites-changed";async function II(t,e,n={}){const i=await t.callWS({type:"call_service",domain:l,service:e,service_data:n,return_response:!0});return i?.response??null}const DI={continuous:"continuous_threshold_pct",spike:"spike_threshold_pct","window-m":"window_duration_m","cooldown-m":"cooldown_duration_m"},PI="relay-label",LI="priority-label",EI="controls-note";class NI{constructor(t,e){this.uuid=t,this._on=e,this._sent=0,this._from=0,this._pending=0}get on(){return this._on}get settled(){return 0===this._pending}answered(t){this._on=t}async send(t,e){const n=++this._sent;this._pending+=1;try{const i=await e();return i&&n>this._from&&(this._on=t,this._from=n),i}finally{this._pending-=1}}}class RI extends HTMLElement{constructor(){super(),this.errorStore=null,this._thresholdReads=0,this._limitFields=[],this._storedMonitoring=null,this._controlAccess=de,this.attachShadow({mode:"open"}),this._hass=null,this._config=null,this._debounceTimers={},this._ratingsEditor=new _I(this)}set hass(t){const e=bI(this._hass)!==bI(t);this._hass=t,this.hasAttribute("open")&&this._config&&(e&&this._showsMonitoring()?this._render():this._updateLiveState())}_showsMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!0!==t.showMonitoring)}get hass(){return this._hass}open(t){this._config=t,this._storedMonitoring=t.panelMode||t.subDeviceMode||t.favoritesMode?null:new NI(t.uuid,en(t.monitoringInfo)),this._controlAccess=t.panelMode||t.subDeviceMode||t.favoritesMode?de:t.controlAccess,this._render(),this.offsetHeight,this.setAttribute("open",""),this.setAttribute("data-mode",this._modeFor(t))}get openCircuit(){const t=this._config;return!t||!this.hasAttribute("open")||t.panelMode||t.subDeviceMode||t.favoritesMode?null:{uuid:t.uuid,configEntryId:t.configEntryId??null}}refreshRating(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i={...e,members:t.members,capacityA:t.capacityA,monitoringInfo:t.monitoringInfo,monitoringGlobals:t.monitoringGlobals};this._config=i,this._monitoringStoredAs(e.uuid,t.monitoringInfo);const r=n.querySelector(".subtitle");r&&(r.textContent=this._circuitSubtitle(i)),this._syncMonitoring()}close(){this.removeAttribute("open"),this.removeAttribute("data-mode"),this._config=null,this._storedMonitoring=null,this._controlAccess=de,this.dispatchEvent(new CustomEvent("side-panel-closed",{bubbles:!0,composed:!0}))}_modeFor(t){return t.favoritesMode?"favorites":t.panelMode?"panel":t.subDeviceMode?"subDevice":"circuit"}_render(){const t=this._config;if(!t)return;const e=this.shadowRoot;if(!e)return;e.innerHTML="";const n=document.createElement("style");n.textContent='\n :host {\n display: block;\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n width: 360px;\n max-width: 90vw;\n z-index: 1000;\n transform: translateX(100%);\n transition: transform 0.3s ease;\n pointer-events: none;\n }\n :host([open]) {\n transform: translateX(0);\n pointer-events: auto;\n }\n\n .backdrop {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.3);\n z-index: -1;\n }\n :host([open]) .backdrop {\n display: block;\n }\n\n .panel {\n height: 100%;\n background: var(--card-background-color, #fff);\n border-left: 1px solid var(--divider-color, #e0e0e0);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n\n .panel-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px;\n border-bottom: 1px solid var(--divider-color, #e0e0e0);\n }\n .panel-header .title {\n font-size: 18px;\n font-weight: 500;\n color: var(--primary-text-color, #212121);\n margin: 0;\n }\n .panel-header .subtitle {\n font-size: 13px;\n color: var(--secondary-text-color, #727272);\n margin: 2px 0 0 0;\n }\n .close-btn {\n background: none;\n border: none;\n cursor: pointer;\n color: var(--secondary-text-color, #727272);\n padding: 4px;\n line-height: 1;\n font-size: 20px;\n }\n\n .panel-body {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n }\n\n .section {\n margin-bottom: 20px;\n }\n .section-label {\n font-size: 12px;\n font-weight: 600;\n text-transform: uppercase;\n color: var(--secondary-text-color, #727272);\n margin: 0 0 8px 0;\n letter-spacing: 0.5px;\n }\n\n .field-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 8px 0;\n }\n /* Why the section\'s relay or priority cannot be operated, under it. */\n .controls-note {\n margin: 4px 0 0;\n font-size: 0.85em;\n color: var(--secondary-text-color, #727272);\n }\n .field-label {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n }\n\n select {\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n }\n\n input[type="number"] {\n width: 72px;\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n text-align: right;\n }\n input[type="number"]:disabled {\n opacity: 0.5;\n }\n\n .radio-group {\n display: flex;\n gap: 16px;\n padding: 8px 0;\n }\n .radio-group label {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n cursor: pointer;\n }\n\n .horizon-bar {\n display: flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n margin-top: 4px;\n }\n .horizon-segment {\n flex: 1;\n padding: 6px 0;\n text-align: center;\n font-size: 13px;\n cursor: pointer;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n transition: background 0.15s ease, color 0.15s ease;\n user-select: none;\n line-height: 1.4;\n }\n .horizon-segment:last-child {\n border-right: none;\n }\n .horizon-segment:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .horizon-segment.active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n .horizon-segment.referenced {\n box-shadow: inset 0 -3px 0 var(--primary-color, #03a9f4);\n }\n\n .unit-toggle {\n display: inline-flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n }\n .unit-btn {\n padding: 4px 10px;\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease;\n }\n .unit-btn:last-child {\n border-right: none;\n }\n .unit-btn:hover:not(.unit-active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .unit-btn.unit-active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n\n .monitoring-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n\n .fav-heart {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--secondary-text-color, #727272);\n border-radius: 4px;\n padding: 2px 6px;\n cursor: pointer;\n font-size: 0.9em;\n margin-right: 6px;\n line-height: 1;\n display: inline-flex;\n align-items: center;\n }\n .fav-heart.active {\n color: var(--primary-color, #03a9f4);\n border-color: var(--primary-color, #03a9f4);\n }\n .fav-heart:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .fav-heart span-icon {\n --mdc-icon-size: 16px;\n }\n\n .rating-section {\n margin-bottom: 8px;\n }\n .limit-row {\n flex-wrap: wrap;\n }\n .limit-feedback {\n flex-basis: 100%;\n }\n .rating-row {\n flex-wrap: wrap;\n justify-content: flex-start;\n gap: 6px 8px;\n }\n .rating-row [data-role="rating-panel-rating"] {\n flex-basis: 100%;\n }\n .rating-feedback {\n font-size: 13px;\n color: var(--error-color, #db4437);\n }\n .rating-warning {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 6px 8px;\n margin-top: 6px;\n padding: 8px;\n border-left: 3px solid var(--warning-color, #ffa600);\n border-radius: 4px;\n background: color-mix(in srgb, var(--warning-color, #ffa600) 12%, transparent);\n font-size: 13px;\n }\n\n .text-btn {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--primary-text-color, #212121);\n border-radius: 4px;\n padding: 4px 8px;\n font: inherit;\n font-size: 13px;\n line-height: 1.3;\n cursor: pointer;\n }\n .text-btn:hover:not(:disabled):not([aria-disabled="true"]) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .text-btn:focus-visible {\n outline: 2px solid var(--primary-color, #03a9f4);\n outline-offset: 1px;\n }\n .text-btn:disabled,\n .text-btn[aria-disabled="true"] {\n opacity: 0.5;\n cursor: default;\n }\n\n .panel-mode-info {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n line-height: 1.6;\n }\n .panel-mode-info p {\n margin: 0 0 12px 0;\n }\n\n',e.appendChild(n);const i=document.createElement("div");i.className="backdrop",i.addEventListener("click",()=>this.close()),e.appendChild(i);const r=document.createElement("div");r.className="panel",e.appendChild(r),t.favoritesMode?this._renderFavoritesMode(r):t.panelMode?this._renderPanelMode(r):t.subDeviceMode?this._renderSubDeviceMode(r,t):this._renderCircuitMode(r,t)}_renderPanelMode(t){const e=this._config,n=this._createHeader(i("sidepanel.graph_settings"),i("sidepanel.global_defaults"));t.appendChild(n);const r=document.createElement("div");r.className="panel-body";const o=e.graphSettings,l=e.topology,c=o?.global_horizon??a,u=o?.circuits??{};r.appendChild(this._buildListColumnsSection());const d=document.createElement("div");d.className="section";const h=document.createElement("div");h.className="section-label",h.textContent=i("sidepanel.graph_horizon"),d.appendChild(h);const p=document.createElement("div");p.className="field-row";const f=document.createElement("span");f.className="field-label",f.textContent=i("sidepanel.global_default"),p.appendChild(f);const g=document.createElement("select");for(const t of Object.keys(s)){const e=document.createElement("option");e.value=t;const n=`horizon.${t}`,r=i(n);e.textContent=r!==n?r:t,t===c&&(e.selected=!0),g.appendChild(e)}if(g.addEventListener("change",()=>{const t={horizon:g.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_graph_time_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})}),p.appendChild(g),d.appendChild(p),r.appendChild(d),l?.circuits){const t=document.createElement("div");t.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=i("sidepanel.circuit_scales"),t.appendChild(n);const o=Object.entries(l.circuits).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[n,i]of o){const r=this._buildPanelModeCircuitRow(n,i,u[n],c,e.configEntryId??null,e.showFavorites??!1,e.favoritePanelDeviceId,e.favoriteCircuitUuids);t.appendChild(r)}r.appendChild(t)}const m=o?.sub_devices??{};if(l?.sub_devices){const t=document.createElement("div");t.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=i("sidepanel.subdevice_scales"),t.appendChild(n);const o=Object.entries(l.sub_devices).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[n,r]of o){const o=qn(r).length>0,a=e.showFavorites&&e.favoritePanelDeviceId?this._buildSubDeviceFavoriteHeart(r.entities,e.favoriteSubDeviceIds?.has(n)??!1):null;if(!o&&!a)continue;const l=document.createElement("div");l.className="field-row";const u=document.createElement("span");if(u.className="field-label",u.textContent=r.name||n,u.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",l.appendChild(u),a&&l.appendChild(a),!o){t.appendChild(l);continue}const d=m[n]||{horizon:c,has_override:!1},h=d.has_override?d.horizon:c,p=document.createElement("select");p.dataset.subdevId=n;for(const t of Object.keys(s)){const e=document.createElement("option");e.value=t;const n=`horizon.${t}`,r=i(n);e.textContent=r!==n?r:t,t===h&&(e.selected=!0),p.appendChild(e)}if(p.addEventListener("change",()=>{this._debounce(`subdev-${e.configEntryId??""}-${n}`,500,()=>{const t={subdevice_id:n,horizon:p.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_subdevice_graph_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})})}),l.appendChild(p),d.has_override){const t=document.createElement("button");t.textContent="↺",t.title=i("sidepanel.reset_to_global"),Object.assign(t.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),t.addEventListener("click",()=>{const r={subdevice_id:n};e.configEntryId&&(r.config_entry_id=e.configEntryId),this._callDomainService("clear_subdevice_graph_horizon",r).then(()=>{p.value=c,t.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})}),l.appendChild(t)}t.appendChild(l)}t.children.length>1&&r.appendChild(t)}t.appendChild(r)}_buildPanelModeCircuitRow(t,e,n,r,o,a,l,c){const u=document.createElement("div");u.className="field-row";const d=document.createElement("span");if(d.className="field-label",d.textContent=e.name||t,d.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",u.appendChild(d),a&&l){const n=this._buildFavoriteHeart(e.entities,c?.has(t)??!1);n&&u.appendChild(n)}const h=n||{horizon:r,has_override:!1},p=h.has_override?h.horizon:r,f=document.createElement("select");f.dataset.uuid=t;for(const t of Object.keys(s)){const e=document.createElement("option");e.value=t;const n=`horizon.${t}`,r=i(n);e.textContent=r!==n?r:t,t===p&&(e.selected=!0),f.appendChild(e)}if(f.addEventListener("change",()=>{this._debounce(`circuit-${o??""}-${t}`,500,()=>{const e={circuit_id:t,horizon:f.value};o&&(e.config_entry_id=o),this._callDomainService("set_circuit_graph_horizon",e).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})})}),u.appendChild(f),h.has_override){const e=document.createElement("button");e.textContent="↺",e.title=i("sidepanel.reset_to_global"),Object.assign(e.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),e.addEventListener("click",()=>{const n={circuit_id:t};o&&(n.config_entry_id=o),this._callDomainService("clear_circuit_graph_horizon",n).then(()=>{f.value=r,e.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})}),u.appendChild(e)}return u}_renderFavoritesMode(t){const e=this._config,n=this._createHeader(i("sidepanel.graph_settings"),i("sidepanel.favorites_subtitle"));t.appendChild(n);const r=document.createElement("div");r.className="panel-body",r.appendChild(this._buildListColumnsSection());for(const t of e.perPanelSections)r.appendChild(this._buildFavoritesPanelSection(t));t.appendChild(r)}_buildFavoritesPanelSection(t){const e=document.createElement("div");e.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=t.panelName,e.appendChild(n);const i=t.graphSettings?.global_horizon??a,r=t.graphSettings?.circuits??{},o=function(t){const e=t.circuits??{};return Object.entries(e).map(([t,e])=>({uuid:t,circuit:e})).sort((t,e)=>(t.circuit.name||"").localeCompare(e.circuit.name||""))}(t.topology);for(const{uuid:n,circuit:a}of o){const o=this._buildPanelModeCircuitRow(n,a,r[n],i,t.configEntryId,!0,t.panelDeviceId,t.favoriteCircuitUuids);e.appendChild(o)}return e}_renderCircuitMode(t,e){const n=this._createHeader(e.name,this._circuitSubtitle(e));t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),this._renderRelaySection(i,e),e.showFavorites&&this._renderFavoriteSection(i,e),this._renderSheddingSection(i,e),this._placeControlNote(i),this._renderGraphHorizonSection(i,e),e.showMonitoring&&this._renderMonitoringSection(i,e)}_placeControlNote(t){t.querySelector('[data-role="controls-note"]')?.remove();const e=[...t.querySelectorAll('[data-role="relay-toggle"], [data-role="shedding-select"]')];e[0]?.closest(".section")?.insertAdjacentHTML("beforeend",Me(this._controlAccess));const n=t.querySelector('[data-role="controls-note"]');n&&(n.id=EI);for(const t of e)n?t.setAttribute("aria-describedby",EI):t.removeAttribute("aria-describedby")}refreshControlAccess(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i=this._controlAccess;i.mayOperate===t.mayOperate&&i.reason===t.reason||(this._controlAccess=t,this._updateLiveState(),this._placeControlNote(n))}_circuitSubtitle(t){const e=t.members.map(t=>t.circuit),n=[...new Set(e.flatMap(t=>t.voltage?[t.voltage]:[]))].sort((t,e)=>t-e);return[je(e),e.length>1&&t.capacityA?r("sidepanel.capacity",{amps:String(t.capacityA)}):"",n.length>0?`${n.join("/")}V`:"",`Tabs [${Fe(e).join(",")}]`].filter(Boolean).join(" · ")}_favoriteEntityId(t){return t?.current??t?.power??null}_buildSubDeviceFavoriteHeart(t,e){const n=Gn(t);return n?this._buildHeartButton(n,e):null}_buildListColumnsSection(){const t=document.createElement("div");t.className="section";const e=document.createElement("div");e.className="section-label",e.textContent=i("sidepanel.list_view_columns"),t.appendChild(e);const n=document.createElement("div");n.className="field-row";const r=document.createElement("span");r.className="field-label",r.textContent=i("sidepanel.columns"),n.appendChild(r);const o=Wt(),a=document.createElement("div");a.className="unit-toggle";for(const t of[1,2,3]){const e=document.createElement("button");e.type="button",e.className="unit-btn"+(t===o?" unit-active":""),e.dataset.columns=String(t),e.textContent=String(t),e.addEventListener("click",()=>{jt(t);for(const t of a.querySelectorAll(".unit-btn"))t.classList.toggle("unit-active",t===e);this.dispatchEvent(new CustomEvent("list-columns-changed",{detail:t,bubbles:!0,composed:!0}))}),a.appendChild(e)}return n.appendChild(a),t.appendChild(n),t}_buildFavoriteHeart(t,e){const n=this._favoriteEntityId(t);return n?this._buildHeartButton(n,e):(console.warn("SPAN Panel: circuit has no current/power sensor; favorite heart suppressed"),null)}_buildHeartButton(t,e){const n=document.createElement("button");n.type="button",n.className=e?"fav-heart active":"fav-heart",n.dataset.role="fav-heart",n.title=i("sidepanel.save_to_favorites"),n.setAttribute("role","switch"),n.setAttribute("aria-checked",String(e)),n.setAttribute("aria-label",i("sidepanel.save_to_favorites"));const r=document.createElement("span-icon");return r.setAttribute("icon",e?"mdi:heart":"mdi:heart-outline"),n.appendChild(r),n.addEventListener("click",e=>{e.stopPropagation(),this._toggleFavoriteEntity(n,r,t).catch(()=>{})}),n}async _toggleFavoriteEntity(t,e,n){if(!this._hass)return;const r=t.classList.contains("active"),o=!r;t.classList.toggle("active",o),e.setAttribute("icon",o?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(o));try{o?await async function(t,e){const n=await II(t,"add_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(AI)),n?.favorites??{}}(this._hass,n):await async function(t,e){const n=await II(t,"remove_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(AI)),n?.favorites??{}}(this._hass,n)}catch(n){throw t.classList.toggle("active",r),e.setAttribute("icon",r?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(r)),console.warn("SPAN Panel: favorite toggle failed",n),this.errorStore?.add({key:"service:favorites",level:"error",message:i("error.favorites_toggle_failed"),persistent:!1}),n}}_renderFavoriteSection(t,e){const n=this._favoriteEntityId(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_appendFavoriteHeartSection(t,e,n){const r=document.createElement("div");r.className="section",r.innerHTML=``;const o=document.createElement("div");o.className="field-row";const a=document.createElement("span");a.className="field-label",a.textContent=i("sidepanel.save_to_favorites"),o.appendChild(a),o.appendChild(this._buildHeartButton(e,n)),r.appendChild(o),t.appendChild(r)}_renderSubDeviceMode(t,e){const n=this._createHeader(e.name,e.deviceType);t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),e.showFavorites&&this._renderSubDeviceFavoriteSection(i,e),e.hasChart&&this._renderSubDeviceHorizonSection(i,e)}_renderSubDeviceFavoriteSection(t,e){const n=Gn(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_renderSubDeviceHorizonSection(t,e){const n=document.createElement("div");n.className="section";const r=document.createElement("div");r.className="section-label",r.textContent=i("sidepanel.graph_horizon"),n.appendChild(r);const o=e.graphHorizonInfo,l=!0===o?.has_override,c=o?.horizon||a,u=o?.globalHorizon||a,d=document.createElement("div");d.className="horizon-bar";const h=[{key:"global",label:i("sidepanel.global")}];for(const t of Object.keys(s))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of d.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===u)}};for(const{key:t,label:n}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=n,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===u),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const n={subdevice_id:e.subDeviceId};e.configEntryId&&(n.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_subdevice_graph_horizon",n).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_subdevice_graph_horizon",{...n,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})}))}),d.appendChild(r)}n.appendChild(d),t.appendChild(n)}_createHeader(t,e){const n=document.createElement("div");n.className="panel-header";const i=document.createElement("div"),r=document.createElement("div");if(r.className="title",r.textContent=t,i.appendChild(r),e){const t=document.createElement("div");t.className="subtitle",t.textContent=e,i.appendChild(t)}const o=document.createElement("button");return o.className="close-btn",o.innerHTML="✕",o.addEventListener("click",()=>this.close()),n.appendChild(i),n.appendChild(o),n}_renderRelaySection(t,e){if(!this._hass||"none"===_n(e,this._hass))return;const n=document.createElement("div");n.className="section",n.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=PI,o.textContent=i("sidepanel.breaker");const a=document.createElement("span-switch");a.dataset.role="relay-toggle",a.setAttribute("aria-labelledby",PI);const s=e.entities.switch;this._applyRelayToggle(a,e),a.addEventListener("change",()=>{const t=this._hass;t&&s&&"operable"===_n(e,t)&&xe(t,this._controlAccess).setRelay(s,a.checked).catch(n=>{Ce(t,this.errorStore,n,"relay"),this._applyRelayToggle(a,e)})}),r.appendChild(o),r.appendChild(a),n.appendChild(r),t.appendChild(n)}_renderSheddingSection(t,e){if(!e.entities?.select)return;const n=document.createElement("div");n.className="section",n.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=LI,o.textContent=i("sidepanel.priority_label");const a=document.createElement("select");a.dataset.role="shedding-select",a.setAttribute("aria-labelledby",LI);const s=e.entities.select;for(const t of x){const e=b[t];if(!e)continue;const n=document.createElement("option");n.value=t,n.textContent=i(`shedding.select.${t}`)||e.label(),a.appendChild(n)}a.addEventListener("change",()=>{const t=this._hass;t&&xe(t,this._controlAccess).setPriority(s,a.value).catch(n=>{Ce(t,this.errorStore,n,"priority"),this._applySheddingSelect(a,e)})}),r.appendChild(o),r.appendChild(a),n.appendChild(r),t.appendChild(n),this._applySheddingSelect(a,e)}get ratingsView(){const t=this._config;return!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!t.showMonitoring?null:{members:t.members??[],monitoringInfo:t.monitoringInfo,offered:!0===t.monitoringRatingOffered}}setPackageRatings(t,e){return SI(this._hass).setCircuitPackageRatings(this._ratingsPayload(t,{package_ratings_a:[...e]}))}clearPackageRatings(t){return SI(this._hass).clearCircuitPackageRatings(this._ratingsPayload(t,{}))}reportRatingsFailure(t){!function(t,e,n){console.warn("SPAN Panel: package ratings update failed",n),se(t,n,l,i("error.package_ratings_failed")).then(t=>{e?.add({key:"service:package-ratings",level:"error",message:t,persistent:!1})})}(this._hass,this.errorStore,t)}async useGlobalThresholds(){const t=this._config,e=this.shadowRoot;if(!t||!e||t.panelMode||t.subDeviceMode||t.favoritesMode)return!1;const n=e.querySelector('input[name="monitoring-mode"][value="global"]'),i=e.querySelector('input[name="monitoring-mode"][value="custom"]'),r=e.querySelector('[data-role="threshold-fields"]');n&&(n.checked=!0),r&&(r.style.display="none"),this._thresholdReads+=1;const o={circuit_id:t.entities?.power||t.uuid};t.configEntryId&&(o.config_entry_id=t.configEntryId);try{await SI(this._hass).clearCircuitThreshold(o)}catch(e){return kI(this.errorStore,e,"monitoring update"),this._config===t&&(i&&(i.checked=!0),r&&(r.style.display="block")),!1}const a=this._config===t?t.monitoringGlobals??null:null;return this._monitoringChanged(t.uuid,{has_override:!1,continuous_threshold_pct:a?.continuous_threshold_pct,spike_threshold_pct:a?.spike_threshold_pct}),!0}async turnOffMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode)&&this._sendMonitoringEnabled(t,!1)}focusAfterRatingsEditor(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"]:checked')??t?.querySelector('input[name="monitoring-mode"]');e?.focus()}_ratingsPayload(t,e){const n={circuit_id:t,...e},i=this._config,r=!i||i.panelMode||i.subDeviceMode||i.favoritesMode?null:i.configEntryId;return r&&(n.config_entry_id=r),n}_monitoringChanged(t,e){const n=this._openCircuitConfig(t);n&&(this._config={...n,monitoringInfo:{...n.monitoringInfo??{},...e}},this._syncMonitoring())}_monitoringAnswered(t,e,n){const i=this._openCircuitConfig(t);i&&(this._config={...i,monitoringInfo:e,monitoringGlobals:n},this._monitoringStoredAs(t,e),!0!==e.has_override&&this._showGlobalChoice(),this._syncMonitoring())}_monitoringStoredAs(t,e){const n=this._storedMonitoring;e&&n?.uuid===t&&n.answered(en(e))}_showStoredMonitoring(t){if(!t||t!==this._storedMonitoring||!t.settled)return;const e=this.shadowRoot?.querySelector('[data-role="monitoring-toggle"]')?.hasAttribute("checked");e!==t.on&&this._showMonitoringEnabled(t.uuid,t.on)}_showGlobalChoice(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"][value="global"]'),n=t?.querySelector('[data-role="threshold-fields"]');e&&n&&!e.checked&&!this._limitFields.some(t=>t.dirty)&&(e.checked=!0,hI(n)&&e.focus(),n.style.display="none")}_openCircuitConfig(t){const e=this._config;return!e||e.panelMode||e.subDeviceMode||e.favoritesMode||e.uuid!==t||!this.hasAttribute("open")?null:e}_syncMonitoring(){const t=this._config,e=this.shadowRoot?.querySelector('[data-role="judged-against"]');if(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!e)return;const n=this._judgedAgainstText(t.monitoringInfo);e.textContent!==n&&(e.textContent=n),this._ratingsEditor.sync(e),this._lockMonitoringIfReadOnly()}_renderGraphHorizonSection(t,e){const n=document.createElement("div");n.className="section",n.dataset.role="horizon-section";const r=document.createElement("div");r.className="section-label",r.textContent=i("sidepanel.graph_horizon"),n.appendChild(r);const o=e.graphHorizonInfo,l=!0===o?.has_override,c=o?.horizon||a,u=o?.globalHorizon||a,d=document.createElement("div");d.className="horizon-bar";const h=[{key:"global",label:i("sidepanel.global")}];for(const t of Object.keys(s))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of d.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===u)}};for(const{key:t,label:n}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=n,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===u),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const n={circuit_id:e.uuid};e.configEntryId&&(n.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_circuit_graph_horizon",n).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_circuit_graph_horizon",{...n,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})}))}),d.appendChild(r)}n.appendChild(d),t.appendChild(n)}_judgedAgainstText(t){return function(t){return t.amps?t.userSet?r("monitoringRating.judged_copied",{rating:String(t.amps),copied:an(t)}):r("sidepanel.judged_against",{rating:`${t.amps} A`}):r("sidepanel.judged_against",{rating:i("monitoringRating.none")})}({amps:(e=t)?tn(e):void 0,panelAmps:e?.breaker_rating_a,userSet:!0===e?.monitoring_rating_user_set,packageRatings:e?.package_ratings_a??null});var e}_renderMonitoringSection(t,e){const n=document.createElement("div");n.className="section",n.dataset.role="monitoring-section";const r=document.createElement("div");r.className="monitoring-header";const o=document.createElement("div");o.className="section-label",o.textContent=i("sidepanel.monitoring"),o.style.margin="0";const a=document.createElement("span-switch");a.dataset.role="monitoring-toggle";const s=e.monitoringInfo,l=en(s);l&&a.setAttribute("checked",""),r.appendChild(o),r.appendChild(a),n.appendChild(r),bI(this._hass)||n.appendChild(function(){const t=document.createElement("p");return t.dataset.role="monitoring-read-only",t.setAttribute("role","note"),t.style.cssText="margin:8px 0 12px;font-size:0.85em;color:var(--secondary-text-color);",t.textContent=xI(),t}());const c=document.createElement("div");c.dataset.role="monitoring-details",c.style.display=l?"block":"none",n.appendChild(c);const u=!0===s?.has_override,d=document.createElement("div");d.className="field-label",d.dataset.role="judged-against",d.setAttribute("aria-live","polite"),d.style.marginBottom="8px",d.textContent=this._judgedAgainstText(s),c.appendChild(d),this._ratingsEditor.mount(d);const h=document.createElement("div");h.className="radio-group",h.innerHTML=`\n \n \n `,c.appendChild(h),this._limitFields=[];const p=document.createElement("div");p.dataset.role="threshold-fields",p.style.display=u?"block":"none";const f=s?.continuous_threshold_pct??80,g=s?.spike_threshold_pct??100,m=s?.window_duration_m??15,v=s?.cooldown_duration_m??15;p.appendChild(this._createLimitRow(i("sidepanel.continuous_pct"),"continuous",f,null,e)),p.appendChild(this._createLimitRow(i("sidepanel.spike_pct"),"spike",g,null,e)),p.appendChild(this._createLimitRow(i("sidepanel.window_duration"),"window-m",m,"m",e)),p.appendChild(this._createLimitRow(i("sidepanel.cooldown"),"cooldown-m",v,"m",e)),c.appendChild(p),a.addEventListener("change",()=>{const t=a.checked;this._showMonitoringEnabled(e.uuid,t),this._sendMonitoringEnabled(e,t)});const y=h.querySelectorAll('input[type="radio"]');for(const t of y)t.addEventListener("change",()=>{t.checked&&("custom"===t.value?p.style.display="block":this.useGlobalThresholds())});t.appendChild(n),this._lockMonitoringIfReadOnly()}_lockMonitoringIfReadOnly(){const t=this.shadowRoot?.querySelector('[data-role="monitoring-section"]');t&&!bI(this._hass)&&function(t){const e=xI();for(const n of t.querySelectorAll("input, select, textarea, button, span-switch"))n instanceof HTMLInputElement&&MI.has(n.type)||n instanceof HTMLTextAreaElement?n.readOnly=!0:n.setAttribute("disabled",""),n.title=e,"span-switch"!==n.localName&&(TI(n)||(n.style.opacity="0.5"),n.style.cursor="not-allowed")}(t)}async _sendMonitoringEnabled(t,e){const n={circuit_id:t.entities?.power||t.uuid,monitoring_enabled:e};t.configEntryId&&(n.config_entry_id=t.configEntryId);const i=async()=>{try{return await SI(this._hass).setCircuitThreshold(n),!0}catch(t){return kI(this.errorStore,t,"monitoring update"),!1}},r=this._storedMonitoring;if(r?.uuid!==t.uuid)return i();const o=await r.send(e,i);return this._showStoredMonitoring(r),o}_showMonitoringEnabled(t,e){const n=this.shadowRoot;if(!this._openCircuitConfig(t)||!n)return;const i=n.querySelector('[data-role="monitoring-toggle"]');i?.toggleAttribute("checked",e);const r=n.querySelector('[data-role="monitoring-details"]');if(r){const t=!e&&hI(r);r.style.display=e?"block":"none",t&&i?.focus()}this._monitoringChanged(t,{monitoring_enabled:e})}_createLimitRow(t,e,n,i,o){const a=DI[e],{min:s,max:l}=gI[a],c=document.createElement("div");c.className="field-row limit-row";const u=document.createElement("span");u.className="field-label",u.id=`threshold-label-${e}`,u.textContent=t;const d=document.createElement("div"),h=document.createElement("input");if(h.type="number",h.setAttribute("aria-labelledby",u.id),h.min=String(s),h.max=String(l),h.step="1",h.value=String(n),h.dataset.role=`threshold-${e}`,h.setAttribute("aria-describedby",`threshold-feedback-${e}`),d.appendChild(h),i){const t=document.createElement("span");t.textContent=i,d.appendChild(t)}const p=document.createElement("div");p.className="field-label rating-feedback limit-feedback",p.id=`threshold-feedback-${e}`,p.dataset.role=`threshold-feedback-${e}`,p.setAttribute("aria-live","polite");const f=function(t,e,n){const{min:i,max:o}=gI[e];mI(t);let a=!1;const s=e=>{e?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),n.report(e)},l=()=>{const e=""===t.value.trim()?Number.NaN:Number(t.value);return Number.isSafeInteger(e)&&e>=i&&e<=o?e:(s(r("monitoring.limit_invalid",{min:String(i),max:String(o)})),null)},c=()=>{if(!a)return;const t=l();null!==t&&(a=!1,s(null),n.save(t))};return t.addEventListener("input",()=>{a=!0,s(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&c()}),fI(t,c),{get dirty(){return a},check:l}}(h,a,{report:t=>{p.textContent=t??""},save:t=>{const e={circuit_id:o.entities?.power||o.uuid,[a]:t};o.configEntryId&&(e.config_entry_id=o.configEntryId),this._saveThresholds(o,e)}});return this._limitFields.push(f),c.append(u,d,p),c}_saveThresholds(t,e){SI(this._hass).setCircuitThreshold(e).then(()=>this._readThresholds(t,e),t=>kI(this.errorStore,t,"monitoring update"))}_updateLiveState(){if(!this._config||this._config.panelMode)return;const t=this._config;if(!t.subDeviceMode&&!t.favoritesMode){if(t.entities?.switch){const e=this.shadowRoot?.querySelector('[data-role="relay-toggle"]');e&&this._applyRelayToggle(e,t)}if(t.entities?.select){const e=this.shadowRoot?.querySelector('[data-role="shedding-select"]');e&&this._applySheddingSelect(e,t)}}}_applyRelayToggle(t,e){if(!this._hass)return;const n=this._controlAccess;t.disabled=!n.mayOperate||"operable"!==_n(e,this._hass),ke(t,n),yn(e,this._hass)?t.setAttribute("checked",""):t.removeAttribute("checked")}_applySheddingSelect(t,e){if(!this._hass)return;const n=this._controlAccess,i=wn(e,this._hass);x.includes(i)?t.value=i:t.selectedIndex=-1,t.disabled=!n.mayOperate||!function(t,e){const n=xn(t,e);return void 0!==n&&fn.has(n)}(e,this._hass),ke(t,n)}async _readThresholds(t,e){const n=++this._thresholdReads;let i=null;try{i=await this._readMonitoringStatus(t.configEntryId??null)}catch(t){console.warn("SPAN Panel: monitoring status read failed",t)}if(n!==this._thresholdReads)return;const r=Ze(i,t);if(r)return void this._monitoringAnswered(t.uuid,r,i?.global_settings??null);const o={has_override:!0};"number"==typeof e.continuous_threshold_pct&&(o.continuous_threshold_pct=e.continuous_threshold_pct),"number"==typeof e.spike_threshold_pct&&(o.spike_threshold_pct=e.spike_threshold_pct),this._monitoringChanged(t.uuid,o)}async _readMonitoringStatus(t){if(!this._hass)return null;const e=await this._hass.callWS({type:"call_service",domain:l,service:"get_monitoring_status",service_data:t?{config_entry_id:t}:{},return_response:!0});return Ge(e?.response)}_callDomainService(t,e){return this._hass?this._hass.callWS({type:"call_service",domain:l,service:t,service_data:e}):Promise.resolve()}_debounce(t,e,n){this._debounceTimers[t]&&clearTimeout(this._debounceTimers[t]),this._debounceTimers[t]=setTimeout(()=>{delete this._debounceTimers[t],n()},e)}}try{customElements.get("span-side-panel")||customElements.define("span-side-panel",RI)}catch{}class OI extends Nt{constructor(){super(...arguments),this._store=null,this._unsub=null,this._errors=[]}set store(t){if(this._store===t)return;this._unsub?.(),this._unsub=null,this._store=t,this._errors=t.active;const e=t;this._unsub=t.subscribe(()=>{this._errors=e.active})}connectedCallback(){if(super.connectedCallback(),this._store&&!this._unsub){const t=this._store;this._errors=t.active,this._unsub=t.subscribe(()=>{this._errors=t.active})}}disconnectedCallback(){super.disconnectedCallback(),this._unsub?.(),this._unsub=null}render(){return 0===this._errors.length?yt:gt`${this._errors.map(t=>gt` + `,C([Ht({attribute:!1})],bA.prototype,"options",void 0),C([Ht({attribute:!1})],bA.prototype,"data",void 0),C([Ht({type:String})],bA.prototype,"height",void 0);try{customElements.get("span-chart")||customElements.define("span-chart",bA)}catch{}function xA(t,e,n,i,r,a,s,l,c){const{options:u,series:d}=function(t,e,n,i,r,a=!1){n||(n=y[o]);const s=i?"140, 160, 220":"77, 217, 175",l=`rgb(${s})`,c=Date.now(),u=c-e,d=void 0!==n.fixedMin&&void 0!==n.fixedMax,h=(t??[]).filter(t=>t.time>=u).map(t=>[t.time,Math.abs(t.value)]),p=[{type:"line",data:h,showSymbol:!1,smooth:!1,...a?{}:{step:"end"},lineStyle:{width:1.5,color:l},areaStyle:{color:{type:"linear",x:0,y:0,x2:0,y2:1,colorStops:[{offset:0,color:`rgba(${s}, 0.18)`},{offset:1,color:`rgba(${s}, 0.18)`}]}},itemStyle:{color:l}}],f=h.length>0?function(t){let e=0;for(const n of t)n[1]>e&&(e=n[1]);return e}(h):0,g={type:"value",splitNumber:4,axisLabel:{fontSize:10,formatter:f<10?t=>0===t?"0":t.toFixed(1):t=>n.format(t)},splitLine:{lineStyle:{opacity:.15}}};if(d?(g.min=n.fixedMin,g.max=n.fixedMax):f<1&&(g.min=0,g.max=1),r&&"current"===n.entityRole){const t=r.ratingA*r.continuousPct/100,e=r.ratingA*r.spikePct/100;g.min=0,g.max=Math.ceil(1.25*Math.max(t,e,f)),p.push({type:"line",data:[[u,t],[c,t]],showSymbol:!1,lineStyle:{width:1,color:"rgba(255, 200, 40, 0.6)",type:"dashed"},itemStyle:{color:"transparent"},tooltip:{show:!1}}),p.push({type:"line",data:[[u,e],[c,e]],showSymbol:!1,lineStyle:{width:1.5,color:"rgba(255, 60, 60, 0.7)",type:"solid"},itemStyle:{color:"transparent"},tooltip:{show:!1}})}const m={xAxis:{type:"time",min:u,max:c,axisLabel:{fontSize:10},splitLine:{show:!1}},yAxis:g,grid:{top:8,right:4,bottom:0,left:0,containLabel:!0},tooltip:{trigger:"axis",axisPointer:{type:"line",lineStyle:{type:"dashed"}},formatter:t=>{if(!t||0===t.length)return"";const e=t[0],i=new Date(e.value[0]).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}),r=parseFloat(e.value[1].toFixed(2));return`
${i}
${n.format(r)} ${n.unit(r)}
`}},animation:!1};return{options:m,series:p}}(n,i,r,a,l,c),h=s??120;t.style.minHeight=h+"px";let p=t.querySelector("span-chart");p||(p=document.createElement("span-chart"),p.style.display="block",p.style.width="100%",t.innerHTML="",t.appendChild(p));const f=t.clientHeight;p.height=(f>0?f:h)+"px",p.options=u,p.data=d}function wA(t){return null===t?Xt:function(t){return(Math.abs(t)/1e3).toFixed(1)}(t)}function SA(t,e,n,i,r){const o=t.querySelector(".panel-stats");o&&function(t,e,n,i,r){const o="current"===(i.chart_metric||"power"),a=t.querySelector(".stat-consumption .stat-value"),s=t.querySelector(".stat-consumption .stat-unit");if(o){const t=n.panel_entities?.site_power,i=t?e.states[t]:null,r=i?parseFloat(i.attributes?.amperage):NaN;a&&(a.textContent=Number.isFinite(r)?Math.abs(r).toFixed(1):Xt,a.classList.remove("stat-partial")),s&&(s.textContent="A")}else{let t=r;const i=n.panel_entities?.site_power,o=i?e.states[i]:void 0;o&&(t={total:qt(o),partial:!1}),a&&(a.textContent=wA(t?.total??null),a.classList.toggle("stat-partial",t?.partial??!1)),s&&(s.textContent="kW")}const l=t.querySelector(".stat-upstream .stat-value"),c=t.querySelector(".stat-upstream .stat-unit");if(l){const t=n.panel_entities?.current_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;l.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):Xt,c&&(c.textContent="A")}else l.textContent=wA(qt(i)),c&&(c.textContent="kW")}const u=t.querySelector(".stat-downstream .stat-value"),d=t.querySelector(".stat-downstream .stat-unit");if(u){const t=n.panel_entities?.feedthrough_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;u.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):Xt,d&&(d.textContent="A")}else u.textContent=wA(qt(i)),d&&(d.textContent="kW")}const h=t.querySelector(".stat-solar .stat-value"),p=t.querySelector(".stat-solar .stat-unit");if(h){const t=n.panel_entities?.pv_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;h.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):Xt,p&&(p.textContent="A")}else h.textContent=wA(qt(i)),p&&(p.textContent="kW")}const f=t.querySelector(".stat-battery .stat-value");if(f){const t=n.panel_entities?.battery_level,i=qt(t?e.states[t]:void 0);f.textContent=null===i?Xt:`${Math.round(i)}`}const g=t.querySelector(".stat-grid-state .stat-value");if(g){const t=n.panel_entities?.dsm_state,i=t?e.states[t]:null;g.textContent=i?e.formatEntityState?.(i)||i.state:Xt}}(o,e,n,i,r)}function CA(t,e,n,i){const{hass:r,powerHistory:o,horizonMap:a,defaultDurationMs:s,chartMetric:l,monitoringStatus:c}=i,u=cn(n,r),d=hn(n,u),h=ln(n,r),p=t.querySelector(".power-value");p&&(p.innerHTML="current"===l.entityRole?te(un(n,r)):Jt(u)),kn(t,h,_n(n,r),ge(i.topology,e)),t.classList.toggle("circuit-off",!h),t.classList.toggle("circuit-producer",d),In(t,wn(n,r));const f=t.querySelector(".chart-container");if(f){const i=o.get(e)||[],r=t.classList.contains("circuit-col-span")?200:100,u=a?.has(e)?oi(a.get(e)):s,h=dn(n),p=Ze(c,n),g=nn(n,p);xA(f,0,i,u,l,d,r,g?{ratingA:g,...Ke(p)}:void 0,h)}}class kA{get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this._retry=t?new Ue(t):null}constructor(){this._errorStore=null,this._retry=null,this._settings=null,this._lastFetch=0,this._fetching=!1}async fetch(t,e){const n=Date.now();if(this._fetching)return this._settings;if(this._settings&&n-this._lastFetch<3e4)return this._settings;this._fetching=!0;try{const n={};e&&(n.config_entry_id=e);const r={type:"call_service",domain:l,service:"get_graph_settings",service_data:n,return_response:!0},o=this._retry?await this._retry.callWS(t,r,{errorId:"fetch:graph_settings",errorMessage:i("error.graph_settings_failed")}):await t.callWS(r);this._settings=o?.response??null,this._lastFetch=Date.now()}catch(t){console.warn("SPAN Panel: graph settings fetch failed",t),this._settings=null,this._retry||this._errorStore?.add({key:"fetch:graph_settings",level:"warning",message:i("error.graph_settings_failed"),persistent:!1})}finally{this._fetching=!1}return this._settings}invalidate(){this._lastFetch=0}get settings(){return this._settings}clear(){this._settings=null,this._lastFetch=0}}function MA(t,e){if(!t)return a;const n=t.circuits?.[e];return n?.has_override?n.horizon:t.global_horizon??a}function TA(t,e){if(!t)return a;const n=t.sub_devices?.[e];return n?.has_override?n.horizon:t.global_horizon??a}function AA(t,e,n){return{members:t?ze(t):[{uuid:e,circuit:n}],capacityA:t&&t.members.length>1?t.circuit.breaker_rating_a??null:null}}class IA{constructor(){this.powerHistory=new Map,this.horizonMap=new Map,this.subDeviceHorizonMap=new Map,this.monitoringCache=new Xe,this.monitoringMultiCache=new Ye,this.graphSettingsCache=new kA,this._errorStore=null,this._hass=null,this._topology=null,this._config=null,this._configEntryId=null,this._favRefs=null,this._favoritesMonitoringStatus=null,this._perPanelInfo=new Map,this._panelFavorites=null,this._showMonitoring=!1,this._updateInterval=null,this._recorderRefreshInterval=null,this._resizeObserver=null,this._lastWidth=0,this._resizeDebounce=null}get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this.monitoringCache.errorStore=t,this.graphSettingsCache.errorStore=t,this.monitoringMultiCache.errorStore=t}get hass(){return this._hass}set hass(t){this._hass=t}get topology(){return this._topology}get config(){return this._config}set showMonitoring(t){this._showMonitoring=t}init(t,e,n,i){this._topology=t,this._config=e,this._hass=n,this._configEntryId=i}setFavoriteRefs(t){this._favRefs=t}clearFavoriteRefs(){this._favRefs=null,this._favoritesMonitoringStatus=null}get monitoringStatus(){return this._favRefs?this._favoritesMonitoringStatus:this.monitoringCache.status}setPanelFavorites(t){this._panelFavorites=t}setFavoritesPerPanelInfo(t){this._perPanelInfo=t??new Map}get _inFavoritesView(){return null!==this._favRefs}get showFavorites(){return this._inFavoritesView||null!==this._panelFavorites}setConfig(t){this._config=t}buildHorizonMaps(t){if(this.horizonMap.clear(),this.subDeviceHorizonMap.clear(),t&&this._topology?.circuits)for(const e of Object.keys(this._topology.circuits))this.horizonMap.set(e,MA(t,e));if(t&&this._topology?.sub_devices)for(const e of Object.keys(this._topology.sub_devices))this.subDeviceHorizonMap.set(e,TA(t,e))}async fetchAndBuildHorizonMaps(){try{this._favRefs?await this._buildFavoritesHorizonMaps():(await this.graphSettingsCache.fetch(this._hass,this._configEntryId),this.buildHorizonMaps(this.graphSettingsCache.settings))}catch(t){console.warn("SPAN Panel: graph settings fetch failed",t),this.graphSettingsCache.errorStore||this._errorStore?.add({key:"fetch:graph_settings",level:"warning",message:i("error.graph_settings_failed"),persistent:!1})}}async fetchMergedMonitoringStatus(t){if(!this._hass||0===t.length)return null;const e=this._hass,n=function(t){let e=!1;const n={},i={};for(const r of t)r&&(e=!0,r.circuits&&Object.assign(n,r.circuits),r.mains&&Object.assign(i,r.mains));return e?{circuits:n,mains:i}:null}(await Promise.all(t.map(t=>this.monitoringMultiCache.fetchOne(e,t))));return this._favoritesMonitoringStatus=n,n}async _buildFavoritesHorizonMaps(){if(!this._hass||!this._favRefs||!this._topology)return;const t=new Set;for(const e of Object.values(this._favRefs))e.configEntryId&&t.add(e.configEntryId);const e=new Map;await Promise.all(Array.from(t).map(async t=>{e.set(t,await this._fetchGraphSettingsFresh(t))})),this.horizonMap.clear(),this.subDeviceHorizonMap.clear();for(const t of Object.keys(this._topology.circuits)){const n=this._favRefs[t],i=n?.configEntryId?e.get(n.configEntryId)??null:null,r=n?.targetId??t;this.horizonMap.set(t,MA(i,r))}if(this._topology.sub_devices)for(const t of Object.keys(this._topology.sub_devices)){const n=this._favRefs[t],i=n?.configEntryId?e.get(n.configEntryId)??null:null,r=n?.targetId??t;this.subDeviceHorizonMap.set(t,TA(i,r))}}async loadHistory(){await fi(this._hass,this._topology,this._config,this.powerHistory,this.horizonMap,this.subDeviceHorizonMap)}recordSamples(){if(!this._topology||!this._hass||!this._config)return;const t=Date.now();for(const[e,n]of Object.entries(this._topology.circuits)){const i=this.horizonMap.get(e)??a;if(!s[i]?.useRealtime)continue;const r=Oe(n,this._config);if(!r)continue;const o=qt(this._hass.states[r]);if(null===o)continue;const l=oi(i),c=ai(l),u=si(l),d=t-l,h=this.powerHistory.get(e)??[];h.length>0&&t-h[h.length-1].time0&&t-h[h.length-1].time0&&this._topology)for(const{key:t,devId:e}of pi(this._topology))n.has(e)&&r.add(t);const o=new Map;try{await fi(this._hass,this._topology,this._config,o,e,n);for(const t of e.keys()){const e=o.get(t);e?this.powerHistory.set(t,e):this.powerHistory.delete(t)}for(const t of r){const e=o.get(t);e?this.powerHistory.set(t,e):this.powerHistory.delete(t)}this.updateDOM(t)}catch(t){console.warn("SPAN Panel: history refresh failed",t),this._errorStore?.add({key:"fetch:history",level:"warning",message:i("error.history_failed"),persistent:!1})}}updateDOM(t){this._hass&&this._topology&&this._config&&(function(t,e,n,i,r,o,a){if(!t||!n||!e)return;const s=ri(i),l=Fe(n),c=[];for(const{circuit:t}of l){if(!t.entities?.power||dn(t)||Ie(t))continue;const n=cn(t,e);c.push(null===n?null:Math.abs(n))}SA(t,e,n,i,function(t){let e=null,n=!1;for(const i of t)null===i?n=!0:e=null===e?i:e+i;return{total:e,partial:n&&null!==e}}(c));const u={hass:e,topology:n,powerHistory:r,horizonMap:o,defaultDurationMs:s,chartMetric:Re(i),monitoringStatus:a};for(const e of l)for(const n of ze(e)){const i=t.querySelector(`.circuit-slot[data-uuid="${Ln(n.uuid)}"]`);if(!i)continue;const r=n.uuid===e.uuid?e.circuit:Be(n.circuit,e);CA(i,n.uuid,r,u)}}(t,this._hass,this._topology,this._config,this.powerHistory,this.horizonMap,this.monitoringStatus),function(t,e,n,i,r,o){if(!n.sub_devices)return;const a=ri(i);for(const[i,s]of Object.entries(n.sub_devices)){const n=t.querySelector(`[data-subdev="${Ln(i)}"]`);if(!n)continue;const l=Wn(s);if(l.headlineEid){const t=n.querySelector(".sub-power-value");t&&(t.innerHTML=Qt(Un(e,l.headlineEid)))}if(l.siteTotalEid){const t=Un(e,l.siteTotalEid),i=n.querySelector(".sub-site-total-value");i&&(i.innerHTML=Qt(t));const r=i?.closest(".sub-entity");r&&(r.hidden=null===t)}const c=n.querySelectorAll("[data-chart-key]");for(const t of c){const e=t.dataset.chartKey;if(!e)continue;const n=r.get(e)||[];let s=_.power;e.endsWith("_soc")?s=_.soc:e.endsWith("_soe")&&(s=_.soe);const l=!!t.closest(".bess-chart-col");xA(t,0,n,o?.has(i)?oi(o.get(i)):a,s,!1,l?120:150,void 0,e.endsWith("_soc")||e.endsWith("_soe"))}for(const t of Object.keys(s.entities||{})){const i=n.querySelector(`[data-eid="${Ln(t)}"]`);if(!i)continue;const r=e.states[t];if(r){let t;if(e.formatEntityState)t=e.formatEntityState(r);else{t=r.state;const e=r.attributes.unit_of_measurement||"";e&&(t+=" "+e)}if("Wh"===(r.attributes.unit_of_measurement||"")){const e=qt(r);null!==e&&(t=(e/1e3).toFixed(1)+" kWh")}i.textContent=t}}}}(t,this._hass,this._topology,this._config,this.powerHistory,this.subDeviceHorizonMap),function(t,e,n,i){for(const[r,o]of En(n)){const n=t.querySelector(`.meter-tile[data-meter-uuid="${Ln(r)}"] .meter-readings`);n&&(n.innerHTML=On(o,e,i))}}(t,this._hass,this._topology,this._config))}async onGraphSettingsChanged(t){if(this._hass){this._favRefs?await this._buildFavoritesHorizonMaps():(this.graphSettingsCache.invalidate(),await this.graphSettingsCache.fetch(this._hass,this._configEntryId),this.buildHorizonMaps(this.graphSettingsCache.settings)),this.powerHistory.clear();try{await this.loadHistory()}catch{}this.updateDOM(t)}}onToggleClick(t,e){const n=t.target,i=n?.closest(".toggle-pill");if(!i)return;const r=e.querySelector(".slide-confirm");if(!r||!r.classList.contains("confirmed"))return;t.stopPropagation(),t.preventDefault();const o=i.closest("[data-uuid]");if(!o||!this._topology||!this._hass)return;const a=o.dataset.uuid;if(!a)return;const s=this._topology.circuits[a];if(!s)return;const l=s.entities?.switch;if(!l)return;if("operable"!==_n(s,this._hass))return;const c=ge(this._topology,a);if(!c.mayOperate)return void this._errorStore?.add({key:"service:relay",level:"warning",message:_e(c),persistent:!1});const u=this._hass;xe(u,c).setRelay(l,"on"!==u.states[l]?.state).catch(t=>Ce(u,this._errorStore,t,"relay"))}async onGearClick(t,e){const n=t.target,i=n?.closest(".gear-icon");if(!i)return;const r=e.querySelector("span-side-panel");if(!r||!this._hass)return;if(r.hass=this._hass,r.errorStore=this.errorStore,i.classList.contains("panel-gear")){if(this._inFavoritesView){const t=await this._buildFavoritesSections();if(0===t.length)return;return void r.open({favoritesMode:!0,perPanelSections:t})}if(!this._topology)return;return await this.graphSettingsCache.fetch(this._hass,this._configEntryId),void r.open({panelMode:!0,topology:this._topology,graphSettings:this.graphSettingsCache.settings,showFavorites:null!==this._panelFavorites,favoritePanelDeviceId:this._panelFavorites?.panelDeviceId,favoriteCircuitUuids:this._panelFavorites?.circuitUuids,favoriteSubDeviceIds:this._panelFavorites?.subDeviceIds,configEntryId:this._configEntryId})}const o=i.dataset.uuid;if(o&&this._topology){const t=this._topology.circuits[o];if(t){const e=this._favRefs?.[o]??null,n=e&&"circuit"===e.kind?e.targetId:o,i=e?.configEntryId??this._configEntryId;let s,l;e?[s,l]=await Promise.all([this._fetchGraphSettingsFresh(i),this._fetchMonitoringStatusFresh(i)]):(await Promise.all([this.graphSettingsCache.fetch(this._hass,i),this.monitoringCache.fetch(this._hass,i)]),s=this.graphSettingsCache.settings,l=this.monitoringCache.status);const c=Ze(l,t),u=s?.global_horizon??a,d=s?.circuits?.[n],h=d?{...d,globalHorizon:u}:{horizon:u,has_override:!1,globalHorizon:u},p=e?.panelDeviceId??this._panelFavorites?.panelDeviceId,f=null!==e||(this._panelFavorites?.circuitUuids.has(n)??!1),g=this._sidePanelSlot(o,e),m=e?this._perPanelInfo.get(e.panelDeviceId)?.topology:this._topology,v={uuid:n,name:t.name,entities:t.entities,...AA(g,n,t),is_user_controllable:t.is_user_controllable,always_on:t.always_on,relay_state:t.relay_state,priority:t.priority,device_type:t.device_type,monitoringInfo:c,monitoringGlobals:l?.global_settings??null,showMonitoring:this._showMonitoring,monitoringRatingOffered:!0===m?.monitoring_rating_offered,graphHorizonInfo:h,showFavorites:this.showFavorites,favoritePanelDeviceId:p,isFavorite:f,configEntryId:i,controlAccess:ge(this._topology,o)};return void r.open(v)}}const s=i.dataset.subdevId;if(s&&this._topology?.sub_devices?.[s]){const t=this._topology.sub_devices[s],e=this._favRefs?.[s]??null,n=e&&"sub_device"===e.kind?e.targetId:s,i=e?.configEntryId??this._configEntryId;let o;e?o=await this._fetchGraphSettingsFresh(i):(await this.graphSettingsCache.fetch(this._hass,i),o=this.graphSettingsCache.settings);const l=o?.global_horizon??a,c=o?.sub_devices?.[n],u=c?{...c,globalHorizon:l}:{horizon:l,has_override:!1,globalHorizon:l},d=e?.panelDeviceId??this._panelFavorites?.panelDeviceId,h=null!==e||(this._panelFavorites?.subDeviceIds.has(n)??!1);r.open({subDeviceMode:!0,subDeviceId:n,name:t.name??n,deviceType:t.type??"",entities:t.entities,hasChart:qn(t).length>0,graphHorizonInfo:u,showFavorites:this.showFavorites,favoritePanelDeviceId:d,isFavorite:h,configEntryId:i})}}_sidePanelSlot(t,e){const n="circuit"===e?.kind?this._perPanelInfo.get(e.panelDeviceId)?.topology:void 0;return n&&e?He(Fe(n)).get(e.targetId):this._topology?He(Fe(this._topology)).get(t):void 0}async refreshCircuitSidePanel(t,e,n,i=null){const r=t.querySelector("span-side-panel"),o=r?.openCircuit;if(!r||!o||o.configEntryId!==e)return;const a=n.circuits[o.uuid];if(!a)return;const s=He(Fe(n)).get(o.uuid);if(i&&!(s?.memberIds??[o.uuid]).some(t=>i.has(t)))return;const l=await this._fetchMonitoringStatusFresh(e);if(r.openCircuit?.uuid!==o.uuid)return;const c=Ze(l,a);r.refreshRating({...AA(s,o.uuid,a),monitoringInfo:c,monitoringGlobals:l?.global_settings??null})}refreshCircuitControlAccess(t,e,n){const i=t.querySelector("span-side-panel"),r=i?.openCircuit;i&&r&&r.configEntryId===e&&i.refreshControlAccess(pe(n))}async _buildFavoritesSections(){if(!this._hass||!this._favRefs)return[];const t=function(t,e){const n=new Map;for(const i of Object.values(t)){if("circuit"!==i.kind)continue;const t=e.get(i.panelDeviceId);if(void 0===t)continue;let r=n.get(i.panelDeviceId);void 0===r&&(r={panelDeviceId:i.panelDeviceId,panelName:t.panelName,topology:t.topology,configEntryId:t.configEntryId,favoriteCircuitUuids:new Set},n.set(i.panelDeviceId,r)),r.favoriteCircuitUuids.add(i.targetId)}return Array.from(n.values()).sort((t,e)=>t.panelName.localeCompare(e.panelName))}(this._favRefs,this._perPanelInfo);if(0===t.length)return[];return await Promise.all(t.map(async t=>({panelDeviceId:t.panelDeviceId,panelName:t.panelName,topology:t.topology,graphSettings:await this._fetchGraphSettingsFresh(t.configEntryId),favoriteCircuitUuids:t.favoriteCircuitUuids,configEntryId:t.configEntryId})))}async _fetchGraphSettingsFresh(t){if(!this._hass)return null;try{const e={};t&&(e.config_entry_id=t);const n={type:"call_service",domain:l,service:"get_graph_settings",service_data:e,return_response:!0},r=this._errorStore?new Ue(this._errorStore):null,o=r?await r.callWS(this._hass,n,{errorId:"fetch:graph_settings",errorMessage:i("error.graph_settings_failed")}):await this._hass.callWS(n);return o?.response??null}catch(t){return console.warn("SPAN Panel: fresh graph settings fetch failed",t),null}}async _fetchMonitoringStatusFresh(t){if(!this._hass)return null;try{const e={};t&&(e.config_entry_id=t);const n={type:"call_service",domain:l,service:"get_monitoring_status",service_data:e,return_response:!0},r=this._errorStore?new Ue(this._errorStore):null,o=r?await r.callWS(this._hass,n,{errorId:"fetch:monitoring",errorMessage:i("error.monitoring_failed")}):await this._hass.callWS(n);return Ge(o?.response)}catch(t){return console.warn("SPAN Panel: fresh monitoring status fetch failed",t),null}}bindSlideConfirm(t,e){if(t.classList.contains("slide-confirm-forbidden"))return;const n=t.querySelector(".slide-confirm-knob"),i=t.querySelector(".slide-confirm-text");if(!n||!i)return;let r=!1,o=0,a=0;const s=e=>{t.classList.contains("confirmed")||(r=!0,o=e-n.offsetLeft,a=t.offsetWidth-n.offsetWidth-4,n.classList.remove("snapping"))},l=t=>{if(!r)return;const e=Math.max(2,Math.min(t-o,a));n.style.left=e+"px"},c=()=>{if(!r)return;r=!1;(n.offsetLeft-2)/a>=.9?(n.style.left=a+"px",t.classList.add("confirmed"),n.querySelector("span-icon")?.setAttribute("icon","mdi:lock-open"),i.textContent=t.dataset.textOn??"",e&&e.classList.remove("switches-disabled")):(n.classList.add("snapping"),n.style.left="2px")};n.addEventListener("mousedown",t=>{t.preventDefault(),s(t.clientX)}),t.addEventListener("mousemove",t=>l(t.clientX)),t.addEventListener("mouseup",c),t.addEventListener("mouseleave",c),n.addEventListener("touchstart",t=>{t.preventDefault(),s(t.touches[0].clientX)},{passive:!1}),t.addEventListener("touchmove",t=>l(t.touches[0].clientX),{passive:!0}),t.addEventListener("touchend",c),t.addEventListener("touchcancel",c),t.addEventListener("click",()=>{t.classList.contains("confirmed")&&(t.classList.remove("confirmed"),n.classList.add("snapping"),n.style.left="2px",n.querySelector("span-icon")?.setAttribute("icon","mdi:lock"),i.textContent=t.dataset.textOff??"",e&&e.classList.add("switches-disabled"))})}startIntervals(t,e){this._updateInterval=setInterval(()=>{this.recordSamples(),this.updateDOM(t),e&&e()},1e3),this._recorderRefreshInterval=setInterval(()=>{this.refreshRecorderData(t)},3e4)}stopIntervals(){this._updateInterval&&(clearInterval(this._updateInterval),this._updateInterval=null),this._recorderRefreshInterval&&(clearInterval(this._recorderRefreshInterval),this._recorderRefreshInterval=null),this.cleanupResizeObserver()}setupResizeObserver(t,e){this.cleanupResizeObserver(),e&&(this._lastWidth=e.clientWidth,this._resizeObserver=new ResizeObserver(e=>{const n=e[0];if(!n)return;const i=n.contentRect.width;Math.abs(i-this._lastWidth)<5||(this._lastWidth=i,this._resizeDebounce&&clearTimeout(this._resizeDebounce),this._resizeDebounce=setTimeout(()=>{for(const e of t.querySelectorAll(".chart-container")){const t=e.querySelector("span-chart");t&&t.remove()}this.updateDOM(t)},150))}),this._resizeObserver.observe(e))}cleanupResizeObserver(){this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),this._resizeDebounce&&(clearTimeout(this._resizeDebounce),this._resizeDebounce=null)}reset(){this.powerHistory.clear(),this.horizonMap.clear(),this.subDeviceHorizonMap.clear(),this.monitoringCache.clear(),this.monitoringMultiCache.clear(),this.graphSettingsCache.clear()}}function DA(t=""){const e=t?` value="${jt(t)}"`:"",n=t?"":"display:none;";return`\n
\n \n \n
\n `}function PA(t,e,n,r,o,a,s,l,c){const u=ln(e,n),d=_n(e,n),h=Ve([e]),p=jt(e.name||i("grid.unknown")),f="current"===Re(r).entityRole;let g;g=u?f?te(un(e,n)):Jt(cn(e,n)):"";const m=An(a||"unknown");let v="";const y=pn(l,n,o);null!==y&&(v=`${Math.round(y)}%`);const _=``,b=Ie(e)?"":"none"===d?`${u?"ON":"OFF"}`:Cn(u,d,c);return`\n
\n ${h?`${h}`:""}\n ${v}\n ${p}\n ${m}\n ${b}\n \n ${g}\n \n ${_}\n \n
\n `}function LA(t,e,n,i,r){const o=hn(e,cn(e,n)),a=sn(0,r,ln(e,n),o),s=jt(t);return`\n
\n
\n
\n
\n
\n `}function EA(t){return`
${jt(t)}
`}function NA(t,e){const n=e.hysteresisPx??48,i=new WeakSet;let r=null;const o=t=>{const n=t.querySelector(e.nameSelector);return!!n&&(0!==t.clientWidth&&(n.clientWidth<1||n.scrollWidth>n.clientWidth+1))},a=()=>{const i=t.querySelectorAll(e.rowSelector);if(0===i.length)return;const a=i[0].clientWidth;if(0===a)return;if(null!==r){if(a>r+n){for(const t of i)t.classList.remove(e.foldClass);r=null}else for(const t of i)t.classList.add(e.foldClass);return}let s=!1;for(const t of i)if(o(t)){s=!0;break}if(s){for(const t of i)t.classList.add(e.foldClass);r=a}},s=new ResizeObserver(()=>a()),l=()=>{const n=t.querySelectorAll(e.rowSelector);for(const t of n)i.has(t)||(i.add(t),s.observe(t));requestAnimationFrame(()=>a())};l();const c=new MutationObserver(t=>{(t=>{const n=t=>{for(const n of t)if(n instanceof Element){if(n.matches(e.rowSelector))return!0;if(n.querySelector(e.rowSelector))return!0}return!1};for(const e of t)if(n(e.addedNodes)||n(e.removedNodes))return!0;return!1})(t)&&l()});return c.observe(t,{childList:!0,subtree:!0}),()=>{s.disconnect(),c.disconnect()}}function RA(t,e,n){return{isOn:ln(t,e),value:"current"===(n.chart_metric||"power")?un(t,e):cn(t,e)}}function OA(t,e,n,i){const r=RA(t,n,i),o=RA(e,n,i);return r.isOn&&!o.isOn?-1:!r.isOn&&o.isOn?1:null===r.value||null===o.value?r.value===o.value?0:null===r.value?1:-1:Math.abs(o.value)-Math.abs(r.value)}function zA(t,e,n){return t.sort((t,i)=>OA(t[1],i[1],e,n))}class HA{constructor(t){this._expandedUuids=new Set,this._searchQuery="",this._container=null,this._clickHandler=null,this._inputHandler=null,this._graphSettingsHandler=null,this._hass=null,this._topology=null,this._config=null,this._monitoringStatus=null,this._viewName=null,this._columns=1,this._foldUnobserve=null,this._ctrl=t}setColumns(t){const e=Math.max(1,Math.min(3,Math.floor(t)));this._columns=e}setInitialExpansion(t){this._expandedUuids=new Set(t)}setInitialSearchQuery(t){this._searchQuery=t}setViewName(t){this._viewName=t}renderActivityView(t,e,n,i,r,o){this._unbindEvents(),this._hass=e,this._topology=n,this._config=i,this._monitoringStatus=r;const a=zA(Object.entries(n.circuits),e,i),s=He(Fe(n));let l=o+DA(this._searchQuery);l+=`
`;for(const[t,o]of a){const a=Ze(r,o),c=wn(o,e),u=this._expandedUuids.has(t);l+=`
`,l+=PA(t,o,e,i,a,c,u,Be(o,s.get(t)),ge(n,t)),u&&(l+=LA(t,o,e,0,a)),l+="
"}l+="
",l+="",t.innerHTML=l;const c=t.querySelector("span-side-panel");c&&(c.hass=e,c.errorStore=this._ctrl.errorStore),this._bindEvents(t),this._searchQuery&&this._applyFilter(t),this._ctrl.updateDOM(t),this._attachFoldObserver(t)}renderAreaView(t,e,n,r,o,a){this._unbindEvents(),this._hass=e,this._topology=n,this._config=r,this._monitoringStatus=o;const s=i("list.unassigned_area"),l=He(Fe(n)),c=new Map;for(const[t,e]of Object.entries(n.circuits)){const n=e.area??s,i=c.get(n);i?i.push([t,e]):c.set(n,[[t,e]])}const u=[...c.keys()].sort((t,e)=>t===s?1:e===s?-1:t.localeCompare(e));let d=a+DA(this._searchQuery);d+=`
`;for(const t of u){const i=c.get(t);if(!i)continue;const a=zA(i,e,r);d+=EA(t);for(const[t,i]of a){const a=Ze(o,i),s=wn(i,e),c=this._expandedUuids.has(t);d+=`
`,d+=PA(t,i,e,r,a,s,c,Be(i,l.get(t)),ge(n,t)),c&&(d+=LA(t,i,e,0,a)),d+="
"}}d+="
",d+="",t.innerHTML=d;const h=t.querySelector("span-side-panel");h&&(h.hass=e,h.errorStore=this._ctrl.errorStore),this._bindEvents(t),this._searchQuery&&this._applyFilter(t),this._ctrl.updateDOM(t),this._attachFoldObserver(t)}updateCollapsedRows(t,e,n,i){const r="current"===Re(i).entityRole,o=t.querySelectorAll(".list-row[data-row-uuid]");for(const t of o){const o=t.dataset.rowUuid;if(!o)continue;const a=n.circuits[o];if(!a)continue;const{isOn:s,value:l}=RA(a,e,i),c=t.querySelector(".list-power-value");c&&(c.innerHTML=s?r?te(l):Jt(l):""),kn(t,s,_n(a,e),ge(n,o)),In(t,wn(a,e));const u=t.querySelector(".list-status-badge");u&&(u.textContent=s?"ON":"OFF",u.classList.toggle("list-status-on",s),u.classList.toggle("list-status-off",!s)),t.classList.toggle("circuit-off",!s)}!function(t,e,n,i){const r=t.querySelector(".list-view");if(r)for(const t of function(t,e){let n={anchor:null,units:[]};const i=[n];for(const r of[...t.children])if(r.classList.contains("area-header"))n={anchor:r,units:[]},i.push(n);else if(r.classList.contains("list-cell")){const t=r.dataset.cellUuid,i=t?e.circuits[t]:void 0;t&&i&&n.units.push({cell:r,uuid:t,circuit:i})}return i}(r,n)){if(t.units.length<2)continue;const n=[...t.units].sort((t,n)=>OA(t.circuit,n.circuit,e,i));if(!n.some((e,n)=>e.uuid!==t.units[n].uuid))continue;let o=t.anchor;for(const t of n)o?o.after(t.cell):r.prepend(t.cell),o=t.cell}}(t,e,n,i)}stop(){this._unbindEvents(),null===this._viewName&&(this._expandedUuids.clear(),this._searchQuery=""),this._hass=null,this._topology=null,this._config=null,this._monitoringStatus=null}_dispatchFavoritesViewState(){if(!this._viewName||!this._container)return;const t={view:this._viewName,expanded:[...this._expandedUuids],searchQuery:this._searchQuery};this._container.dispatchEvent(new CustomEvent("favorites-view-state-changed",{detail:t,bubbles:!0,composed:!0}))}_bindEvents(t){this._container=t,this._clickHandler=e=>{const n=e.target;if(!n)return;const i=n.closest(".list-expand-toggle");if(i){const t=i.dataset.expandUuid;return void(t&&this._toggleExpand(t))}if(n.closest(".gear-icon"))return void this._ctrl.onGearClick(e,t);if(n.closest(".toggle-pill"))return void this._ctrl.onToggleClick(e,t);if(n.closest(".list-search-clear")){const e=t.querySelector(".list-search");return void(e&&(e.value="",e.dispatchEvent(new Event("input",{bubbles:!0}))))}const r=n.closest(".unit-btn");if(r){const e=r.dataset.unit;e&&t.dispatchEvent(new CustomEvent("unit-changed",{detail:e,bubbles:!0,composed:!0}))}},this._inputHandler=e=>{const n=e.target;n&&n.classList.contains("list-search")&&(this._searchQuery=n.value.toLowerCase(),this._applyFilter(t),this._dispatchFavoritesViewState())},this._graphSettingsHandler=()=>{this._ctrl.onGraphSettingsChanged(t).then(()=>{this._ctrl.updateDOM(t)}).catch(()=>{})},t.addEventListener("click",this._clickHandler),t.addEventListener("input",this._inputHandler),t.addEventListener("graph-settings-changed",this._graphSettingsHandler);const e=t.querySelector(".slide-confirm");e&&(this._ctrl.bindSlideConfirm(e,t),t.classList.add("switches-disabled"))}_unbindEvents(){this._container&&(this._clickHandler&&this._container.removeEventListener("click",this._clickHandler),this._inputHandler&&this._container.removeEventListener("input",this._inputHandler),this._graphSettingsHandler&&this._container.removeEventListener("graph-settings-changed",this._graphSettingsHandler)),this._foldUnobserve&&(this._foldUnobserve(),this._foldUnobserve=null),this._container=null,this._clickHandler=null,this._inputHandler=null,this._graphSettingsHandler=null}_attachFoldObserver(t){this._foldUnobserve&&(this._foldUnobserve(),this._foldUnobserve=null),this._foldUnobserve=NA(t,{rowSelector:".list-row",nameSelector:".list-circuit-name",foldClass:"is-folded"})}_applyFilter(t){const e=t.querySelector(".list-search-clear");e&&(e.style.display=this._searchQuery?"":"none");const n=t.querySelectorAll(".list-cell[data-cell-uuid]");for(const t of n){const e=t.querySelector(".list-circuit-name"),n=(e?.textContent?.toLowerCase()??"").includes(this._searchQuery);t.style.display=n?"":"none"}const i=t.querySelectorAll(".area-header");for(const t of i){let e=!1,n=t.nextElementSibling;for(;n&&!n.classList.contains("area-header");){if(n.classList.contains("list-cell")&&"none"!==n.style.display){e=!0;break}n=n.nextElementSibling}t.style.display=e?"":"none"}}_toggleExpand(t){if(!(this._container&&this._hass&&this._topology&&this._config))return;const e=Ln(t),n=this._container.querySelector(`.list-cell[data-cell-uuid="${e}"]`);if(!n)return;const i=n.querySelector(`.list-row[data-row-uuid="${e}"]`),r=n.querySelector(`.list-expand-toggle[data-expand-uuid="${e}"]`);if(i){if(this._expandedUuids.has(t)){this._expandedUuids.delete(t);const o=n.querySelector(`.list-expanded-content[data-expanded-uuid="${e}"]`);o&&o.remove(),r&&r.classList.remove("expanded"),i.classList.remove("list-row-expanded")}else{this._expandedUuids.add(t);const e=this._topology.circuits[t];if(!e)return;const n=Ze(this._monitoringStatus,e),o=LA(t,e,this._hass,this._config,n);i.insertAdjacentHTML("afterend",o),r&&r.classList.add("expanded"),i.classList.add("list-row-expanded"),this._ctrl.updateDOM(this._container)}this._dispatchFavoritesViewState()}}}const BA=["entity_registry_updated","area_registry_updated","device_registry_updated"];async function FA(t,e){const[n,i,r]=await Promise.all([t.callWS({type:"config/area_registry/list"}),t.callWS({type:"config/entity_registry/list"}),t.callWS({type:"config/device_registry/list"})]),o=new Map;for(const t of n)o.set(t.area_id,t.name);const a=new Map,s=new Map;for(const t of i)t.area_id&&a.set(t.entity_id,t.area_id),t.device_id&&s.set(t.entity_id,t.device_id);const l=new Map;for(const t of r)t.area_id&&l.set(t.id,t.area_id);const c=e.panel_device_id??e.device_id,u=t=>t?l.get(t):void 0;for(const t of Object.values(e.circuits)){const e=Object.values(t.entities).filter(t=>!!t),n=[u(t.device_id),...e.map(t=>a.get(t)),...e.map(t=>u(s.get(t))),u(c)];t.area=n.map(t=>t?o.get(t):void 0).find(t=>!!t)}}const $A=["name","name_by_user"];async function VA(t,e,n){const i=t.connection;return i?i.subscribeEvents(t=>{const i=function(t){if("object"!=typeof t||null===t||!("data"in t))return null;const{data:e}=t;if("object"!=typeof e||null===e)return null;if(!("action"in e)||"update"!==e.action)return null;if(!("device_id"in e)||"string"!=typeof e.device_id)return null;if(!("changes"in e))return null;const{changes:n}=e;return"object"!=typeof n||null===n?null:$A.some(t=>t in n)?e.device_id:null}(t),r=i?e():null;i&&r&&function(t,e){return(t.panel_device_id??t.device_id)===e||!!Object.keys(t.sub_devices??{}).includes(e)||Object.values(t.circuits).some(t=>t.device_id===e)}(r,i)&&n()},"device_registry_updated"):()=>{}}const WA="loaded";async function jA(t,e,n,{initialIsReseed:i}){const r=t.connection;if(!r)return async()=>{};const o=new Map;let a=!1;return r.subscribeMessage(t=>{if(t.every(t=>null===t.type)){const r=a||i;a=!0,o.clear();for(const{entry:i}of t)e(i)&&(o.set(i.entry_id,i.state),r&&i.state===WA&&n(i.entry_id));return}for(const{type:i,entry:r}of t){if(!e(r))continue;if("removed"===i){o.delete(r.entry_id);continue}const t=o.get(r.entry_id);o.set(r.entry_id,r.state),"updated"===i&&r.state===WA&&t!==WA&&n(r.entry_id)}},{type:"config_entries/subscribe",type_filter:["device"]})}function qA(t){if("object"!=typeof t||null===t||!("data"in t))return null;const{data:e}=t;return"object"==typeof e&&null!==e?e:null}async function UA(t,e,n){const i=t.connection;return i?i.subscribeEvents(t=>{(function(t){const e=qA(t);return e&&"config_entry_id"in e&&"string"==typeof e.config_entry_id?e.config_entry_id:null})(t)===e&&n(function(t){const e=qA(t);if(!e||!("circuit_ids"in e)||!Array.isArray(e.circuit_ids))return null;const n=e.circuit_ids;return n.every(t=>"string"==typeof t)?new Set(n):null}(t))},"span_panel_package_ratings_changed"):()=>{}}function GA(t){let e=null,n=!1;return async function i(){if(e)return n=!0,void await e.catch(()=>{});const r=(async()=>{try{await t()}finally{e=null,n&&(n=!1,await i())}})();e=r,await r}}function XA(){let t=0;return()=>{t+=1;const e=t;return()=>t!==e}}class YA{constructor(){this._persistent=new Map,this._transient=null,this._transientTimer=null,this._subscribers=new Set,this._watchedPanels=new Map}add(t){const e={...t,timestamp:Date.now()};if(e.persistent)this._persistent.set(e.key,e);else{this._clearTransient(),this._transient=e;const t=e.ttl??5e3;this._transientTimer=setTimeout(()=>{this._transient=null,this._transientTimer=null,this._notify()},t)}this._notify()}remove(t){if(this._persistent.has(t))return this._persistent.delete(t),void this._notify();this._transient?.key===t&&(this._clearTransient(),this._notify())}clear(t){void 0===t?(this._persistent.clear(),this._clearTransient(),this._watchedPanels.clear()):!0===t.persistent?this._persistent.clear():!1===t.persistent&&this._clearTransient(),this._notify()}get active(){const t=[...this._persistent.values()];return null!==this._transient&&t.push(this._transient),t}hasPersistent(t){return this._persistent.has(t)}hasAnyPanelOffline(){for(const t of this._persistent.keys())if("panel-offline"===t||t.startsWith("panel-offline:"))return!0;return!1}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}watchPanelStatus(t){this.watchPanelStatuses([{entityId:t,panelName:null}])}watchPanelStatuses(t){const e=this._watchedPanels,n=new Map;for(const i of t){const t=e.get(i.entityId);n.set(i.entityId,{panelName:i.panelName??null,wasOffline:t?.wasOffline??!1})}const i=this._isSingleUnnamed(e),r=this._isSingleUnnamed(n);for(const t of e.keys()){n.has(t)&&i===r||this._persistent.delete(this._offlineKey(t,i))}this._watchedPanels=n,this._notify()}clearPanelStatusWatch(){if(0===this._watchedPanels.size)return;const t=this._isSingleUnnamed(this._watchedPanels);for(const e of this._watchedPanels.keys())this._persistent.delete(this._offlineKey(e,t));this._watchedPanels.clear(),this._notify()}updateHass(t){if(0===this._watchedPanels.size)return;const e=this._isSingleUnnamed(this._watchedPanels);for(const[n,o]of this._watchedPanels){const a=t.states[n]?.state,s="on"===a,l=this._offlineKey(n,e),c=this._reconnectKey(n,e);if(s){const t=o.wasOffline;o.wasOffline=!1,this.remove(l),t&&this.add({key:c,level:"info",message:null===o.panelName?i("error.panel_reconnected"):r("error.panel_reconnected_named",{name:o.panelName}),persistent:!1})}else o.wasOffline=!0,this.hasPersistent(l)||this.add({key:l,level:"error",message:null===o.panelName?i("error.panel_offline"):r("error.panel_offline_named",{name:o.panelName}),persistent:!0})}}dispose(){this._clearTransient(),this._persistent.clear(),this._subscribers.clear(),this._watchedPanels.clear()}_isSingleUnnamed(t){if(1!==t.size)return!1;for(const e of t.values())return null===e.panelName;return!1}_offlineKey(t,e){return e?"panel-offline":`panel-offline:${t}`}_reconnectKey(t,e){return e?"panel-reconnected":`panel-reconnected:${t}`}_clearTransient(){null!==this._transientTimer&&(clearTimeout(this._transientTimer),this._transientTimer=null),this._transient=null}_notify(){for(const t of this._subscribers)try{t()}catch(t){console.warn("SPAN Panel: error-store subscriber threw",t)}}}async function ZA(t,e,n){if(!e)throw new Error(i("card.device_not_found"));const r={type:`${l}/panel_topology`,device_id:e},o=n?await n.callWS(t,r,{errorId:"fetch:topology"}):await t.callWS(r),a=Ae(o.panel_size)?o.panel_size:function(t){let e=0;for(const n of Object.values(t))if(n&&!Ie(n))for(const t of n.tabs)t>e&&(e=t);return e>0?e+e%2:0}(o.circuits);if(!De(o,a))throw new Error(i("card.topology_error"));const s={type:"config/device_registry/list"},c=n?await n.callWS(t,s,{errorId:"fetch:topology"}):await t.callWS(s);return function(t,e){const n=new Map(e.map(t=>[t.id,t]));for(const e of Object.values(t)){const t=e.device_id?n.get(e.device_id):void 0,i=t?Kn(t):"";i&&(e.name=i)}}(o.circuits,c),await FA(t,o),{topology:o,panelSize:a}}const KA=new Set(["not_loaded","no_data","unknown_command"]);function QA(t){return!!function(t){if(3===t)return!0;if("object"!=typeof t||null===t||!("error"in t))return!1;const{error:e}=t;return"object"==typeof e&&null!==e&&"code"in e&&3===e.code}(t)||"object"==typeof t&&null!==t&&"code"in t&&KA.has(t.code)}async function JA(t,e,n){const i=await async function(t,e){try{const n=await t.callWS({type:"config/device_registry/list"});return n.find(t=>t.id===e)?.config_entry_id??null}catch(t){return console.warn("SPAN Panel: device registry list failed; waiting for any SPAN Panel entry to load:",ee(t)),null}}(t,e);return jA(t,t=>null===i?t.domain===l:t.entry_id===i,()=>n(),{initialIsReseed:!0})}function tI(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function eI(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((t,n)=>eI(t,e[n]));if(!tI(t)||!tI(e))return!1;const n=Object.keys(t).filter(e=>void 0!==t[e]),i=Object.keys(e).filter(t=>void 0!==e[t]);return n.length===i.length&&n.every(n=>eI(t[n],e[n]))}function nI(t){const e={...t};for(const t of le)delete e[t];return e}function iI(t){const e=Object.fromEntries(Object.entries(t.circuits).map(([t,e])=>[t,nI(e)]));return{...t,circuits:e}}function rI(t){const e=t.getRootNode();return e instanceof Document||e instanceof ShadowRoot?e.activeElement:null}function oI(t){return null!==t&&rI(t)===t}function aI(t){if(!t)return!1;const e=rI(t);return null!==e&&t.contains(e)}function sI(t){return function(t){if(!t)return null;const e=rI(t);return e instanceof HTMLElement&&t.contains(e)?e:null}(t)?.dataset.role??null}function lI(t,e){t.addEventListener("blur",()=>{queueMicrotask(()=>{t.isConnected&&e()})})}const cI={continuous_threshold_pct:{min:1,max:200},spike_threshold_pct:{min:1,max:200},window_duration_m:{min:1,max:180},cooldown_duration_m:{min:1,max:180}};function uI(t){t.addEventListener("wheel",e=>{oI(t)&&e.preventDefault()},{passive:!1})}function dI(t){if(!t?.offered)return null;const[e,...n]=t.members;if(!e||n.length>0)return null;const i=e.circuit.package_ratings_form,r=e.circuit.breaker_rating_a;return"one_space"!==i&&"two_spaces"!==i||null==r?null:{kind:i,member:e,panelA:r}}function hI(t){return t.circuit.package_ratings_a?.[1]??null}class pI{constructor(t){this._host=t,this._section=null,this._field=null}get element(){return this._section}mount(t){this._field=null;const e=dI(this._host.ratingsView);this._section=e?this._build(e):null,this._section&&t.after(this._section)}sync(t){const e=dI(this._host.ratingsView),n=this._section;if(n&&e&&n.dataset.kind===e.kind&&n.dataset.uuid===e.member.uuid)return void this._patch(n,e);const i=sI(n);this._field=null;const r=e?this._build(e):null;if(n&&r?n.replaceWith(r):n?n.remove():r&&t.after(r),this._section=r,null===i)return;const o=r?.querySelector(`[data-role="${i}"]`)??r?.querySelector('[data-role="rating-input"]');o?o.focus():this._host.focusAfterRatingsEditor()}_build(t){const e=document.createElement("div");e.dataset.role="rating-section",e.dataset.kind=t.kind,e.dataset.uuid=t.member.uuid,e.className="rating-section";const n=document.createElement("div");n.className="section-label",n.textContent=i("monitoringRating.title"),e.appendChild(n);const r=document.createElement("div");r.className="field-label",r.id="rating-guidance",r.dataset.role="rating-guidance",r.textContent=i("one_space"===t.kind?"monitoringRating.guidance":"monitoringRating.guidance_two_spaces"),e.appendChild(r);const o=document.createElement("div");o.className="field-label rating-feedback",o.id="rating-feedback",o.dataset.role="rating-feedback",o.setAttribute("aria-live","polite"),e.appendChild(this._buildRow(t,o)),e.appendChild(o);const a=document.createElement("div");return a.dataset.role="rating-warning-region",a.setAttribute("aria-live","polite"),e.appendChild(a),this._syncWarning(e,t.member),e}_buildRow(t,e){const{member:n}=t,o=document.createElement("div");o.className="field-row rating-row",o.dataset.role="rating-row",o.dataset.uuid=n.uuid;const a=document.createElement("span");a.className="field-label",a.id="rating-panel-rating",a.dataset.role="rating-panel-rating",a.textContent=r("monitoringRating.panel_rating",{panel:String(t.panelA)});const s=document.createElement("span");s.className="field-label",s.textContent=i("monitoringRating.other_breaker");const l=document.createElement("input");l.type="number",l.min="1",l.step="1",l.inputMode="numeric";const c=hI(n);return l.value=null!==c?String(c):"",l.setAttribute("aria-label",r("monitoringRating.other_breaker_label",{circuit:n.circuit.name})),l.setAttribute("aria-describedby","rating-panel-rating rating-guidance rating-feedback"),l.dataset.role="rating-input",this._field=function(t,e){uI(t);let n=!1,r=null;const o=n=>{n?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),e.report(n)},a=()=>{n=!1,r=null,o(null);const i=e.stored();t.value=null!==i?String(i):""},s=()=>{if(!n)return;const s=t.value.trim();if(""===s&&t.validity?.badInput)return void o(i("monitoringRating.invalid_other"));if(""===s)return void a();const l=Number(s);!Number.isSafeInteger(l)||l<1?o(i("monitoringRating.invalid_other")):(n=!1,o(null),l!==e.stored()&&(r=l,e.save(l)))};return t.addEventListener("input",()=>{n=!0,r=null,o(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&s()}),lI(t,s),{get dirty(){return n},revert:a,answerRefusal:t=>r===t&&(a(),!0)}}(l,{report:t=>{e.textContent=t??""},stored:()=>this._storedInForce(),save:t=>this._save(t)}),o.append(a,s,l),null!==c&&o.appendChild(this._buildReset(n.uuid)),o}_buildReset(t){const e=document.createElement("button");return e.type="button",e.className="text-btn",e.dataset.role="rating-reset",e.textContent=i("monitoringRating.reset"),e.addEventListener("click",()=>{this._field?.revert(),this._host.clearPackageRatings(t).catch(t=>this._host.reportRatingsFailure(t))}),e}_patch(t,e){const{member:n}=e,i=hI(n),o=t.querySelector('[data-role="rating-panel-rating"]');o&&(o.textContent=r("monitoringRating.panel_rating",{panel:String(e.panelA)}));const a=t.querySelector('[data-role="rating-input"]');this._field&&!this._field.dirty&&this._field.revert();const s=t.querySelector('[data-role="rating-row"]'),l=t.querySelector('[data-role="rating-reset"]');null===i&&l?(oI(l)&&a?.focus(),l.remove()):null!==i&&!l&&s&&s.appendChild(this._buildReset(n.uuid)),this._syncWarning(t,n)}_storedInForce(){const t=dI(this._host.ratingsView);return t?hI(t.member):null}_save(t){const e=dI(this._host.ratingsView);if(!e)return;const{member:n,panelA:i}=e;this._host.setPackageRatings(n.uuid,[i,t]).catch(e=>{this._host.reportRatingsFailure(e),this._answerRefusal(n.uuid,t)})}_answerRefusal(t,e){const n=this._section,i=n?.querySelector('[data-role="rating-input"]'),r=this._field;n&&i&&r&&n.dataset.uuid===t&&dI(this._host.ratingsView)?.member.uuid===t&&r.answerRefusal(e)&&(null===document.activeElement||document.activeElement===document.body||aI(n))&&i.focus()}_syncWarning(t,e){const n=t.querySelector('[data-role="rating-warning-region"]');if(!n)return;const i=on(e.circuit,this._host.ratingsView?.monitoringInfo??null),r=n.firstElementChild instanceof HTMLElement?n.firstElementChild:null;if(r&&r.dataset.kind===i)return;const o=aI(r);r?.remove(),i&&n.appendChild("averaged_legs"===i?this._buildAveragedLegsWarning():this._buildThresholdWarning(i)),o&&this._host.focusAfterRatingsEditor()}_buildThresholdWarning(t){const e="own"===t?i("monitoringRating.threshold_warning"):r("monitoringRating.threshold_warning_global",{settings:i("monitoring.global_settings"),tab:i("tab.monitoring")}),n=this._buildWarning("rating-threshold-warning",t,e);return"own"===t&&n.appendChild(this._buildActionButton("rating-threshold-reset",i("monitoringRating.use_global_thresholds"),()=>this._host.useGlobalThresholds())),n}_buildAveragedLegsWarning(){const t=this._buildWarning("rating-averaged-legs-warning","averaged_legs",i("monitoringRating.averaged_legs"));return t.appendChild(this._buildActionButton("rating-turn-off-monitoring",i("monitoringRating.turn_off_monitoring"),()=>this._host.turnOffMonitoring())),t}_buildWarning(t,e,n){const i=document.createElement("div");i.className="field-label rating-warning",i.dataset.role=t,i.dataset.kind=e,i.setAttribute("role","note");const r=document.createElement("span");return r.textContent=n,i.appendChild(r),i}_buildActionButton(t,e,n){const i=document.createElement("button");return i.type="button",i.className="text-btn",i.dataset.role=t,i.textContent=e,i.addEventListener("click",()=>{"true"!==i.getAttribute("aria-disabled")&&(i.setAttribute("aria-disabled","true"),n().then(t=>{t||i.removeAttribute("aria-disabled")}))}),i}}function fI(t){return!0===t?.user?.is_admin}function gI(){return i("monitoring.admin_only")}class mI extends Error{constructor(){super(gI()),this.name="MonitoringChangeRefused"}}function vI(t){const e=e=>n=>async function(t,e,n){if(!t||!fI(t))throw new mI;try{await t.callWS({type:"call_service",domain:l,service:e,service_data:n})}catch(t){throw ie(t)?new mI:t}}(t,e,n);return{setGlobalMonitoring:e("set_global_monitoring"),testNotification:e("test_notification"),setCircuitThreshold:e("set_circuit_threshold"),clearCircuitThreshold:e("clear_circuit_threshold"),setMainsThreshold:e("set_mains_threshold"),clearMainsThreshold:e("clear_mains_threshold"),setCircuitPackageRatings:e("set_circuit_package_ratings"),clearCircuitPackageRatings:e("clear_circuit_package_ratings")}}function yI(t,e){return t instanceof mI?t.message:e}function _I(t,e,n){console.warn(`SPAN Panel: ${n} failed`,e),t?.add({key:"service:monitoring",level:"error",message:yI(e,i("error.threshold_failed")),persistent:!1})}const bI=new Set(["number","text"]);function xI(t){for(let e=t;e;e=e.parentElement)if(""!==e.style.opacity&&Number(e.style.opacity)<1)return!0;return!1}const wI="favorites-changed";async function SI(t,e,n={}){const i=await t.callWS({type:"call_service",domain:l,service:e,service_data:n,return_response:!0});return i?.response??null}const CI={continuous:"continuous_threshold_pct",spike:"spike_threshold_pct","window-m":"window_duration_m","cooldown-m":"cooldown_duration_m"},kI="relay-label",MI="priority-label",TI="controls-note";class AI{constructor(t,e){this.uuid=t,this._on=e,this._sent=0,this._from=0,this._pending=0}get on(){return this._on}get settled(){return 0===this._pending}answered(t){this._on=t}async send(t,e){const n=++this._sent;this._pending+=1;try{const i=await e();return i&&n>this._from&&(this._on=t,this._from=n),i}finally{this._pending-=1}}}class II extends HTMLElement{constructor(){super(),this.errorStore=null,this._thresholdReads=0,this._limitFields=[],this._storedMonitoring=null,this._controlAccess=de,this.attachShadow({mode:"open"}),this._hass=null,this._config=null,this._debounceTimers={},this._ratingsEditor=new pI(this)}set hass(t){const e=fI(this._hass)!==fI(t);this._hass=t,this.hasAttribute("open")&&this._config&&(e&&this._showsMonitoring()?this._render():this._updateLiveState())}_showsMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!0!==t.showMonitoring)}get hass(){return this._hass}open(t){this._config=t,this._storedMonitoring=t.panelMode||t.subDeviceMode||t.favoritesMode?null:new AI(t.uuid,en(t.monitoringInfo)),this._controlAccess=t.panelMode||t.subDeviceMode||t.favoritesMode?de:t.controlAccess,this._render(),this.offsetHeight,this.setAttribute("open",""),this.setAttribute("data-mode",this._modeFor(t))}get openCircuit(){const t=this._config;return!t||!this.hasAttribute("open")||t.panelMode||t.subDeviceMode||t.favoritesMode?null:{uuid:t.uuid,configEntryId:t.configEntryId??null}}refreshRating(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i={...e,members:t.members,capacityA:t.capacityA,monitoringInfo:t.monitoringInfo,monitoringGlobals:t.monitoringGlobals};this._config=i,this._monitoringStoredAs(e.uuid,t.monitoringInfo);const r=n.querySelector(".subtitle");r&&(r.textContent=this._circuitSubtitle(i)),this._syncMonitoring()}close(){this.removeAttribute("open"),this.removeAttribute("data-mode"),this._config=null,this._storedMonitoring=null,this._controlAccess=de,this.dispatchEvent(new CustomEvent("side-panel-closed",{bubbles:!0,composed:!0}))}_modeFor(t){return t.favoritesMode?"favorites":t.panelMode?"panel":t.subDeviceMode?"subDevice":"circuit"}_render(){const t=this._config;if(!t)return;const e=this.shadowRoot;if(!e)return;e.innerHTML="";const n=document.createElement("style");n.textContent='\n :host {\n display: block;\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n width: 360px;\n max-width: 90vw;\n z-index: 1000;\n transform: translateX(100%);\n transition: transform 0.3s ease;\n pointer-events: none;\n }\n :host([open]) {\n transform: translateX(0);\n pointer-events: auto;\n }\n\n .backdrop {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.3);\n z-index: -1;\n }\n :host([open]) .backdrop {\n display: block;\n }\n\n .panel {\n height: 100%;\n background: var(--card-background-color, #fff);\n border-left: 1px solid var(--divider-color, #e0e0e0);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n\n .panel-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px;\n border-bottom: 1px solid var(--divider-color, #e0e0e0);\n }\n .panel-header .title {\n font-size: 18px;\n font-weight: 500;\n color: var(--primary-text-color, #212121);\n margin: 0;\n }\n .panel-header .subtitle {\n font-size: 13px;\n color: var(--secondary-text-color, #727272);\n margin: 2px 0 0 0;\n }\n .close-btn {\n background: none;\n border: none;\n cursor: pointer;\n color: var(--secondary-text-color, #727272);\n padding: 4px;\n line-height: 1;\n font-size: 20px;\n }\n\n .panel-body {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n }\n\n .section {\n margin-bottom: 20px;\n }\n .section-label {\n font-size: 12px;\n font-weight: 600;\n text-transform: uppercase;\n color: var(--secondary-text-color, #727272);\n margin: 0 0 8px 0;\n letter-spacing: 0.5px;\n }\n\n .field-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 8px 0;\n }\n /* Why the section\'s relay or priority cannot be operated, under it. */\n .controls-note {\n margin: 4px 0 0;\n font-size: 0.85em;\n color: var(--secondary-text-color, #727272);\n }\n .field-label {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n }\n\n select {\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n }\n\n input[type="number"] {\n width: 72px;\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n text-align: right;\n }\n input[type="number"]:disabled {\n opacity: 0.5;\n }\n\n .radio-group {\n display: flex;\n gap: 16px;\n padding: 8px 0;\n }\n .radio-group label {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n cursor: pointer;\n }\n\n .horizon-bar {\n display: flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n margin-top: 4px;\n }\n .horizon-segment {\n flex: 1;\n padding: 6px 0;\n text-align: center;\n font-size: 13px;\n cursor: pointer;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n transition: background 0.15s ease, color 0.15s ease;\n user-select: none;\n line-height: 1.4;\n }\n .horizon-segment:last-child {\n border-right: none;\n }\n .horizon-segment:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .horizon-segment.active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n .horizon-segment.referenced {\n box-shadow: inset 0 -3px 0 var(--primary-color, #03a9f4);\n }\n\n .unit-toggle {\n display: inline-flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n }\n .unit-btn {\n padding: 4px 10px;\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease;\n }\n .unit-btn:last-child {\n border-right: none;\n }\n .unit-btn:hover:not(.unit-active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .unit-btn.unit-active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n\n .monitoring-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n\n .fav-heart {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--secondary-text-color, #727272);\n border-radius: 4px;\n padding: 2px 6px;\n cursor: pointer;\n font-size: 0.9em;\n margin-right: 6px;\n line-height: 1;\n display: inline-flex;\n align-items: center;\n }\n .fav-heart.active {\n color: var(--primary-color, #03a9f4);\n border-color: var(--primary-color, #03a9f4);\n }\n .fav-heart:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .fav-heart span-icon {\n --mdc-icon-size: 16px;\n }\n\n .rating-section {\n margin-bottom: 8px;\n }\n .limit-row {\n flex-wrap: wrap;\n }\n .limit-feedback {\n flex-basis: 100%;\n }\n .rating-row {\n flex-wrap: wrap;\n justify-content: flex-start;\n gap: 6px 8px;\n }\n .rating-row [data-role="rating-panel-rating"] {\n flex-basis: 100%;\n }\n .rating-feedback {\n font-size: 13px;\n color: var(--error-color, #db4437);\n }\n .rating-warning {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 6px 8px;\n margin-top: 6px;\n padding: 8px;\n border-left: 3px solid var(--warning-color, #ffa600);\n border-radius: 4px;\n background: color-mix(in srgb, var(--warning-color, #ffa600) 12%, transparent);\n font-size: 13px;\n }\n\n .text-btn {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--primary-text-color, #212121);\n border-radius: 4px;\n padding: 4px 8px;\n font: inherit;\n font-size: 13px;\n line-height: 1.3;\n cursor: pointer;\n }\n .text-btn:hover:not(:disabled):not([aria-disabled="true"]) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .text-btn:focus-visible {\n outline: 2px solid var(--primary-color, #03a9f4);\n outline-offset: 1px;\n }\n .text-btn:disabled,\n .text-btn[aria-disabled="true"] {\n opacity: 0.5;\n cursor: default;\n }\n\n .panel-mode-info {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n line-height: 1.6;\n }\n .panel-mode-info p {\n margin: 0 0 12px 0;\n }\n\n',e.appendChild(n);const i=document.createElement("div");i.className="backdrop",i.addEventListener("click",()=>this.close()),e.appendChild(i);const r=document.createElement("div");r.className="panel",e.appendChild(r),t.favoritesMode?this._renderFavoritesMode(r):t.panelMode?this._renderPanelMode(r):t.subDeviceMode?this._renderSubDeviceMode(r,t):this._renderCircuitMode(r,t)}_renderPanelMode(t){const e=this._config,n=this._createHeader(i("sidepanel.graph_settings"),i("sidepanel.global_defaults"));t.appendChild(n);const r=document.createElement("div");r.className="panel-body";const o=e.graphSettings,l=e.topology,c=o?.global_horizon??a,u=o?.circuits??{};r.appendChild(this._buildListColumnsSection());const d=document.createElement("div");d.className="section";const h=document.createElement("div");h.className="section-label",h.textContent=i("sidepanel.graph_horizon"),d.appendChild(h);const p=document.createElement("div");p.className="field-row";const f=document.createElement("span");f.className="field-label",f.textContent=i("sidepanel.global_default"),p.appendChild(f);const g=document.createElement("select");for(const t of Object.keys(s)){const e=document.createElement("option");e.value=t;const n=`horizon.${t}`,r=i(n);e.textContent=r!==n?r:t,t===c&&(e.selected=!0),g.appendChild(e)}if(g.addEventListener("change",()=>{const t={horizon:g.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_graph_time_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})}),p.appendChild(g),d.appendChild(p),r.appendChild(d),l?.circuits){const t=document.createElement("div");t.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=i("sidepanel.circuit_scales"),t.appendChild(n);const o=Object.entries(l.circuits).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[n,i]of o){const r=this._buildPanelModeCircuitRow(n,i,u[n],c,e.configEntryId??null,e.showFavorites??!1,e.favoritePanelDeviceId,e.favoriteCircuitUuids);t.appendChild(r)}r.appendChild(t)}const m=o?.sub_devices??{};if(l?.sub_devices){const t=document.createElement("div");t.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=i("sidepanel.subdevice_scales"),t.appendChild(n);const o=Object.entries(l.sub_devices).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[n,r]of o){const o=qn(r).length>0,a=e.showFavorites&&e.favoritePanelDeviceId?this._buildSubDeviceFavoriteHeart(r.entities,e.favoriteSubDeviceIds?.has(n)??!1):null;if(!o&&!a)continue;const l=document.createElement("div");l.className="field-row";const u=document.createElement("span");if(u.className="field-label",u.textContent=r.name||n,u.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",l.appendChild(u),a&&l.appendChild(a),!o){t.appendChild(l);continue}const d=m[n]||{horizon:c,has_override:!1},h=d.has_override?d.horizon:c,p=document.createElement("select");p.dataset.subdevId=n;for(const t of Object.keys(s)){const e=document.createElement("option");e.value=t;const n=`horizon.${t}`,r=i(n);e.textContent=r!==n?r:t,t===h&&(e.selected=!0),p.appendChild(e)}if(p.addEventListener("change",()=>{this._debounce(`subdev-${e.configEntryId??""}-${n}`,500,()=>{const t={subdevice_id:n,horizon:p.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_subdevice_graph_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})})}),l.appendChild(p),d.has_override){const t=document.createElement("button");t.textContent="↺",t.title=i("sidepanel.reset_to_global"),Object.assign(t.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),t.addEventListener("click",()=>{const r={subdevice_id:n};e.configEntryId&&(r.config_entry_id=e.configEntryId),this._callDomainService("clear_subdevice_graph_horizon",r).then(()=>{p.value=c,t.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})}),l.appendChild(t)}t.appendChild(l)}t.children.length>1&&r.appendChild(t)}t.appendChild(r)}_buildPanelModeCircuitRow(t,e,n,r,o,a,l,c){const u=document.createElement("div");u.className="field-row";const d=document.createElement("span");if(d.className="field-label",d.textContent=e.name||t,d.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",u.appendChild(d),a&&l){const n=this._buildFavoriteHeart(e.entities,c?.has(t)??!1);n&&u.appendChild(n)}const h=n||{horizon:r,has_override:!1},p=h.has_override?h.horizon:r,f=document.createElement("select");f.dataset.uuid=t;for(const t of Object.keys(s)){const e=document.createElement("option");e.value=t;const n=`horizon.${t}`,r=i(n);e.textContent=r!==n?r:t,t===p&&(e.selected=!0),f.appendChild(e)}if(f.addEventListener("change",()=>{this._debounce(`circuit-${o??""}-${t}`,500,()=>{const e={circuit_id:t,horizon:f.value};o&&(e.config_entry_id=o),this._callDomainService("set_circuit_graph_horizon",e).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})})}),u.appendChild(f),h.has_override){const e=document.createElement("button");e.textContent="↺",e.title=i("sidepanel.reset_to_global"),Object.assign(e.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),e.addEventListener("click",()=>{const n={circuit_id:t};o&&(n.config_entry_id=o),this._callDomainService("clear_circuit_graph_horizon",n).then(()=>{f.value=r,e.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})}),u.appendChild(e)}return u}_renderFavoritesMode(t){const e=this._config,n=this._createHeader(i("sidepanel.graph_settings"),i("sidepanel.favorites_subtitle"));t.appendChild(n);const r=document.createElement("div");r.className="panel-body",r.appendChild(this._buildListColumnsSection());for(const t of e.perPanelSections)r.appendChild(this._buildFavoritesPanelSection(t));t.appendChild(r)}_buildFavoritesPanelSection(t){const e=document.createElement("div");e.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=t.panelName,e.appendChild(n);const i=t.graphSettings?.global_horizon??a,r=t.graphSettings?.circuits??{},o=function(t){const e=t.circuits??{};return Object.entries(e).map(([t,e])=>({uuid:t,circuit:e})).sort((t,e)=>(t.circuit.name||"").localeCompare(e.circuit.name||""))}(t.topology);for(const{uuid:n,circuit:a}of o){const o=this._buildPanelModeCircuitRow(n,a,r[n],i,t.configEntryId,!0,t.panelDeviceId,t.favoriteCircuitUuids);e.appendChild(o)}return e}_renderCircuitMode(t,e){const n=this._createHeader(e.name,this._circuitSubtitle(e));t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),this._renderRelaySection(i,e),e.showFavorites&&this._renderFavoriteSection(i,e),this._renderSheddingSection(i,e),this._placeControlNote(i),this._renderGraphHorizonSection(i,e),e.showMonitoring&&this._renderMonitoringSection(i,e)}_placeControlNote(t){t.querySelector('[data-role="controls-note"]')?.remove();const e=[...t.querySelectorAll('[data-role="relay-toggle"], [data-role="shedding-select"]')];e[0]?.closest(".section")?.insertAdjacentHTML("beforeend",Me(this._controlAccess));const n=t.querySelector('[data-role="controls-note"]');n&&(n.id=TI);for(const t of e)n?t.setAttribute("aria-describedby",TI):t.removeAttribute("aria-describedby")}refreshControlAccess(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i=this._controlAccess;i.mayOperate===t.mayOperate&&i.reason===t.reason||(this._controlAccess=t,this._updateLiveState(),this._placeControlNote(n))}_circuitSubtitle(t){const e=t.members.map(t=>t.circuit),n=[...new Set(e.flatMap(t=>t.voltage?[t.voltage]:[]))].sort((t,e)=>t-e);return[je(e),e.length>1&&t.capacityA?r("sidepanel.capacity",{amps:String(t.capacityA)}):"",n.length>0?`${n.join("/")}V`:"",`Tabs [${$e(e).join(",")}]`].filter(Boolean).join(" · ")}_favoriteEntityId(t){return t?.current??t?.power??null}_buildSubDeviceFavoriteHeart(t,e){const n=Gn(t);return n?this._buildHeartButton(n,e):null}_buildListColumnsSection(){const t=document.createElement("div");t.className="section";const e=document.createElement("div");e.className="section-label",e.textContent=i("sidepanel.list_view_columns"),t.appendChild(e);const n=document.createElement("div");n.className="field-row";const r=document.createElement("span");r.className="field-label",r.textContent=i("sidepanel.columns"),n.appendChild(r);const o=$t(),a=document.createElement("div");a.className="unit-toggle";for(const t of[1,2,3]){const e=document.createElement("button");e.type="button",e.className="unit-btn"+(t===o?" unit-active":""),e.dataset.columns=String(t),e.textContent=String(t),e.addEventListener("click",()=>{Vt(t);for(const t of a.querySelectorAll(".unit-btn"))t.classList.toggle("unit-active",t===e);this.dispatchEvent(new CustomEvent("list-columns-changed",{detail:t,bubbles:!0,composed:!0}))}),a.appendChild(e)}return n.appendChild(a),t.appendChild(n),t}_buildFavoriteHeart(t,e){const n=this._favoriteEntityId(t);return n?this._buildHeartButton(n,e):(console.warn("SPAN Panel: circuit has no current/power sensor; favorite heart suppressed"),null)}_buildHeartButton(t,e){const n=document.createElement("button");n.type="button",n.className=e?"fav-heart active":"fav-heart",n.dataset.role="fav-heart",n.title=i("sidepanel.save_to_favorites"),n.setAttribute("role","switch"),n.setAttribute("aria-checked",String(e)),n.setAttribute("aria-label",i("sidepanel.save_to_favorites"));const r=document.createElement("span-icon");return r.setAttribute("icon",e?"mdi:heart":"mdi:heart-outline"),n.appendChild(r),n.addEventListener("click",e=>{e.stopPropagation(),this._toggleFavoriteEntity(n,r,t).catch(()=>{})}),n}async _toggleFavoriteEntity(t,e,n){if(!this._hass)return;const r=t.classList.contains("active"),o=!r;t.classList.toggle("active",o),e.setAttribute("icon",o?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(o));try{o?await async function(t,e){const n=await SI(t,"add_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(wI)),n?.favorites??{}}(this._hass,n):await async function(t,e){const n=await SI(t,"remove_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(wI)),n?.favorites??{}}(this._hass,n)}catch(n){throw t.classList.toggle("active",r),e.setAttribute("icon",r?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(r)),console.warn("SPAN Panel: favorite toggle failed",n),this.errorStore?.add({key:"service:favorites",level:"error",message:i("error.favorites_toggle_failed"),persistent:!1}),n}}_renderFavoriteSection(t,e){const n=this._favoriteEntityId(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_appendFavoriteHeartSection(t,e,n){const r=document.createElement("div");r.className="section",r.innerHTML=``;const o=document.createElement("div");o.className="field-row";const a=document.createElement("span");a.className="field-label",a.textContent=i("sidepanel.save_to_favorites"),o.appendChild(a),o.appendChild(this._buildHeartButton(e,n)),r.appendChild(o),t.appendChild(r)}_renderSubDeviceMode(t,e){const n=this._createHeader(e.name,e.deviceType);t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),e.showFavorites&&this._renderSubDeviceFavoriteSection(i,e),e.hasChart&&this._renderSubDeviceHorizonSection(i,e)}_renderSubDeviceFavoriteSection(t,e){const n=Gn(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_renderSubDeviceHorizonSection(t,e){const n=document.createElement("div");n.className="section";const r=document.createElement("div");r.className="section-label",r.textContent=i("sidepanel.graph_horizon"),n.appendChild(r);const o=e.graphHorizonInfo,l=!0===o?.has_override,c=o?.horizon||a,u=o?.globalHorizon||a,d=document.createElement("div");d.className="horizon-bar";const h=[{key:"global",label:i("sidepanel.global")}];for(const t of Object.keys(s))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of d.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===u)}};for(const{key:t,label:n}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=n,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===u),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const n={subdevice_id:e.subDeviceId};e.configEntryId&&(n.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_subdevice_graph_horizon",n).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_subdevice_graph_horizon",{...n,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})}))}),d.appendChild(r)}n.appendChild(d),t.appendChild(n)}_createHeader(t,e){const n=document.createElement("div");n.className="panel-header";const i=document.createElement("div"),r=document.createElement("div");if(r.className="title",r.textContent=t,i.appendChild(r),e){const t=document.createElement("div");t.className="subtitle",t.textContent=e,i.appendChild(t)}const o=document.createElement("button");return o.className="close-btn",o.innerHTML="✕",o.addEventListener("click",()=>this.close()),n.appendChild(i),n.appendChild(o),n}_renderRelaySection(t,e){if(!this._hass||"none"===_n(e,this._hass))return;const n=document.createElement("div");n.className="section",n.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=kI,o.textContent=i("sidepanel.breaker");const a=document.createElement("span-switch");a.dataset.role="relay-toggle",a.setAttribute("aria-labelledby",kI);const s=e.entities.switch;this._applyRelayToggle(a,e),a.addEventListener("change",()=>{const t=this._hass;t&&s&&"operable"===_n(e,t)&&xe(t,this._controlAccess).setRelay(s,a.checked).catch(n=>{Ce(t,this.errorStore,n,"relay"),this._applyRelayToggle(a,e)})}),r.appendChild(o),r.appendChild(a),n.appendChild(r),t.appendChild(n)}_renderSheddingSection(t,e){if(!e.entities?.select)return;const n=document.createElement("div");n.className="section",n.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=MI,o.textContent=i("sidepanel.priority_label");const a=document.createElement("select");a.dataset.role="shedding-select",a.setAttribute("aria-labelledby",MI);const s=e.entities.select;for(const t of x){const e=b[t];if(!e)continue;const n=document.createElement("option");n.value=t,n.textContent=i(`shedding.select.${t}`)||e.label(),a.appendChild(n)}a.addEventListener("change",()=>{const t=this._hass;t&&xe(t,this._controlAccess).setPriority(s,a.value).catch(n=>{Ce(t,this.errorStore,n,"priority"),this._applySheddingSelect(a,e)})}),r.appendChild(o),r.appendChild(a),n.appendChild(r),t.appendChild(n),this._applySheddingSelect(a,e)}get ratingsView(){const t=this._config;return!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!t.showMonitoring?null:{members:t.members??[],monitoringInfo:t.monitoringInfo,offered:!0===t.monitoringRatingOffered}}setPackageRatings(t,e){return vI(this._hass).setCircuitPackageRatings(this._ratingsPayload(t,{package_ratings_a:[...e]}))}clearPackageRatings(t){return vI(this._hass).clearCircuitPackageRatings(this._ratingsPayload(t,{}))}reportRatingsFailure(t){!function(t,e,n){console.warn("SPAN Panel: package ratings update failed",n),se(t,n,l,i("error.package_ratings_failed")).then(t=>{e?.add({key:"service:package-ratings",level:"error",message:t,persistent:!1})})}(this._hass,this.errorStore,t)}async useGlobalThresholds(){const t=this._config,e=this.shadowRoot;if(!t||!e||t.panelMode||t.subDeviceMode||t.favoritesMode)return!1;const n=e.querySelector('input[name="monitoring-mode"][value="global"]'),i=e.querySelector('input[name="monitoring-mode"][value="custom"]'),r=e.querySelector('[data-role="threshold-fields"]');n&&(n.checked=!0),r&&(r.style.display="none"),this._thresholdReads+=1;const o={circuit_id:t.entities?.power||t.uuid};t.configEntryId&&(o.config_entry_id=t.configEntryId);try{await vI(this._hass).clearCircuitThreshold(o)}catch(e){return _I(this.errorStore,e,"monitoring update"),this._config===t&&(i&&(i.checked=!0),r&&(r.style.display="block")),!1}const a=this._config===t?t.monitoringGlobals??null:null;return this._monitoringChanged(t.uuid,{has_override:!1,continuous_threshold_pct:a?.continuous_threshold_pct,spike_threshold_pct:a?.spike_threshold_pct}),!0}async turnOffMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode)&&this._sendMonitoringEnabled(t,!1)}focusAfterRatingsEditor(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"]:checked')??t?.querySelector('input[name="monitoring-mode"]');e?.focus()}_ratingsPayload(t,e){const n={circuit_id:t,...e},i=this._config,r=!i||i.panelMode||i.subDeviceMode||i.favoritesMode?null:i.configEntryId;return r&&(n.config_entry_id=r),n}_monitoringChanged(t,e){const n=this._openCircuitConfig(t);n&&(this._config={...n,monitoringInfo:{...n.monitoringInfo??{},...e}},this._syncMonitoring())}_monitoringAnswered(t,e,n){const i=this._openCircuitConfig(t);i&&(this._config={...i,monitoringInfo:e,monitoringGlobals:n},this._monitoringStoredAs(t,e),!0!==e.has_override&&this._showGlobalChoice(),this._syncMonitoring())}_monitoringStoredAs(t,e){const n=this._storedMonitoring;e&&n?.uuid===t&&n.answered(en(e))}_showStoredMonitoring(t){if(!t||t!==this._storedMonitoring||!t.settled)return;const e=this.shadowRoot?.querySelector('[data-role="monitoring-toggle"]')?.hasAttribute("checked");e!==t.on&&this._showMonitoringEnabled(t.uuid,t.on)}_showGlobalChoice(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"][value="global"]'),n=t?.querySelector('[data-role="threshold-fields"]');e&&n&&!e.checked&&!this._limitFields.some(t=>t.dirty)&&(e.checked=!0,aI(n)&&e.focus(),n.style.display="none")}_openCircuitConfig(t){const e=this._config;return!e||e.panelMode||e.subDeviceMode||e.favoritesMode||e.uuid!==t||!this.hasAttribute("open")?null:e}_syncMonitoring(){const t=this._config,e=this.shadowRoot?.querySelector('[data-role="judged-against"]');if(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!e)return;const n=this._judgedAgainstText(t.monitoringInfo);e.textContent!==n&&(e.textContent=n),this._ratingsEditor.sync(e),this._lockMonitoringIfReadOnly()}_renderGraphHorizonSection(t,e){const n=document.createElement("div");n.className="section",n.dataset.role="horizon-section";const r=document.createElement("div");r.className="section-label",r.textContent=i("sidepanel.graph_horizon"),n.appendChild(r);const o=e.graphHorizonInfo,l=!0===o?.has_override,c=o?.horizon||a,u=o?.globalHorizon||a,d=document.createElement("div");d.className="horizon-bar";const h=[{key:"global",label:i("sidepanel.global")}];for(const t of Object.keys(s))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of d.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===u)}};for(const{key:t,label:n}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=n,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===u),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const n={circuit_id:e.uuid};e.configEntryId&&(n.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_circuit_graph_horizon",n).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_circuit_graph_horizon",{...n,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})}))}),d.appendChild(r)}n.appendChild(d),t.appendChild(n)}_judgedAgainstText(t){return function(t){return t.amps?t.userSet?r("monitoringRating.judged_copied",{rating:String(t.amps),copied:an(t)}):r("sidepanel.judged_against",{rating:`${t.amps} A`}):r("sidepanel.judged_against",{rating:i("monitoringRating.none")})}({amps:(e=t)?tn(e):void 0,panelAmps:e?.breaker_rating_a,userSet:!0===e?.monitoring_rating_user_set,packageRatings:e?.package_ratings_a??null});var e}_renderMonitoringSection(t,e){const n=document.createElement("div");n.className="section",n.dataset.role="monitoring-section";const r=document.createElement("div");r.className="monitoring-header";const o=document.createElement("div");o.className="section-label",o.textContent=i("sidepanel.monitoring"),o.style.margin="0";const a=document.createElement("span-switch");a.dataset.role="monitoring-toggle";const s=e.monitoringInfo,l=en(s);l&&a.setAttribute("checked",""),r.appendChild(o),r.appendChild(a),n.appendChild(r),fI(this._hass)||n.appendChild(function(){const t=document.createElement("p");return t.dataset.role="monitoring-read-only",t.setAttribute("role","note"),t.style.cssText="margin:8px 0 12px;font-size:0.85em;color:var(--secondary-text-color);",t.textContent=gI(),t}());const c=document.createElement("div");c.dataset.role="monitoring-details",c.style.display=l?"block":"none",n.appendChild(c);const u=!0===s?.has_override,d=document.createElement("div");d.className="field-label",d.dataset.role="judged-against",d.setAttribute("aria-live","polite"),d.style.marginBottom="8px",d.textContent=this._judgedAgainstText(s),c.appendChild(d),this._ratingsEditor.mount(d);const h=document.createElement("div");h.className="radio-group",h.innerHTML=`\n \n \n `,c.appendChild(h),this._limitFields=[];const p=document.createElement("div");p.dataset.role="threshold-fields",p.style.display=u?"block":"none";const f=s?.continuous_threshold_pct??80,g=s?.spike_threshold_pct??100,m=s?.window_duration_m??15,v=s?.cooldown_duration_m??15;p.appendChild(this._createLimitRow(i("sidepanel.continuous_pct"),"continuous",f,null,e)),p.appendChild(this._createLimitRow(i("sidepanel.spike_pct"),"spike",g,null,e)),p.appendChild(this._createLimitRow(i("sidepanel.window_duration"),"window-m",m,"m",e)),p.appendChild(this._createLimitRow(i("sidepanel.cooldown"),"cooldown-m",v,"m",e)),c.appendChild(p),a.addEventListener("change",()=>{const t=a.checked;this._showMonitoringEnabled(e.uuid,t),this._sendMonitoringEnabled(e,t)});const y=h.querySelectorAll('input[type="radio"]');for(const t of y)t.addEventListener("change",()=>{t.checked&&("custom"===t.value?p.style.display="block":this.useGlobalThresholds())});t.appendChild(n),this._lockMonitoringIfReadOnly()}_lockMonitoringIfReadOnly(){const t=this.shadowRoot?.querySelector('[data-role="monitoring-section"]');t&&!fI(this._hass)&&function(t){const e=gI();for(const n of t.querySelectorAll("input, select, textarea, button, span-switch"))n instanceof HTMLInputElement&&bI.has(n.type)||n instanceof HTMLTextAreaElement?n.readOnly=!0:n.setAttribute("disabled",""),n.title=e,"span-switch"!==n.localName&&(xI(n)||(n.style.opacity="0.5"),n.style.cursor="not-allowed")}(t)}async _sendMonitoringEnabled(t,e){const n={circuit_id:t.entities?.power||t.uuid,monitoring_enabled:e};t.configEntryId&&(n.config_entry_id=t.configEntryId);const i=async()=>{try{return await vI(this._hass).setCircuitThreshold(n),!0}catch(t){return _I(this.errorStore,t,"monitoring update"),!1}},r=this._storedMonitoring;if(r?.uuid!==t.uuid)return i();const o=await r.send(e,i);return this._showStoredMonitoring(r),o}_showMonitoringEnabled(t,e){const n=this.shadowRoot;if(!this._openCircuitConfig(t)||!n)return;const i=n.querySelector('[data-role="monitoring-toggle"]');i?.toggleAttribute("checked",e);const r=n.querySelector('[data-role="monitoring-details"]');if(r){const t=!e&&aI(r);r.style.display=e?"block":"none",t&&i?.focus()}this._monitoringChanged(t,{monitoring_enabled:e})}_createLimitRow(t,e,n,i,o){const a=CI[e],{min:s,max:l}=cI[a],c=document.createElement("div");c.className="field-row limit-row";const u=document.createElement("span");u.className="field-label",u.id=`threshold-label-${e}`,u.textContent=t;const d=document.createElement("div"),h=document.createElement("input");if(h.type="number",h.setAttribute("aria-labelledby",u.id),h.min=String(s),h.max=String(l),h.step="1",h.value=String(n),h.dataset.role=`threshold-${e}`,h.setAttribute("aria-describedby",`threshold-feedback-${e}`),d.appendChild(h),i){const t=document.createElement("span");t.textContent=i,d.appendChild(t)}const p=document.createElement("div");p.className="field-label rating-feedback limit-feedback",p.id=`threshold-feedback-${e}`,p.dataset.role=`threshold-feedback-${e}`,p.setAttribute("aria-live","polite");const f=function(t,e,n){const{min:i,max:o}=cI[e];uI(t);let a=!1;const s=e=>{e?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),n.report(e)},l=()=>{const e=""===t.value.trim()?Number.NaN:Number(t.value);return Number.isSafeInteger(e)&&e>=i&&e<=o?e:(s(r("monitoring.limit_invalid",{min:String(i),max:String(o)})),null)},c=()=>{if(!a)return;const t=l();null!==t&&(a=!1,s(null),n.save(t))};return t.addEventListener("input",()=>{a=!0,s(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&c()}),lI(t,c),{get dirty(){return a},check:l}}(h,a,{report:t=>{p.textContent=t??""},save:t=>{const e={circuit_id:o.entities?.power||o.uuid,[a]:t};o.configEntryId&&(e.config_entry_id=o.configEntryId),this._saveThresholds(o,e)}});return this._limitFields.push(f),c.append(u,d,p),c}_saveThresholds(t,e){vI(this._hass).setCircuitThreshold(e).then(()=>this._readThresholds(t,e),t=>_I(this.errorStore,t,"monitoring update"))}_updateLiveState(){if(!this._config||this._config.panelMode)return;const t=this._config;if(!t.subDeviceMode&&!t.favoritesMode){if(t.entities?.switch){const e=this.shadowRoot?.querySelector('[data-role="relay-toggle"]');e&&this._applyRelayToggle(e,t)}if(t.entities?.select){const e=this.shadowRoot?.querySelector('[data-role="shedding-select"]');e&&this._applySheddingSelect(e,t)}}}_applyRelayToggle(t,e){if(!this._hass)return;const n=this._controlAccess;t.disabled=!n.mayOperate||"operable"!==_n(e,this._hass),ke(t,n),yn(e,this._hass)?t.setAttribute("checked",""):t.removeAttribute("checked")}_applySheddingSelect(t,e){if(!this._hass)return;const n=this._controlAccess,i=wn(e,this._hass);x.includes(i)?t.value=i:t.selectedIndex=-1,t.disabled=!n.mayOperate||!function(t,e){const n=xn(t,e);return void 0!==n&&fn.has(n)}(e,this._hass),ke(t,n)}async _readThresholds(t,e){const n=++this._thresholdReads;let i=null;try{i=await this._readMonitoringStatus(t.configEntryId??null)}catch(t){console.warn("SPAN Panel: monitoring status read failed",t)}if(n!==this._thresholdReads)return;const r=Ze(i,t);if(r)return void this._monitoringAnswered(t.uuid,r,i?.global_settings??null);const o={has_override:!0};"number"==typeof e.continuous_threshold_pct&&(o.continuous_threshold_pct=e.continuous_threshold_pct),"number"==typeof e.spike_threshold_pct&&(o.spike_threshold_pct=e.spike_threshold_pct),this._monitoringChanged(t.uuid,o)}async _readMonitoringStatus(t){if(!this._hass)return null;const e=await this._hass.callWS({type:"call_service",domain:l,service:"get_monitoring_status",service_data:t?{config_entry_id:t}:{},return_response:!0});return Ge(e?.response)}_callDomainService(t,e){return this._hass?this._hass.callWS({type:"call_service",domain:l,service:t,service_data:e}):Promise.resolve()}_debounce(t,e,n){this._debounceTimers[t]&&clearTimeout(this._debounceTimers[t]),this._debounceTimers[t]=setTimeout(()=>{delete this._debounceTimers[t],n()},e)}}try{customElements.get("span-side-panel")||customElements.define("span-side-panel",II)}catch{}class DI extends Nt{constructor(){super(...arguments),this._store=null,this._unsub=null,this._errors=[]}set store(t){if(this._store===t)return;this._unsub?.(),this._unsub=null,this._store=t,this._errors=t.active;const e=t;this._unsub=t.subscribe(()=>{this._errors=e.active})}connectedCallback(){if(super.connectedCallback(),this._store&&!this._unsub){const t=this._store;this._errors=t.active,this._unsub=t.subscribe(()=>{this._errors=t.active})}}disconnectedCallback(){super.disconnectedCallback(),this._unsub?.(),this._unsub=null}render(){return 0===this._errors.length?yt:gt`${this._errors.map(t=>gt` - `)}`}_iconForLevel(t){switch(t){case"error":return"mdi:alert-circle";case"warning":return"mdi:alert";default:return"mdi:information"}}}OI.styles=P` + `)}`}_iconForLevel(t){switch(t){case"error":return"mdi:alert-circle";case"warning":return"mdi:alert";default:return"mdi:information"}}}DI.styles=P` :host { display: block; } @@ -111,7 +111,7 @@ var Rl={},Ol={};var zl,Hl=function(){function t(t,e,n){var i=this;this._sleepAft .retry-btn:hover { opacity: 0.8; } - `,C([Bt()],OI.prototype,"_errors",void 0);try{customElements.get("span-error-banner")||customElements.define("span-error-banner",OI)}catch{}const zI=Object.freeze({"mdi:alert":"M13 14H11V9H13M13 18H11V16H13M1 21H23L12 2L1 21Z","mdi:alert-circle":"M13,13H11V7H13M13,17H11V15H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z","mdi:battery":"M16.67,4H15V2H9V4H7.33A1.33,1.33 0 0,0 6,5.33V20.67C6,21.4 6.6,22 7.33,22H16.67A1.33,1.33 0 0,0 18,20.67V5.33C18,4.6 17.4,4 16.67,4Z","mdi:battery-alert-variant-outline":"M14 20H6V6H14M14.67 4H13V2H7V4H5.33C4.6 4 4 4.6 4 5.33V20.67C4 21.4 4.6 22 5.33 22H14.67C15.4 22 16 21.4 16 20.67V5.33C16 4.6 15.4 4 14.67 4M21 7H19V13H21V8M21 15H19V17H21V15Z","mdi:chevron-down":"M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z","mdi:close":"M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z","mdi:cog":"M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.21,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.21,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.67 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z","mdi:heart":"M12,21.35L10.55,20.03C5.4,15.36 2,12.27 2,8.5C2,5.41 4.42,3 7.5,3C9.24,3 10.91,3.81 12,5.08C13.09,3.81 14.76,3 16.5,3C19.58,3 22,5.41 22,8.5C22,12.27 18.6,15.36 13.45,20.03L12,21.35Z","mdi:heart-outline":"M12.1,18.55L12,18.65L11.89,18.55C7.14,14.24 4,11.39 4,8.5C4,6.5 5.5,5 7.5,5C9.04,5 10.54,6 11.07,7.36H12.93C13.46,6 14.96,5 16.5,5C18.5,5 20,6.5 20,8.5C20,11.39 16.86,14.24 12.1,18.55M16.5,3C14.76,3 13.09,3.81 12,5.08C10.91,3.81 9.24,3 7.5,3C4.42,3 2,5.41 2,8.5C2,12.27 5.4,15.36 10.55,20.03L12,21.35L13.45,20.03C18.6,15.36 22,12.27 22,8.5C22,5.41 19.58,3 16.5,3Z","mdi:help":"M10,19H13V22H10V19M12,2C17.35,2.22 19.68,7.62 16.5,11.67C15.67,12.67 14.33,13.33 13.67,14.17C13,15 13,16 13,17H10C10,15.33 10,13.92 10.67,12.92C11.33,11.92 12.67,11.33 13.5,10.67C15.92,8.43 15.32,5.26 12,5A3,3 0 0,0 9,8H6A6,6 0 0,1 12,2Z","mdi:help-circle-outline":"M11,18H13V16H11V18M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,6A4,4 0 0,0 8,10H10A2,2 0 0,1 12,8A2,2 0 0,1 14,10C14,12 11,11.75 11,15H13C13,12.75 16,12.5 16,10A4,4 0 0,0 12,6Z","mdi:home-group":"M17,16H15V22H12V17H8V22H5V16H3L10,10L17,16M6,2L10,6H9V9H7V6H5V9H3V6H2L6,2M18,3L23,8H22V12H19V9H17V12H15.34L14,10.87V8H13L18,3Z","mdi:information":"M13,9H11V7H13M13,17H11V11H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z","mdi:lock":"M12,17A2,2 0 0,0 14,15C14,13.89 13.1,13 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V10C4,8.89 4.9,8 6,8H7V6A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,3A3,3 0 0,0 9,6V8H15V6A3,3 0 0,0 12,3Z","mdi:lock-open":"M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6C4.89,22 4,21.1 4,20V10A2,2 0 0,1 6,8H15V6A3,3 0 0,0 12,3A3,3 0 0,0 9,6H7A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,17A2,2 0 0,0 14,15A2,2 0 0,0 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17Z","mdi:menu":"M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z","mdi:monitor-eye":"M3 4V16H21V4H3M3 2H21C22.1 2 23 2.89 23 4V16C23 16.53 22.79 17.04 22.41 17.41C22.04 17.79 21.53 18 21 18H14V20H16V22H8V20H10V18H3C2.47 18 1.96 17.79 1.59 17.41C1.21 17.04 1 16.53 1 16V4C1 2.89 1.89 2 3 2M10.84 8.93C11.15 8.63 11.57 8.45 12 8.45C12.43 8.46 12.85 8.63 13.16 8.94C13.46 9.24 13.64 9.66 13.64 10.09C13.64 10.53 13.46 10.94 13.16 11.25C12.85 11.56 12.43 11.73 12 11.73C11.57 11.73 11.15 11.55 10.84 11.25C10.54 10.94 10.36 10.53 10.36 10.09C10.36 9.66 10.54 9.24 10.84 8.93M10.07 12C10.58 12.53 11.28 12.82 12 12.82C12.72 12.82 13.42 12.53 13.93 12C14.44 11.5 14.73 10.81 14.73 10.09C14.73 9.37 14.44 8.67 13.93 8.16C13.42 7.65 12.72 7.36 12 7.36C11.28 7.36 10.58 7.65 10.07 8.16C9.56 8.67 9.27 9.37 9.27 10.09C9.27 10.81 9.56 11.5 10.07 12M6 10.09C6.94 7.7 9.27 6 12 6C14.73 6 17.06 7.7 18 10.09C17.06 12.5 14.73 14.18 12 14.18C9.27 14.18 6.94 12.5 6 10.09Z","mdi:router-wireless":"M20.2,5.9L21,5.1C19.6,3.7 17.8,3 16,3C14.2,3 12.4,3.7 11,5.1L11.8,5.9C13,4.8 14.5,4.2 16,4.2C17.5,4.2 19,4.8 20.2,5.9M19.3,6.7C18.4,5.8 17.2,5.3 16,5.3C14.8,5.3 13.6,5.8 12.7,6.7L13.5,7.5C14.2,6.8 15.1,6.5 16,6.5C16.9,6.5 17.8,6.8 18.5,7.5L19.3,6.7M19,13H17V9H15V13H5A2,2 0 0,0 3,15V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V15A2,2 0 0,0 19,13M8,18H6V16H8V18M11.5,18H9.5V16H11.5V18M15,18H13V16H15V18Z","mdi:sort-descending":"M19 7H22L18 3L14 7H17V21H19M2 17H12V19H2M6 5V7H2V5M2 11H9V13H2V11Z","mdi:transmission-tower":"M8.28,5.45L6.5,4.55L7.76,2H16.23L17.5,4.55L15.72,5.44L15,4H9L8.28,5.45M18.62,8H14.09L13.3,5H10.7L9.91,8H5.38L4.1,10.55L5.89,11.44L6.62,10H17.38L18.1,11.45L19.89,10.56L18.62,8M17.77,22H15.7L15.46,21.1L12,15.9L8.53,21.1L8.3,22H6.23L9.12,11H11.19L10.83,12.35L12,14.1L13.16,12.35L12.81,11H14.88L17.77,22M11.4,15L10.5,13.65L9.32,18.13L11.4,15M14.68,18.12L13.5,13.64L12.6,15L14.68,18.12Z","mdi:view-dashboard":"M13,3V9H21V3M13,21H21V11H13M3,21H11V15H3M3,13H11V3H3V13Z"}),HI=new Set;class BI extends Nt{constructor(){super(...arguments),this.icon=""}render(){if(!this.icon)return yt;const t=zI[this.icon];return t?gt``:(e=this.icon,HI.has(e)||(HI.add(e),console.warn(`SPAN: unknown icon "${e}". Add it to MDI_PATHS in span-icon.ts.`)),yt);var e}}BI.styles=P` + `,C([Bt()],DI.prototype,"_errors",void 0);try{customElements.get("span-error-banner")||customElements.define("span-error-banner",DI)}catch{}const PI=Object.freeze({"mdi:alert":"M13 14H11V9H13M13 18H11V16H13M1 21H23L12 2L1 21Z","mdi:alert-circle":"M13,13H11V7H13M13,17H11V15H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z","mdi:battery":"M16.67,4H15V2H9V4H7.33A1.33,1.33 0 0,0 6,5.33V20.67C6,21.4 6.6,22 7.33,22H16.67A1.33,1.33 0 0,0 18,20.67V5.33C18,4.6 17.4,4 16.67,4Z","mdi:battery-alert-variant-outline":"M14 20H6V6H14M14.67 4H13V2H7V4H5.33C4.6 4 4 4.6 4 5.33V20.67C4 21.4 4.6 22 5.33 22H14.67C15.4 22 16 21.4 16 20.67V5.33C16 4.6 15.4 4 14.67 4M21 7H19V13H21V8M21 15H19V17H21V15Z","mdi:chevron-down":"M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z","mdi:close":"M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z","mdi:cog":"M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.21,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.21,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.67 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z","mdi:heart":"M12,21.35L10.55,20.03C5.4,15.36 2,12.27 2,8.5C2,5.41 4.42,3 7.5,3C9.24,3 10.91,3.81 12,5.08C13.09,3.81 14.76,3 16.5,3C19.58,3 22,5.41 22,8.5C22,12.27 18.6,15.36 13.45,20.03L12,21.35Z","mdi:heart-outline":"M12.1,18.55L12,18.65L11.89,18.55C7.14,14.24 4,11.39 4,8.5C4,6.5 5.5,5 7.5,5C9.04,5 10.54,6 11.07,7.36H12.93C13.46,6 14.96,5 16.5,5C18.5,5 20,6.5 20,8.5C20,11.39 16.86,14.24 12.1,18.55M16.5,3C14.76,3 13.09,3.81 12,5.08C10.91,3.81 9.24,3 7.5,3C4.42,3 2,5.41 2,8.5C2,12.27 5.4,15.36 10.55,20.03L12,21.35L13.45,20.03C18.6,15.36 22,12.27 22,8.5C22,5.41 19.58,3 16.5,3Z","mdi:help":"M10,19H13V22H10V19M12,2C17.35,2.22 19.68,7.62 16.5,11.67C15.67,12.67 14.33,13.33 13.67,14.17C13,15 13,16 13,17H10C10,15.33 10,13.92 10.67,12.92C11.33,11.92 12.67,11.33 13.5,10.67C15.92,8.43 15.32,5.26 12,5A3,3 0 0,0 9,8H6A6,6 0 0,1 12,2Z","mdi:help-circle-outline":"M11,18H13V16H11V18M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,6A4,4 0 0,0 8,10H10A2,2 0 0,1 12,8A2,2 0 0,1 14,10C14,12 11,11.75 11,15H13C13,12.75 16,12.5 16,10A4,4 0 0,0 12,6Z","mdi:home-group":"M17,16H15V22H12V17H8V22H5V16H3L10,10L17,16M6,2L10,6H9V9H7V6H5V9H3V6H2L6,2M18,3L23,8H22V12H19V9H17V12H15.34L14,10.87V8H13L18,3Z","mdi:information":"M13,9H11V7H13M13,17H11V11H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z","mdi:lock":"M12,17A2,2 0 0,0 14,15C14,13.89 13.1,13 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V10C4,8.89 4.9,8 6,8H7V6A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,3A3,3 0 0,0 9,6V8H15V6A3,3 0 0,0 12,3Z","mdi:lock-open":"M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6C4.89,22 4,21.1 4,20V10A2,2 0 0,1 6,8H15V6A3,3 0 0,0 12,3A3,3 0 0,0 9,6H7A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,17A2,2 0 0,0 14,15A2,2 0 0,0 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17Z","mdi:menu":"M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z","mdi:monitor-eye":"M3 4V16H21V4H3M3 2H21C22.1 2 23 2.89 23 4V16C23 16.53 22.79 17.04 22.41 17.41C22.04 17.79 21.53 18 21 18H14V20H16V22H8V20H10V18H3C2.47 18 1.96 17.79 1.59 17.41C1.21 17.04 1 16.53 1 16V4C1 2.89 1.89 2 3 2M10.84 8.93C11.15 8.63 11.57 8.45 12 8.45C12.43 8.46 12.85 8.63 13.16 8.94C13.46 9.24 13.64 9.66 13.64 10.09C13.64 10.53 13.46 10.94 13.16 11.25C12.85 11.56 12.43 11.73 12 11.73C11.57 11.73 11.15 11.55 10.84 11.25C10.54 10.94 10.36 10.53 10.36 10.09C10.36 9.66 10.54 9.24 10.84 8.93M10.07 12C10.58 12.53 11.28 12.82 12 12.82C12.72 12.82 13.42 12.53 13.93 12C14.44 11.5 14.73 10.81 14.73 10.09C14.73 9.37 14.44 8.67 13.93 8.16C13.42 7.65 12.72 7.36 12 7.36C11.28 7.36 10.58 7.65 10.07 8.16C9.56 8.67 9.27 9.37 9.27 10.09C9.27 10.81 9.56 11.5 10.07 12M6 10.09C6.94 7.7 9.27 6 12 6C14.73 6 17.06 7.7 18 10.09C17.06 12.5 14.73 14.18 12 14.18C9.27 14.18 6.94 12.5 6 10.09Z","mdi:router-wireless":"M20.2,5.9L21,5.1C19.6,3.7 17.8,3 16,3C14.2,3 12.4,3.7 11,5.1L11.8,5.9C13,4.8 14.5,4.2 16,4.2C17.5,4.2 19,4.8 20.2,5.9M19.3,6.7C18.4,5.8 17.2,5.3 16,5.3C14.8,5.3 13.6,5.8 12.7,6.7L13.5,7.5C14.2,6.8 15.1,6.5 16,6.5C16.9,6.5 17.8,6.8 18.5,7.5L19.3,6.7M19,13H17V9H15V13H5A2,2 0 0,0 3,15V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V15A2,2 0 0,0 19,13M8,18H6V16H8V18M11.5,18H9.5V16H11.5V18M15,18H13V16H15V18Z","mdi:sort-descending":"M19 7H22L18 3L14 7H17V21H19M2 17H12V19H2M6 5V7H2V5M2 11H9V13H2V11Z","mdi:transmission-tower":"M8.28,5.45L6.5,4.55L7.76,2H16.23L17.5,4.55L15.72,5.44L15,4H9L8.28,5.45M18.62,8H14.09L13.3,5H10.7L9.91,8H5.38L4.1,10.55L5.89,11.44L6.62,10H17.38L18.1,11.45L19.89,10.56L18.62,8M17.77,22H15.7L15.46,21.1L12,15.9L8.53,21.1L8.3,22H6.23L9.12,11H11.19L10.83,12.35L12,14.1L13.16,12.35L12.81,11H14.88L17.77,22M11.4,15L10.5,13.65L9.32,18.13L11.4,15M14.68,18.12L13.5,13.64L12.6,15L14.68,18.12Z","mdi:view-dashboard":"M13,3V9H21V3M13,21H21V11H13M3,21H11V15H3M3,13H11V3H3V13Z"}),LI=new Set;class EI extends Nt{constructor(){super(...arguments),this.icon=""}render(){if(!this.icon)return yt;const t=PI[this.icon];return t?gt``:(e=this.icon,LI.has(e)||(LI.add(e),console.warn(`SPAN: unknown icon "${e}". Add it to MDI_PATHS in span-icon.ts.`)),yt);var e}}EI.styles=P` :host { display: inline-flex; align-items: center; @@ -128,11 +128,11 @@ var Rl={},Ol={};var zl,Hl=function(){function t(t,e,n){var i=this;this._sleepAft display: block; fill: currentColor; } - `,C([Ht({type:String})],BI.prototype,"icon",void 0);try{customElements.get("span-icon")||customElements.define("span-icon",BI)}catch{}class $I extends Nt{constructor(){super(...arguments),this.checked=!1,this.disabled=!1,this._enabledTabIndex="0",this._onActivate=t=>{if(this.disabled)return t.preventDefault(),void t.stopPropagation();this.checked=!this.checked,this.dispatchEvent(new Event("change",{bubbles:!0,composed:!0}))},this._onKeydown=t=>{" "!==t.key&&"Enter"!==t.key||(t.preventDefault(),this._onActivate(t))}}connectedCallback(){super.connectedCallback(),this._syncFocusable(),this.hasAttribute("role")||this.setAttribute("role","switch"),this.setAttribute("aria-checked",String(this.checked)),this.addEventListener("click",this._onActivate),this.addEventListener("keydown",this._onKeydown)}disconnectedCallback(){this.removeEventListener("click",this._onActivate),this.removeEventListener("keydown",this._onKeydown),super.disconnectedCallback()}updated(t){t.has("checked")&&this.setAttribute("aria-checked",String(this.checked)),t.has("disabled")&&(this.setAttribute("aria-disabled",String(this.disabled)),this._syncFocusable())}_syncFocusable(){const t=this.getAttribute("tabindex");if(this.disabled){if(null===t)return;this._enabledTabIndex=t,this.removeAttribute("tabindex")}else null===t&&this.setAttribute("tabindex",this._enabledTabIndex)}render(){return gt` + `,C([Ht({type:String})],EI.prototype,"icon",void 0);try{customElements.get("span-icon")||customElements.define("span-icon",EI)}catch{}class NI extends Nt{constructor(){super(...arguments),this.checked=!1,this.disabled=!1,this._enabledTabIndex="0",this._onActivate=t=>{if(this.disabled)return t.preventDefault(),void t.stopPropagation();this.checked=!this.checked,this.dispatchEvent(new Event("change",{bubbles:!0,composed:!0}))},this._onKeydown=t=>{" "!==t.key&&"Enter"!==t.key||(t.preventDefault(),this._onActivate(t))}}connectedCallback(){super.connectedCallback(),this._syncFocusable(),this.hasAttribute("role")||this.setAttribute("role","switch"),this.setAttribute("aria-checked",String(this.checked)),this.addEventListener("click",this._onActivate),this.addEventListener("keydown",this._onKeydown)}disconnectedCallback(){this.removeEventListener("click",this._onActivate),this.removeEventListener("keydown",this._onKeydown),super.disconnectedCallback()}updated(t){t.has("checked")&&this.setAttribute("aria-checked",String(this.checked)),t.has("disabled")&&(this.setAttribute("aria-disabled",String(this.disabled)),this._syncFocusable())}_syncFocusable(){const t=this.getAttribute("tabindex");if(this.disabled){if(null===t)return;this._enabledTabIndex=t,this.removeAttribute("tabindex")}else null===t&&this.setAttribute("tabindex",this._enabledTabIndex)}render(){return gt`
- `}}$I.styles=P` + `}}NI.styles=P` :host { --span-switch-track-w: 36px; --span-switch-track-h: 20px; @@ -234,10 +234,10 @@ var Rl={},Ol={};var zl,Hl=function(){function t(t,e,n){var i=this;this._sleepAft outline: var(--wa-focus-ring, 2px solid var(--ha-color-focus, var(--primary-color, #4dd9af))); outline-offset: var(--wa-focus-ring-offset, 2px); } - `,C([Ht({type:Boolean,reflect:!0})],$I.prototype,"checked",void 0),C([Ht({type:Boolean,reflect:!0})],$I.prototype,"disabled",void 0);try{customElements.get("span-switch")||customElements.define("span-switch",$I)}catch{}const FI=[{name:"Kitchen",watts:"120",path:"M0,28 L8,26 L16,24 L24,22 L32,25 L40,20 L48,18 L56,22 L64,19 L72,16 L80,18 L88,15 L96,17 L104,14 L112,16 L120,13"},{name:"Living Room",watts:"85",path:"M0,22 L8,24 L16,20 L24,26 L32,18 L40,22 L48,16 L56,20 L64,24 L72,18 L80,22 L88,20 L96,16 L104,22 L112,18 L120,20"},{name:"Master Bed",watts:"193",path:"M0,8 L8,10 L16,8 L24,12 L32,10 L40,8 L48,10 L56,8 L64,10 L72,8 L80,12 L88,10 L96,8 L104,10 L112,8 L120,10"},{name:"HVAC",watts:"64",path:"M0,30 L8,28 L16,26 L24,22 L32,18 L40,14 L48,18 L56,22 L64,26 L72,22 L80,18 L88,22 L96,26 L104,22 L112,18 L120,22"}];let VI=class extends Nt{constructor(){super(...arguments),this._config={},this._discovered=!1,this._discovering=!1,this._topology=null,this._activeTab="panel",this._panelDevice=null,this._positions=null,this._historyLoaded=!1,this._ctrl=new PA,this._listCtrl=new $A(this._ctrl),this._errorStore=new XA,this._areaSub=null,this._renameSub=null,this._reloadSub=null,this._ratingSub=null,this._topologySource=null,this._topologyRefresh=function(t){let e=null,n=!1;return async function i(){if(e)return n=!0,void await e.catch(()=>{});const r=(async()=>{try{await t()}finally{e=null,n&&(n=!1,await i())}})();e=r,await r}}(()=>this._refreshTopology()),this._beginTopologyEpoch=function(){let t=0;return()=>{t+=1;const e=t;return()=>t!==e}}(),this._tabBarCleanup=null}get _configEntryId(){return t=this._topology,e=this._panelDevice,t?.config_entry_id??e?.config_entry_id??null;var t,e}get _root(){const t=this.shadowRoot;if(!t)throw new Error("span-panel-card: shadow root is not available");return t}connectedCallback(){super.connectedCallback(),this._ctrl.startIntervals(this._root),this._discovered&&this._attachSubscriptions(!0)}disconnectedCallback(){this._ctrl.stopIntervals(),this._listCtrl.stop(),this._detachSubscriptions(),this._beginTopologyEpoch(),this._tabBarCleanup&&(this._tabBarCleanup(),this._tabBarCleanup=null),this._errorStore.dispose(),super.disconnectedCallback()}setConfig(t){this._detachSubscriptions(),this._beginTopologyEpoch(),this._errorStore.clear(),this._config=t,this._discovered=!1,this._discovering=!1,this._historyLoaded=!1,this._topology=null,this._topologySource=null,this._panelDevice=null,this._positions=null,this._activeTab="panel",this._ctrl.reset(),this._ctrl.setConfig(t),this._ctrl.errorStore=this._errorStore}getCardSize(){const t=this._topology?(e=this._topology,n=this._config,Nn(e,n)?2:0):0;var e,n;return(this._positions?Pe(this._positions):0)+3+t}static getConfigElement(){return document.createElement("span-panel-card-editor")}static getStubConfig(){return{device_id:"",history_days:0,history_hours:0,history_minutes:5,chart_metric:o,show_panel:!0,show_battery:!0,show_evse:!0,show_solar:!0}}render(){if(n(this.hass?.language),!this._config.device_id)return this._renderPreview();if(!this._discovered){const t=this._errorStore.hasPersistent("discovery-failed");return gt` + `,C([Ht({type:Boolean,reflect:!0})],NI.prototype,"checked",void 0),C([Ht({type:Boolean,reflect:!0})],NI.prototype,"disabled",void 0);try{customElements.get("span-switch")||customElements.define("span-switch",NI)}catch{}const RI=[{name:"Kitchen",watts:"120",path:"M0,28 L8,26 L16,24 L24,22 L32,25 L40,20 L48,18 L56,22 L64,19 L72,16 L80,18 L88,15 L96,17 L104,14 L112,16 L120,13"},{name:"Living Room",watts:"85",path:"M0,22 L8,24 L16,20 L24,26 L32,18 L40,22 L48,16 L56,20 L64,24 L72,18 L80,22 L88,20 L96,16 L104,22 L112,18 L120,20"},{name:"Master Bed",watts:"193",path:"M0,8 L8,10 L16,8 L24,12 L32,10 L40,8 L48,10 L56,8 L64,10 L72,8 L80,12 L88,10 L96,8 L104,10 L112,8 L120,10"},{name:"HVAC",watts:"64",path:"M0,30 L8,28 L16,26 L24,22 L32,18 L40,14 L48,18 L56,22 L64,26 L72,22 L80,18 L88,22 L96,26 L104,22 L112,18 L120,22"}];let OI=class extends Nt{constructor(){super(...arguments),this._config={},this._discovered=!1,this._discovering=!1,this._awaitingLoad=!1,this._discoveryFailed=!1,this._topology=null,this._activeTab="panel",this._positions=null,this._historyLoaded=!1,this._ctrl=new IA,this._listCtrl=new HA(this._ctrl),this._errorStore=new YA,this._areaSub=null,this._renameSub=null,this._reloadSub=null,this._ratingSub=null,this._loadWait=null,this._topologyRefresh=GA(()=>this._refreshTopology()),this._askOnEntryLoad=function(t){let e=!1;return()=>{e||(e=!0,Promise.resolve().then(()=>{e=!1,t()}))}}(()=>{this._discoveryOnEntryLoad()}),this._discoveryOnEntryLoad=GA(async()=>{this._awaitingLoad&&await this._runDiscovery()}),this._beginDiscoveryRun=XA(),this._beginTopologyEpoch=XA(),this._tabBarCleanup=null}get _configEntryId(){return this._topology?.config_entry_id??null}get _root(){const t=this.shadowRoot;if(!t)throw new Error("span-panel-card: shadow root is not available");return t}connectedCallback(){super.connectedCallback(),this._ctrl.startIntervals(this._root),this._discovered?this._attachSubscriptions(!0):this._awaitingLoad?this._waitForEntryLoad():this._discoveryFailed&&this._reportDiscoveryFailed()}disconnectedCallback(){this._ctrl.stopIntervals(),this._listCtrl.stop(),this._detachSubscriptions(),this._beginTopologyEpoch(),this._tabBarCleanup&&(this._tabBarCleanup(),this._tabBarCleanup=null),this._errorStore.dispose(),super.disconnectedCallback()}setConfig(t){this._detachSubscriptions(),this._beginTopologyEpoch(),this._beginDiscoveryRun(),this._errorStore.clear(),this._config=t,this._discovered=!1,this._discovering=!1,this._awaitingLoad=!1,this._discoveryFailed=!1,this._historyLoaded=!1,this._topology=null,this._positions=null,this._activeTab="panel",this._ctrl.reset(),this._ctrl.setConfig(t),this._ctrl.errorStore=this._errorStore}getCardSize(){const t=this._topology?(e=this._topology,n=this._config,Nn(e,n)?2:0):0;var e,n;return(this._positions?Pe(this._positions):0)+3+t}static getConfigElement(){return document.createElement("span-panel-card-editor")}static getStubConfig(){return{device_id:"",history_days:0,history_hours:0,history_minutes:5,chart_metric:o,show_panel:!0,show_battery:!0,show_evse:!0,show_solar:!0}}render(){if(n(this.hass?.language),!this._config.device_id)return this._renderPreview();if(!this._discovered){const t=this._awaitingLoad?i("card.waiting_for_load"):i("card.connecting");return gt`
- ${t?yt:gt`
${Ft(i("card.connecting"))}
`} + ${this._discoveryFailed?yt:gt`
${t}
`}
`}return gt`
- `}updated(t){if(t.has("hass")&&this.hass&&(n(this.hass.language),this._ctrl.hass=this.hass,this._errorStore.updateHass(this.hass),this._config.device_id))if(this._discovered||this._discovering){if(this._discovered){this._ctrl.recordSamples(),this._ctrl.updateDOM(this._root),this._syncRatingSubscription();const t=this._root.querySelector("span-side-panel");t&&(t.hass=this.hass,t.errorStore=this._errorStore)}this._discovered&&"panel"!==this._activeTab&&this._topology&&this._listCtrl.updateCollapsedRows(this._root,this.hass,this._topology,this._config)}else this._startDiscovery()}async _startDiscovery(){this._discovering||(this._discovering=!0,await this._discoverTopology(),this._errorStore.hasPersistent("discovery-failed")?this._discovering=!1:(this._discovered=!0,this._discovering=!1,this._ctrl.init(this._topology,this._config,this.hass,this._configEntryId),this.isConnected&&this._attachSubscriptions(!1),await this.updateComplete,this._populateCardContent(),this._loadHistory(),this._ctrl.monitoringCache.fetch(this.hass,this._configEntryId).then(()=>{this._discovered&&this._ctrl.updateDOM(this._root)})))}_adoptTopology(t){this._topology=t.topology,this._panelDevice=t.panelDevice,this._positions=De(t.topology,t.panelSize)}async _discoverTopology(){if(!this.hass)return;const t=new Ue(this._errorStore);try{return this._adoptTopology(await YA(this.hass,this._config.device_id,t)),void(this._topologySource="panel_topology")}catch(t){console.error("SPAN Panel: topology fetch failed, falling back to entity discovery",t)}try{this._adoptTopology(await oI(this.hass,this._config.device_id,t)),this._topologySource="entity_fallback"}catch(t){console.error("SPAN Panel: fallback discovery also failed",t),this._errorStore.add({key:"discovery-failed",level:"error",message:i("error.discovery_failed"),persistent:!0,retryFn:()=>{this._errorStore.remove("discovery-failed"),this._startDiscovery()}})}}async _refreshTopology(){const t=this._topologySource;if(!this.hass||!this._discovered||!t)return;const e=this._beginTopologyEpoch();let n;try{n="panel_topology"===t?await YA(this.hass,this._config.device_id,null):await oI(this.hass,this._config.device_id,null)}catch(t){return void console.warn("SPAN Panel: topology refresh failed; keeping the current topology:",ee(t))}if(e())return;if(!n.topology)return void console.warn("SPAN Panel: topology refresh found no panel; keeping the current topology");if(sI(n.topology,this._topology))return;const i=(r=n.topology,!(null!==(o=this._topology)&&sI(cI(r),cI(o))));var r,o;this._adoptTopology(n),this._ctrl.init(this._topology,this._config,this.hass,this._configEntryId),this._ctrl.refreshCircuitControlAccess(this._root,this._configEntryId,n.topology),i&&(this._watchPanelStatus(),this._populateCardContent()),this._ctrl.updateDOM(this._root)}_attachSubscriptions(t){this._detachSubscriptions(),this.hass&&(this._areaSub=async function(t,e,n,r){const o=t.connection;if(!o)return()=>{};const a=async()=>{const o=e();if(o)try{const e=new Map;for(const[t,n]of Object.entries(o.circuits))e.set(t,n.area);await VA(t,o);for(const[t,i]of Object.entries(o.circuits))if(i.area!==e.get(t))return void n()}catch(t){console.warn("[span-panel] area registry update failed:",t),r?.add({key:"fetch:areas",level:"warning",message:i("error.areas_failed"),persistent:!1})}},s=await Promise.all(FA.map(t=>o.subscribeEvents(a,t)));return()=>{for(const t of s)t()}}(this.hass,()=>this._topology,()=>{"area"===this._activeTab&&this._discovered&&this._populateCardContent()},this._errorStore).catch(t=>(console.warn("SPAN Panel: area subscription failed",t),this._errorStore.add({key:"subscribe:area",level:"warning",message:i("error.areas_failed"),persistent:!1}),()=>{})),this._renameSub=jA(this.hass,()=>this._topology,()=>{this._topologyRefresh()}).catch(t=>(console.warn("SPAN Panel: device rename subscription failed",t),()=>{})),this._reloadSub=async function(t,e,n,{initialIsReseed:i}){const r=t.connection;if(!r)return async()=>{};const o=new Map;let a=!1;return r.subscribeMessage(t=>{if(t.every(t=>null===t.type)){const r=a||i;a=!0,o.clear();for(const{entry:i}of t)e(i)&&(o.set(i.entry_id,i.state),r&&i.state===qA&&n(i.entry_id));return}for(const{type:i,entry:r}of t){if(!e(r))continue;if("removed"===i){o.delete(r.entry_id);continue}const t=o.get(r.entry_id);o.set(r.entry_id,r.state),"updated"===i&&r.state===qA&&t!==qA&&n(r.entry_id)}},{type:"config_entries/subscribe",type_filter:["device"]})}(this.hass,t=>t.entry_id===this._configEntryId,()=>{this._topologyRefresh()},{initialIsReseed:t}).catch(t=>(console.warn("SPAN Panel: config entry subscription failed",t),async()=>{})),this._syncRatingSubscription(),this._watchPanelStatus())}_syncRatingSubscription(){if(t=this.hass,!0!==t?.user?.is_admin)return void this._dropRatingSubscription();var t;const e=this._configEntryId;this.isConnected&&!this._ratingSub&&"panel_topology"===this._topologySource&&e&&(this._ratingSub=GA(this.hass,e,()=>{this._onRatingChanged()}).catch(t=>(console.warn("SPAN Panel: monitoring rating subscription failed",t),()=>{})))}_dropRatingSubscription(){const t=this._ratingSub;this._ratingSub=null,t?.then(t=>t())}async _onRatingChanged(){this.hass&&this._discovered&&(this._ctrl.monitoringCache.invalidate(),await this._ctrl.monitoringCache.fetch(this.hass,this._configEntryId),await this._topologyRefresh())}_detachSubscriptions(){const t=this._areaSub,e=this._renameSub,n=this._reloadSub;this._areaSub=null,this._renameSub=null,this._reloadSub=null,t?.then(t=>t()),e?.then(t=>t()),n?.then(t=>t()),this._dropRatingSubscription()}_watchPanelStatus(){const t=this._topology?.panel_entities?.panel_status;t&&this.hass&&(this._errorStore.watchPanelStatus(t),this._errorStore.updateHass(this.hass))}async _loadHistory(){if(!this._historyLoaded&&this._topology&&this.hass){this._historyLoaded=!0,await this._ctrl.fetchAndBuildHorizonMaps();try{await this._ctrl.loadHistory(),this._ctrl.updateDOM(this._root)}catch(t){console.warn("SPAN Panel: history fetch failed, charts will populate live",t)}}}_populateCardContent(){const t=this._root.querySelector("#card-content");if(!(t&&this.hass&&this._topology&&this._positions))return;const e=this._root.querySelector("#card-tabs");if(e){const t=[{id:"panel",label:i("tab.by_panel"),icon:"mdi:view-dashboard"},{id:"activity",label:i("tab.by_activity"),icon:"mdi:sort-descending"},{id:"area",label:i("tab.by_area"),icon:"mdi:home-group"}];e.innerHTML=(n=t,r=this._activeTab,o=this._config.tab_style??"text",`
${n.map(t=>{const e=t.id===r?" active":"",n=Ft(t.id);return"icon"===o?``:``}).join("")}
`),this._tabBarCleanup&&(this._tabBarCleanup(),this._tabBarCleanup=null),this._tabBarCleanup=function(t,e){const n=t=>{const n=t.target.closest(".shared-tab");if(n){const t=n.dataset.tab;t&&e(t)}};return t.addEventListener("click",n),()=>{t.removeEventListener("click",n)}}(e,t=>{["panel","activity","area"].includes(t)&&(this._activeTab=t,this._listCtrl.stop(),this._populateCardContent())})}var n,r,o;if("panel"===this._activeTab){const e=Pe(this._positions),n=Te(this._topology,this._config),r=this._ctrl.monitoringCache.status,o=function(t){if(!t)return"";const e=Object.values(t.circuits??{}),n=Object.values(t.mains??{}),r=new Map(Object.entries(t.circuits??{}).map(([t,e])=>[void 0!==e.point_id?`point:${e.point_id}`:`entry:${t}`,e])),o=[...r.values(),...n],a=o.flatMap(t=>null!=t.utilization_pct?[Qe(t.utilization_pct,t)]:[]),s=a.filter(t=>"warning"===t).length,l=a.filter(t=>"alert"===t).length,c=o.filter(t=>t.has_override).length;return`\n
\n ✓ ${i("status.monitoring")} · ${e.length} ${i("status.circuits")} · ${n.length} ${i("status.mains")}\n \n ${s>0?`${s} ${i(s>1?"status.warnings":"status.warning")}`:""}\n ${l>0?`${l} ${i(l>1?"status.alerts":"status.alert")}`:""}\n ${c>0?`${c} ${i(c>1?"status.overrides":"status.override")}`:""}\n \n
\n `}(r),a=function(t,e,n,i,r){const o=new Map,a=new Set;for(const{uuid:e,circuit:n,members:i}of $e(t)){if(Ie(n))continue;const t=n.tabs;if(!t||0===t.length)continue;const r=Math.min(...t),s=1===t.length?"single":Ne(t)??"single";o.set(r,{uuid:e,circuit:n,members:i,layout:s});for(const e of t)a.add(e)}const s=new Set,l=new Set;for(const[t,e]of o)if("col-span"===e.layout){const n=e.circuit.tabs,i=Le(Math.max(...n));0===Ee(t)?s.add(i):l.add(i)}function c(e){return{monInfo:Ze(r,e.circuit),sheddingPriority:wn(e.circuit,n),access:ge(t,e.uuid)}}const u=t=>t>=e.first&&t<=e.last,d=Le(e.first),h=Le(e.last);let p="";for(let t=d;t<=h;t++){const e=t-d+1,r=2*t-1,h=2*t,f=o.get(r),g=o.get(h),m=u(r)?`
${r}
`:"",v=u(h)?`
${h}
`:"";if(p+=m,f&&"row-span"===f.layout){const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=Dn(f.uuid,f.circuit,e,"2 / 5","row-span",n,i,t,r,o,f.members),p+=v;continue}if(!s.has(t))if(!f||"col-span"!==f.layout&&"single"!==f.layout)!a.has(r)&&u(r)&&(p+=Pn(e,"2"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=Dn(f.uuid,f.circuit,e,"2",f.layout,n,i,t,r,o,f.members)}if(!l.has(t))if(!g||"col-span"!==g.layout&&"single"!==g.layout)!a.has(h)&&u(h)&&(p+=Pn(e,"4"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(g);p+=Dn(g.uuid,g.circuit,e,"4",g.layout,n,i,t,r,o,g.members)}p+=v}return p}(this._topology,this._positions,this.hass,this._config,r),s=ti(this._topology,this.hass,this._config,{showFavorites:this._ctrl.showFavorites}),l=function(t,e,n){if(!Nn(t,n))return"";const r=En(t).map(([t,r])=>`\n
\n ${Ft(r.name||i("grid.unknown"))}\n ${On(r,e,n)}\n
`).join("");return`\n
\n
${Ft(i("meters.title"))}
\n ${r}\n
\n `}(this._topology,this.hass,this._config);t.innerHTML=`\n ${n}\n ${o}\n ${s?`
${s}
`:""}\n ${l}\n ${!1!==this._config.show_panel?`
${a}
`:""}\n `;const c=t.querySelector(".slide-confirm");if(c){const t=this._root.querySelector(".span-card");this._ctrl.bindSlideConfirm(c,t),t&&t.classList.add("switches-disabled")}const u=this._root.querySelector("span-side-panel");u&&(u.hass=this.hass,u.errorStore=this._errorStore),this._ctrl.recordSamples(),this._ctrl.updateDOM(this._root),this._ctrl.setupResizeObserver(this._root,this._root.querySelector(".span-card"))}else if("activity"===this._activeTab){t.innerHTML="";const e=Te(this._topology,this._config);this._listCtrl.setColumns(Wt()),this._listCtrl.renderActivityView(t,this.hass,this._topology,this._config,this._ctrl.monitoringCache.status,e),this._ctrl.updateDOM(this._root)}else if("area"===this._activeTab){t.innerHTML="";const e=Te(this._topology,this._config);this._listCtrl.setColumns(Wt()),this._listCtrl.renderAreaView(t,this.hass,this._topology,this._config,this._ctrl.monitoringCache.status,e),this._ctrl.updateDOM(this._root)}}_onCardClick(t){if("panel"!==this._activeTab)return;const e=t.target;if(!e)return;const n=e.closest(".unit-btn");if(n)return void this._onUnitToggle(n);if(e.closest(".toggle-pill"))return void this._ctrl.onToggleClick(t,this._root);e.closest(".gear-icon")&&this._ctrl.onGearClick(t,this._root)}async _onUnitToggle(t){const e=t.dataset.unit;e&&e!==(this._config.chart_metric??"power")&&(this._config={...this._config,chart_metric:e},this._ctrl.setConfig(this._config),this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:this._config},bubbles:!0,composed:!0})),this._ctrl.powerHistory.clear(),this._historyLoaded=!1,this._populateCardContent(),await this._loadHistory(),this._ctrl.updateDOM(this._root))}async _onListUnitChanged(t){const e=t.detail;e&&e!==(this._config.chart_metric??"power")&&(this._config={...this._config,chart_metric:e},this._ctrl.setConfig(this._config),this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:this._config},bubbles:!0,composed:!0})),this._ctrl.powerHistory.clear(),this._historyLoaded=!1,this._populateCardContent(),await this._loadHistory(),this._ctrl.updateDOM(this._root))}_onGraphSettingsChanged(){this._ctrl.onGraphSettingsChanged(this._root)}_onListColumnsChanged(t){const e=t.detail;"number"!=typeof e||1!==e&&2!==e&&3!==e||"activity"!==this._activeTab&&"area"!==this._activeTab||this._populateCardContent()}_onSidePanelClosed(){this._ctrl.monitoringCache.invalidate(),this._ctrl.graphSettingsCache.invalidate()}_renderPreview(){const t=FI.map(t=>gt` + `}updated(t){if(t.has("hass")&&this.hass&&(n(this.hass.language),this._ctrl.hass=this.hass,this._errorStore.updateHass(this.hass),this._config.device_id))if(this._discovered||this._discovering||this._discoveryFailed){if(this._discovered){this._ctrl.recordSamples(),this._ctrl.updateDOM(this._root),this._syncRatingSubscription();const t=this._root.querySelector("span-side-panel");t&&(t.hass=this.hass,t.errorStore=this._errorStore)}this._discovered&&"panel"!==this._activeTab&&this._topology&&this._listCtrl.updateCollapsedRows(this._root,this.hass,this._topology,this._config)}else this._startDiscovery()}async _startDiscovery(){this._discovering||(this._discovering=!0,await this._runDiscovery())}async _runDiscovery(){const t=this.hass;if(!t)return void(this._discovering=!1);const e=this._beginDiscoveryRun(),n=new Ue(this._errorStore,{passThrough:QA});let i;try{i=await ZA(t,this._config.device_id,n)}catch(t){if(e())return;return QA(t)?void this._awaitEntryLoad():(console.error("SPAN Panel: topology fetch failed",t),void this._failDiscovery())}e()||(this._endEntryLoadWait(),this._adoptTopology(i),this._discovered=!0,this._discovering=!1,this._ctrl.init(this._topology,this._config,this.hass,this._configEntryId),this.isConnected&&this._attachSubscriptions(!1),await this.updateComplete,this._populateCardContent(),this._loadHistory(),this._ctrl.monitoringCache.fetch(this.hass,this._configEntryId).then(()=>{this._discovered&&this._ctrl.updateDOM(this._root)}))}_adoptTopology(t){this._topology=t.topology,this._positions=De(t.topology,t.panelSize)}_failDiscovery(){this._beginDiscoveryRun(),this._endEntryLoadWait(),this._discovering=!1,this._discoveryFailed=!0,this._reportDiscoveryFailed()}_reportDiscoveryFailed(){this._errorStore.add({key:"discovery-failed",level:"error",message:i("error.discovery_failed"),persistent:!0,retryFn:()=>this._retryDiscovery()})}_retryDiscovery(){this._errorStore.remove("discovery-failed"),this._discoveryFailed=!1,this._startDiscovery()}_awaitEntryLoad(){this._awaitingLoad=!0,this.isConnected&&!this._loadWait&&this._waitForEntryLoad()}_waitForEntryLoad(){this._dropEntryLoadWait();const t=this._config.device_id;if(!this.hass||!t)return;const e=JA(this.hass,t,()=>{this._loadWait===e&&this._askOnEntryLoad()}).catch(t=>(console.warn("SPAN Panel: config entry subscription failed",t),this._loadWait===e&&this._failDiscovery(),async()=>{}));this._loadWait=e}_endEntryLoadWait(){this._awaitingLoad=!1,this._dropEntryLoadWait()}_dropEntryLoadWait(){const t=this._loadWait;this._loadWait=null,t?.then(t=>t())}async _refreshTopology(){if(!this.hass||!this._discovered)return;const t=this._beginTopologyEpoch();let e;try{e=await ZA(this.hass,this._config.device_id,null)}catch(t){return void console.warn("SPAN Panel: topology refresh failed; keeping the current topology:",ee(t))}if(t())return;if(eI(e.topology,this._topology))return;const n=(i=e.topology,!(null!==(r=this._topology)&&eI(iI(i),iI(r))));var i,r;this._adoptTopology(e),this._ctrl.init(this._topology,this._config,this.hass,this._configEntryId),this._ctrl.refreshCircuitControlAccess(this._root,this._configEntryId,e.topology),n&&(this._watchPanelStatus(),this._populateCardContent()),this._ctrl.updateDOM(this._root)}_attachSubscriptions(t){this._detachSubscriptions(),this.hass&&(this._areaSub=async function(t,e,n,r){const o=t.connection;if(!o)return()=>{};const a=async()=>{const o=e();if(o)try{const e=new Map;for(const[t,n]of Object.entries(o.circuits))e.set(t,n.area);await FA(t,o);for(const[t,i]of Object.entries(o.circuits))if(i.area!==e.get(t))return void n()}catch(t){console.warn("[span-panel] area registry update failed:",t),r?.add({key:"fetch:areas",level:"warning",message:i("error.areas_failed"),persistent:!1})}},s=await Promise.all(BA.map(t=>o.subscribeEvents(a,t)));return()=>{for(const t of s)t()}}(this.hass,()=>this._topology,()=>{"area"===this._activeTab&&this._discovered&&this._populateCardContent()},this._errorStore).catch(t=>(console.warn("SPAN Panel: area subscription failed",t),this._errorStore.add({key:"subscribe:area",level:"warning",message:i("error.areas_failed"),persistent:!1}),()=>{})),this._renameSub=VA(this.hass,()=>this._topology,()=>{this._topologyRefresh()}).catch(t=>(console.warn("SPAN Panel: device rename subscription failed",t),()=>{})),this._reloadSub=jA(this.hass,t=>t.entry_id===this._configEntryId,()=>{this._topologyRefresh()},{initialIsReseed:t}).catch(t=>(console.warn("SPAN Panel: config entry subscription failed",t),async()=>{})),this._syncRatingSubscription(),this._watchPanelStatus())}_syncRatingSubscription(){if(t=this.hass,!0!==t?.user?.is_admin)return void this._dropRatingSubscription();var t;const e=this._configEntryId;this.isConnected&&!this._ratingSub&&e&&(this._ratingSub=UA(this.hass,e,()=>{this._onRatingChanged()}).catch(t=>(console.warn("SPAN Panel: monitoring rating subscription failed",t),()=>{})))}_dropRatingSubscription(){const t=this._ratingSub;this._ratingSub=null,t?.then(t=>t())}async _onRatingChanged(){this.hass&&this._discovered&&(this._ctrl.monitoringCache.invalidate(),await this._ctrl.monitoringCache.fetch(this.hass,this._configEntryId),await this._topologyRefresh())}_detachSubscriptions(){const t=this._areaSub,e=this._renameSub,n=this._reloadSub;this._areaSub=null,this._renameSub=null,this._reloadSub=null,t?.then(t=>t()),e?.then(t=>t()),n?.then(t=>t()),this._dropRatingSubscription(),this._dropEntryLoadWait()}_watchPanelStatus(){const t=this._topology?.panel_entities?.panel_status;t&&this.hass&&(this._errorStore.watchPanelStatus(t),this._errorStore.updateHass(this.hass))}async _loadHistory(){if(!this._historyLoaded&&this._topology&&this.hass){this._historyLoaded=!0,await this._ctrl.fetchAndBuildHorizonMaps();try{await this._ctrl.loadHistory(),this._ctrl.updateDOM(this._root)}catch(t){console.warn("SPAN Panel: history fetch failed, charts will populate live",t)}}}_populateCardContent(){const t=this._root.querySelector("#card-content");if(!(t&&this.hass&&this._topology&&this._positions))return;const e=this._root.querySelector("#card-tabs");if(e){const t=[{id:"panel",label:i("tab.by_panel"),icon:"mdi:view-dashboard"},{id:"activity",label:i("tab.by_activity"),icon:"mdi:sort-descending"},{id:"area",label:i("tab.by_area"),icon:"mdi:home-group"}];e.innerHTML=(n=t,r=this._activeTab,o=this._config.tab_style??"text",`
${n.map(t=>{const e=t.id===r?" active":"",n=jt(t.id);return"icon"===o?``:``}).join("")}
`),this._tabBarCleanup&&(this._tabBarCleanup(),this._tabBarCleanup=null),this._tabBarCleanup=function(t,e){const n=t=>{const n=t.target.closest(".shared-tab");if(n){const t=n.dataset.tab;t&&e(t)}};return t.addEventListener("click",n),()=>{t.removeEventListener("click",n)}}(e,t=>{["panel","activity","area"].includes(t)&&(this._activeTab=t,this._listCtrl.stop(),this._populateCardContent())})}var n,r,o;if("panel"===this._activeTab){const e=Pe(this._positions),n=Te(this._topology,this._config),r=this._ctrl.monitoringCache.status,o=function(t){if(!t)return"";const e=Object.values(t.circuits??{}),n=Object.values(t.mains??{}),r=new Map(Object.entries(t.circuits??{}).map(([t,e])=>[void 0!==e.point_id?`point:${e.point_id}`:`entry:${t}`,e])),o=[...r.values(),...n],a=o.flatMap(t=>null!=t.utilization_pct?[Qe(t.utilization_pct,t)]:[]),s=a.filter(t=>"warning"===t).length,l=a.filter(t=>"alert"===t).length,c=o.filter(t=>t.has_override).length;return`\n
\n ✓ ${i("status.monitoring")} · ${e.length} ${i("status.circuits")} · ${n.length} ${i("status.mains")}\n \n ${s>0?`${s} ${i(s>1?"status.warnings":"status.warning")}`:""}\n ${l>0?`${l} ${i(l>1?"status.alerts":"status.alert")}`:""}\n ${c>0?`${c} ${i(c>1?"status.overrides":"status.override")}`:""}\n \n
\n `}(r),a=function(t,e,n,i,r){const o=new Map,a=new Set;for(const{uuid:e,circuit:n,members:i}of Fe(t)){if(Ie(n))continue;const t=n.tabs;if(!t||0===t.length)continue;const r=Math.min(...t),s=1===t.length?"single":Ne(t)??"single";o.set(r,{uuid:e,circuit:n,members:i,layout:s});for(const e of t)a.add(e)}const s=new Set,l=new Set;for(const[t,e]of o)if("col-span"===e.layout){const n=e.circuit.tabs,i=Le(Math.max(...n));0===Ee(t)?s.add(i):l.add(i)}function c(e){return{monInfo:Ze(r,e.circuit),sheddingPriority:wn(e.circuit,n),access:ge(t,e.uuid)}}const u=t=>t>=e.first&&t<=e.last,d=Le(e.first),h=Le(e.last);let p="";for(let t=d;t<=h;t++){const e=t-d+1,r=2*t-1,h=2*t,f=o.get(r),g=o.get(h),m=u(r)?`
${r}
`:"",v=u(h)?`
${h}
`:"";if(p+=m,f&&"row-span"===f.layout){const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=Dn(f.uuid,f.circuit,e,"2 / 5","row-span",n,i,t,r,o,f.members),p+=v;continue}if(!s.has(t))if(!f||"col-span"!==f.layout&&"single"!==f.layout)!a.has(r)&&u(r)&&(p+=Pn(e,"2"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=Dn(f.uuid,f.circuit,e,"2",f.layout,n,i,t,r,o,f.members)}if(!l.has(t))if(!g||"col-span"!==g.layout&&"single"!==g.layout)!a.has(h)&&u(h)&&(p+=Pn(e,"4"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(g);p+=Dn(g.uuid,g.circuit,e,"4",g.layout,n,i,t,r,o,g.members)}p+=v}return p}(this._topology,this._positions,this.hass,this._config,r),s=Qn(this._topology,this.hass,this._config,{showFavorites:this._ctrl.showFavorites}),l=function(t,e,n){if(!Nn(t,n))return"";const r=En(t).map(([t,r])=>`\n
\n ${jt(r.name||i("grid.unknown"))}\n ${On(r,e,n)}\n
`).join("");return`\n
\n
${jt(i("meters.title"))}
\n ${r}\n
\n `}(this._topology,this.hass,this._config);t.innerHTML=`\n ${n}\n ${o}\n ${s?`
${s}
`:""}\n ${l}\n ${!1!==this._config.show_panel?`
${a}
`:""}\n `;const c=t.querySelector(".slide-confirm");if(c){const t=this._root.querySelector(".span-card");this._ctrl.bindSlideConfirm(c,t),t&&t.classList.add("switches-disabled")}const u=this._root.querySelector("span-side-panel");u&&(u.hass=this.hass,u.errorStore=this._errorStore),this._ctrl.recordSamples(),this._ctrl.updateDOM(this._root),this._ctrl.setupResizeObserver(this._root,this._root.querySelector(".span-card"))}else if("activity"===this._activeTab){t.innerHTML="";const e=Te(this._topology,this._config);this._listCtrl.setColumns($t()),this._listCtrl.renderActivityView(t,this.hass,this._topology,this._config,this._ctrl.monitoringCache.status,e),this._ctrl.updateDOM(this._root)}else if("area"===this._activeTab){t.innerHTML="";const e=Te(this._topology,this._config);this._listCtrl.setColumns($t()),this._listCtrl.renderAreaView(t,this.hass,this._topology,this._config,this._ctrl.monitoringCache.status,e),this._ctrl.updateDOM(this._root)}}_onCardClick(t){if("panel"!==this._activeTab)return;const e=t.target;if(!e)return;const n=e.closest(".unit-btn");if(n)return void this._onUnitToggle(n);if(e.closest(".toggle-pill"))return void this._ctrl.onToggleClick(t,this._root);e.closest(".gear-icon")&&this._ctrl.onGearClick(t,this._root)}async _onUnitToggle(t){const e=t.dataset.unit;e&&e!==(this._config.chart_metric??"power")&&(this._config={...this._config,chart_metric:e},this._ctrl.setConfig(this._config),this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:this._config},bubbles:!0,composed:!0})),this._ctrl.powerHistory.clear(),this._historyLoaded=!1,this._populateCardContent(),await this._loadHistory(),this._ctrl.updateDOM(this._root))}async _onListUnitChanged(t){const e=t.detail;e&&e!==(this._config.chart_metric??"power")&&(this._config={...this._config,chart_metric:e},this._ctrl.setConfig(this._config),this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:this._config},bubbles:!0,composed:!0})),this._ctrl.powerHistory.clear(),this._historyLoaded=!1,this._populateCardContent(),await this._loadHistory(),this._ctrl.updateDOM(this._root))}_onGraphSettingsChanged(){this._ctrl.onGraphSettingsChanged(this._root)}_onListColumnsChanged(t){const e=t.detail;"number"!=typeof e||1!==e&&2!==e&&3!==e||"activity"!==this._activeTab&&"area"!==this._activeTab||this._populateCardContent()}_onSidePanelClosed(){this._ctrl.monitoringCache.invalidate(),this._ctrl.graphSettingsCache.invalidate()}_renderPreview(){const t=RI.map(t=>gt`
${t.name} @@ -276,4 +276,4 @@ var Rl={},Ol={};var zl,Hl=function(){function t(t,e,n){var i=this;this._sleepAft
${i("card.no_device")}
- `}};function WI(t){const e=new Set;for(const n of Object.values(t.entities??{})){if(n.platform!==l||!n.device_id)continue;const i=t.devices?.[n.device_id]?.config_entry_id;i&&e.add(i)}return e}function jI(t,e){return Yn(Object.entries(t)).filter(([,t])=>t.type===e).map(([t,e])=>{const n=jn(e),i=e.name??"",r=Object.entries(e.entities??{}).filter(([t])=>!n.has(t)).map(([t,e])=>{let n=e.original_name??t;return i&&n.startsWith(i+" ")&&(n=n.slice(i.length+1)),{entityId:t,label:n}});return{devId:t,name:i||t,entities:r}})}VI.styles=D('\n :host {\n --span-accent: var(--primary-color, #4dd9af);\n }\n\n /* Card shell — replaces . Theme variables (--ha-card-*) are\n stable HA contracts (not the deprecated component APIs flagged by the\n 2026.4 frontend blog), so they stay in place to keep visual parity\n with the rest of HA\'s dashboards. */\n .span-card {\n display: block;\n padding: 24px;\n background: var(--card-background-color, #1c1c1c);\n color: var(--primary-text-color, #e0e0e0);\n border-radius: var(--ha-card-border-radius, 12px);\n border: var(--ha-card-border-width, 1px) solid var(--ha-card-border-color, var(--divider-color, #333));\n box-shadow: var(--ha-card-box-shadow, none);\n }\n\n .panel-header {\n display: flex;\n flex-wrap: wrap;\n justify-content: space-between;\n align-items: flex-start;\n gap: 8px 16px;\n margin-bottom: 20px;\n padding-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n .header-left { flex: 1 1 300px; min-width: 0; }\n .header-center { flex: 0 0 auto; }\n .header-right { flex: 0 1 auto; min-width: 0; }\n\n .panel-identity {\n display: flex;\n align-items: center;\n flex-wrap: wrap;\n gap: 8px 12px;\n margin-bottom: 12px;\n }\n\n .panel-title {\n font-size: 1.8em;\n font-weight: 700;\n margin: 0;\n color: var(--primary-text-color, #fff);\n }\n\n .panel-serial {\n font-size: 0.85em;\n color: var(--secondary-text-color, #999);\n font-family: monospace;\n }\n\n .panel-stats {\n display: flex;\n flex-wrap: wrap;\n gap: 16px 32px;\n }\n\n /* Favorites view header: gear + slide-to-arm + right-anchored legend/W-A cluster. */\n .favorites-summary {\n padding: 8px 24px;\n border-bottom: 1px solid var(--divider-color, #e0e0e0);\n display: flex;\n align-items: center;\n gap: 12px;\n }\n /* Override the generic .gear-icon { margin-left: auto } rule so the\n favorites gear stays flush-left instead of floating to the right of\n the flex row (same idea as .panel-identity .panel-gear does for\n real-panel headers). */\n .favorites-summary .favorites-gear {\n margin-left: 0;\n }\n /* Right-anchored cluster wrapping the shedding legend + W/A unit toggle.\n margin-left:auto moved here from .favorites-summary-unit-toggle so the\n legend and toggle cluster together, matching the real-panel header\n layout. */\n .favorites-summary-right {\n margin-left: auto;\n display: flex;\n align-items: center;\n gap: 16px;\n }\n .favorites-subdevices-section {\n padding: 8px 16px 0;\n }\n\n /* Favorites view: responsive grid of per-contributing-panel status cards. */\n .favorites-panel-stats-grid {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));\n gap: 12px;\n padding: 12px 24px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n .favorites-panel-card {\n background: var(--secondary-background-color, rgba(255, 255, 255, 0.04));\n border: 1px solid var(--divider-color, #333);\n border-radius: 8px;\n padding: 10px 14px;\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n .favorites-panel-card-title {\n font-size: 0.85em;\n font-weight: 600;\n color: var(--primary-text-color);\n opacity: 0.85;\n }\n .favorites-panel-card .controls-note {\n margin: 2px 0 6px;\n }\n .favorites-panel-card .panel-stats {\n gap: 10px 20px;\n }\n .favorites-panel-card .stat-value {\n font-size: 1.15em;\n }\n\n .stat { display: flex; flex-direction: column; }\n .stat-label { font-size: 0.8em; color: var(--secondary-text-color, #999); margin-bottom: 2px; }\n .stat-row { display: flex; align-items: baseline; gap: 2px; }\n .stat-value { font-size: 1.5em; font-weight: 700; color: var(--primary-text-color, #fff); }\n /* A sum that left out a term with no reading: dimmed, and marked as at least this much. */\n .stat-value.stat-partial { opacity: 0.7; }\n .stat-value.stat-partial::after { content: "+"; }\n .stat-unit { font-size: 0.7em; font-weight: 400; color: var(--secondary-text-color, #999); }\n\n .header-right { display: flex; flex-direction: column; align-items: flex-end; gap: 8px; padding-top: 8px; }\n .header-right-top { display: flex; gap: 20px; align-items: center; }\n .meta-item { font-size: 0.8em; color: var(--secondary-text-color, #999); }\n\n .shedding-legend { display: flex; gap: 12px; flex-wrap: wrap; justify-content: flex-end; }\n .shedding-legend-item { display: inline-flex; align-items: center; gap: 3px; }\n .shedding-legend-item span-icon { --mdc-icon-size: 16px; }\n .shedding-legend-secondary { --mdc-icon-size: 12px; opacity: 0.8; }\n .shedding-legend-text { font-size: 9px; font-weight: 600; }\n .shedding-legend-label { font-size: 0.7em; color: var(--secondary-text-color, #999); }\n\n .panel-gear {\n background: none;\n border: none;\n cursor: pointer;\n color: var(--secondary-text-color);\n opacity: 0.6;\n padding: 4px;\n margin-left: 8px;\n vertical-align: middle;\n }\n .panel-gear:hover { opacity: 1; }\n .header-center {\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-top: 8px;\n }\n .panel-identity .panel-gear {\n margin-left: 0;\n }\n .slide-confirm {\n position: relative;\n display: inline-flex;\n align-items: center;\n width: 160px;\n height: 28px;\n border-radius: 14px;\n background: color-mix(in srgb, var(--primary-color, #4dd9af) 20%, var(--secondary-background-color, #333));\n vertical-align: middle;\n overflow: hidden;\n user-select: none;\n touch-action: none;\n }\n .slide-confirm-text {\n position: absolute;\n width: 100%;\n text-align: center;\n font-size: 0.65em;\n font-weight: 600;\n color: var(--secondary-text-color, #999);\n pointer-events: none;\n z-index: 0;\n }\n .slide-confirm-knob {\n position: absolute;\n left: 2px;\n top: 2px;\n width: 24px;\n height: 24px;\n border-radius: 50%;\n background: var(--secondary-text-color, #666);\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: grab;\n z-index: 1;\n transition: none;\n }\n .slide-confirm-knob span-icon {\n --mdc-icon-size: 14px;\n color: var(--card-background-color, #1c1c1c);\n }\n .slide-confirm-knob.snapping {\n transition: left 0.25s ease;\n }\n .slide-confirm.confirmed {\n background: color-mix(in srgb, var(--state-active-color, var(--span-accent)) 25%, transparent);\n }\n .slide-confirm.confirmed .slide-confirm-text {\n color: var(--state-active-color, var(--span-accent));\n }\n .slide-confirm.confirmed .slide-confirm-knob {\n background: var(--state-active-color, var(--span-accent));\n }\n .switches-disabled .toggle-pill {\n opacity: 0.3;\n pointer-events: none;\n }\n /* The slider where the user may operate none of the view\'s controls: dimmed, and never armed. */\n .slide-confirm.slide-confirm-forbidden {\n opacity: 0.5;\n cursor: not-allowed;\n }\n .slide-confirm.slide-confirm-forbidden .slide-confirm-knob {\n cursor: not-allowed;\n }\n /* Its note, saying why: on a line of its own under the panel\'s name, or under each panel\'s name in the Favorites stats grid. */\n .controls-note {\n margin: 0;\n font-size: 0.8em;\n color: var(--secondary-text-color, #727272);\n }\n .panel-identity .controls-note {\n flex-basis: 100%;\n }\n .unit-toggle {\n display: inline-flex;\n background: var(--secondary-background-color, #333);\n border-radius: 6px;\n overflow: hidden;\n margin-left: 8px;\n }\n .unit-btn {\n padding: 4px 10px;\n border: none;\n background: none;\n color: var(--secondary-text-color);\n font-size: 0.75em;\n font-weight: 600;\n cursor: pointer;\n }\n .unit-btn.unit-active {\n background: var(--primary-color, #4dd9af);\n color: var(--text-primary-color, #000);\n }\n\n .monitoring-summary {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 6px 16px;\n font-size: 0.8em;\n background: rgba(76, 175, 80, 0.1);\n border: 1px solid var(--divider-color, #333);\n border-top: none;\n }\n .monitoring-active { color: #4caf50; }\n .monitoring-counts { display: flex; gap: 12px; }\n .count-warning { color: #ff9800; }\n .count-alert { color: #f44336; }\n .count-overrides { color: var(--secondary-text-color); }\n\n .panel-grid {\n display: grid;\n /* Five columns: left tab label, left cell, explicit 8px spacer,\n right cell, right tab label. Spacer is in-band rather than a\n column-gap so we can keep inter-cell space without paying an\n equal gap between each cell and its tab label. The tab columns\n are sized to fit a 2-digit breaker number (the font is 0.85em\n of the panel body ≈ 14px glyph width). */\n grid-template-columns: 14px 1fr 8px 1fr 14px;\n column-gap: 0;\n row-gap: 8px;\n align-items: stretch;\n }\n\n .tab-label {\n display: flex;\n align-items: center;\n font-size: 0.85em;\n font-weight: 600;\n color: var(--secondary-text-color, #999);\n user-select: none;\n }\n .tab-left { justify-content: flex-start; }\n .tab-right { justify-content: flex-end; }\n\n .circuit-slot {\n background: var(--secondary-background-color, var(--card-background-color, #2a2a2a));\n border: 1px solid var(--divider-color, #333);\n border-radius: 12px;\n padding: 14px 16px 20px;\n min-height: 140px;\n transition: opacity 0.3s;\n position: relative;\n overflow: hidden;\n }\n\n .circuit-col-span { min-height: 280px; }\n .circuit-row-span { border-left: 3px solid var(--span-accent); }\n .circuit-off .circuit-name,\n .circuit-off .breaker-badge,\n .circuit-off .power-value,\n .circuit-off .chart-container { opacity: 0.35; }\n .circuit-off .toggle-pill,\n .circuit-off .gear-icon { opacity: 1; }\n\n .circuit-empty {\n opacity: 0.2;\n min-height: 60px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-style: dashed;\n }\n .empty-label { color: var(--secondary-text-color, #999); font-size: 0.85em; }\n\n .circuit-header {\n display: flex;\n justify-content: space-between;\n align-items: flex-start;\n margin-bottom: 6px;\n gap: 8px;\n }\n\n .circuit-info { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; }\n\n .breaker-badge {\n background: color-mix(in srgb, var(--span-accent) 15%, transparent);\n color: var(--span-accent);\n font-size: 0.7em;\n font-weight: 700;\n padding: 2px 3px;\n border-radius: 4px;\n white-space: nowrap;\n border: 1px solid color-mix(in srgb, var(--span-accent) 25%, transparent);\n flex-shrink: 0;\n }\n\n /* The pencil that marks a rating from a copied package, a button so a tap or a key can show what it says. */\n .rating-user-set {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 24px;\n min-height: 24px;\n margin-left: 2px;\n padding: 0 2px;\n border: none;\n border-radius: 3px;\n background: none;\n color: inherit;\n font: inherit;\n font-weight: 400;\n line-height: inherit;\n cursor: help;\n }\n .rating-user-set:focus-visible {\n outline: 2px solid var(--primary-color, #03a9f4);\n outline-offset: 1px;\n }\n .rating-copied-note {\n display: block;\n margin-top: 2px;\n font-size: 0.85em;\n color: var(--secondary-text-color, #727272);\n white-space: normal;\n }\n .rating-copied-note[hidden] {\n display: none;\n }\n\n .circuit-name {\n font-size: 0.9em;\n font-weight: 500;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--primary-text-color, #e0e0e0);\n }\n\n .circuit-controls { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }\n\n /* Truncation-driven fold for By Panel breaker cells. The .is-folded\n class is added/removed by the JS observer in\n src/core/truncation-fold.ts when the .circuit-name actually\n ellipsizes. Pixel thresholds can\'t get this right because name\n length varies wildly per circuit (e.g. "Spa" vs\n "Commissioned PV System") — only measuring the live name vs its\n container catches the exact moment of truncation.\n\n When folded the nested flex wrappers (.circuit-header,\n .circuit-info, .circuit-controls, .circuit-status) collapse via\n \'display: contents\' so the leaf elements participate directly in\n the outer grid: name gets the whole first row, readings/controls/\n gear drop to a second row, chart stays as the full-width third. */\n .circuit-slot.is-folded {\n display: grid;\n /* Columns: badges + relay-toggle pack tight on the left, slack\n absorbed by the 1fr column between the relay and the power\n reading, keeping power + gear pinned to the right edge. The\n previous layout placed the slack between the shedding icon and\n the relay, which read as wasted padding the user pointed out. */\n grid-template-columns: auto auto auto auto 1fr auto auto;\n /* Rows: name and controls sized to content; chart absorbs any\n extra cell height. Without the explicit 1fr on row 3, a tall\n cell (e.g. .circuit-col-span\'s 280px min-height for 240V\n double-pole breakers) distributes excess space equally across\n all three rows via the default align-content:stretch, which\n pushes the chart down and vertically inflates the badge and\n relay toggle to fill the controls row. */\n grid-template-rows: auto auto 1fr;\n grid-template-areas:\n "name name name name name name name"\n "badge util shed status . power gear"\n "chart chart chart chart chart chart chart";\n row-gap: 6px;\n column-gap: 8px;\n }\n .circuit-slot.is-folded > .circuit-header,\n .circuit-slot.is-folded > .circuit-status,\n .circuit-slot.is-folded > .circuit-header > .circuit-info,\n .circuit-slot.is-folded > .circuit-header > .circuit-controls {\n display: contents;\n }\n .circuit-slot.is-folded .circuit-name {\n grid-area: name;\n justify-self: start;\n }\n .circuit-slot.is-folded .breaker-badge {\n grid-area: badge;\n }\n .circuit-slot.is-folded .utilization {\n grid-area: util;\n }\n .circuit-slot.is-folded .shedding-icon,\n .circuit-slot.is-folded .shedding-composite {\n grid-area: shed;\n }\n .circuit-slot.is-folded .toggle-pill {\n grid-area: status;\n justify-self: end;\n }\n .circuit-slot.is-folded .power-value {\n grid-area: power;\n justify-self: end;\n }\n .circuit-slot.is-folded .gear-icon.circuit-gear {\n grid-area: gear;\n justify-self: end;\n }\n .circuit-slot.is-folded > .chart-container {\n grid-area: chart;\n }\n\n .power-value { font-size: 0.9em; color: var(--primary-text-color, #fff); white-space: nowrap; }\n .power-value strong { font-weight: 700; font-size: 1.1em; }\n .power-unit { font-size: 0.8em; font-weight: 400; color: var(--secondary-text-color, #999); margin-left: 1px; }\n .circuit-producer .power-value strong { color: var(--info-color, #4fc3f7); }\n\n .toggle-pill {\n display: flex;\n align-items: center;\n gap: 3px;\n padding: 2px 4px;\n border-radius: 10px;\n cursor: pointer;\n font-size: 0.65em;\n font-weight: 600;\n transition: background 0.2s;\n user-select: none;\n min-width: 40px;\n }\n .toggle-on {\n padding-left: 6px;\n background: color-mix(in srgb, var(--state-active-color, var(--span-accent)) 25%, transparent);\n color: var(--state-active-color, var(--span-accent));\n }\n .toggle-off {\n padding-right: 6px;\n background: color-mix(in srgb, var(--secondary-text-color) 15%, transparent);\n color: var(--secondary-text-color, #999);\n }\n .toggle-knob {\n width: 14px;\n height: 14px;\n border-radius: 50%;\n transition: background 0.2s, margin 0.2s;\n }\n .toggle-on .toggle-knob {\n background: var(--state-active-color, var(--span-accent));\n margin-left: auto;\n }\n .toggle-off .toggle-knob {\n background: var(--secondary-text-color, #999);\n margin-right: auto;\n order: -1;\n }\n /* A switch Home Assistant reports unavailable: the relay state is still\n shown, but the pill cannot be operated. */\n .toggle-pill.toggle-unavailable {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n /* Locked switches dim every pill to 0.3; an inert one stays dimmer still. */\n .switches-disabled .toggle-pill.toggle-unavailable {\n opacity: 0.2;\n }\n /* A switch the user may not operate: the relay state is still shown, and the\n pill, titled with why, sends nothing. Dimmer still while the switches are locked. */\n .toggle-pill.toggle-forbidden {\n opacity: 0.4;\n cursor: not-allowed;\n }\n .switches-disabled .toggle-pill.toggle-forbidden {\n opacity: 0.2;\n }\n\n .circuit-status {\n display: flex;\n align-items: center;\n gap: 4px;\n margin-top: 4px;\n padding: 0 4px;\n }\n .shedding-icon { opacity: 0.8; cursor: default; }\n .shedding-composite {\n display: inline-flex;\n align-items: center;\n gap: 2px;\n }\n .shedding-icon-secondary { opacity: 0.8; }\n .shedding-label {\n font-size: 10px;\n font-weight: 600;\n opacity: 0.8;\n }\n .gear-icon {\n background: none;\n border: none;\n cursor: pointer;\n padding: 2px;\n opacity: 0.6;\n transition: opacity 0.2s;\n margin-left: auto;\n }\n .gear-icon:hover { opacity: 1; }\n .utilization {\n font-size: 0.75em;\n font-weight: 600;\n }\n .utilization-normal { color: #4caf50; }\n .utilization-warning { color: #ff9800; }\n .utilization-alert { color: #f44336; }\n .circuit-alert {\n border-color: #f44336 !important;\n box-shadow: 0 0 8px rgba(244, 67, 54, 0.3);\n }\n .chart-container {\n width: 100%;\n aspect-ratio: 4 / 1;\n margin-top: 4px;\n overflow: hidden;\n min-width: 0;\n }\n\n .sub-devices {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n gap: 12px;\n margin-bottom: 20px;\n padding-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n\n /* Meters outside the panel: no breaker space, so a strip above the grid. */\n .meters-strip {\n display: flex;\n flex-wrap: wrap;\n gap: 12px;\n margin-bottom: 20px;\n padding-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n .meters-title { flex-basis: 100%; font-size: 0.7em; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--span-accent); }\n .meter-tile {\n flex: 1 1 220px;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 6px;\n background: var(--secondary-background-color, var(--card-background-color, #2a2a2a));\n border: 1px solid var(--divider-color, #333);\n border-radius: 12px;\n padding: 12px 16px;\n }\n .meter-name {\n font-size: 0.9em;\n font-weight: 500;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--primary-text-color, #e0e0e0);\n }\n .meter-readings { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; font-size: 0.85em; color: var(--secondary-text-color, #999); }\n .meter-value { font-size: 1.05em; color: var(--primary-text-color, #fff); white-space: nowrap; }\n .meter-value strong { font-weight: 700; font-size: 1.1em; }\n .meter-direction:empty { display: none; }\n\n .sub-device {\n background: var(--secondary-background-color, var(--card-background-color, #2a2a2a));\n border: 1px solid var(--divider-color, #333);\n border-radius: 12px;\n padding: 14px 16px;\n }\n .sub-device-bess,\n .sub-device-full {\n grid-column: 1 / -1;\n }\n\n .sub-device-header { display: flex; gap: 10px; align-items: baseline; margin-bottom: 8px; }\n .sub-device-type { font-size: 0.7em; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--span-accent); }\n .sub-device-name { font-size: 0.85em; color: var(--secondary-text-color, #999); flex: 1; }\n .sub-power-value { font-size: 0.9em; color: var(--primary-text-color, #fff); white-space: nowrap; }\n .sub-power-value strong { font-weight: 700; font-size: 1.1em; }\n .sub-device .chart-container { margin-bottom: 8px; aspect-ratio: auto; }\n\n .bess-charts {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(0, 1fr));\n gap: 12px;\n margin-bottom: 10px;\n }\n .bess-chart-col { min-width: 0; }\n .bess-chart-title {\n font-size: 0.75em;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.04em;\n color: var(--secondary-text-color, #999);\n margin-bottom: 4px;\n }\n .bess-chart-col .chart-container { aspect-ratio: auto; }\n .sub-entity { display: flex; gap: 6px; padding: 3px 0; font-size: 0.85em; }\n .sub-entity-name { color: var(--secondary-text-color, #999); }\n .sub-entity-value { font-weight: 500; color: var(--primary-text-color, #e0e0e0); }\n .sub-identity { font-size: 0.85em; color: var(--secondary-text-color, #999); margin: 2px 0 6px; }\n .sub-note { font-size: 0.85em; color: var(--secondary-text-color, #999); font-style: italic; margin-top: 4px; }\n .sub-power-caption { font-size: 0.75em; color: var(--secondary-text-color, #999); margin-right: 6px; text-transform: uppercase; }\n\n /* ── Shared tab bar ────────────────────────────────────── */\n\n .shared-tab-bar {\n display: flex;\n gap: 0;\n margin-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n\n .shared-tab {\n padding: 8px 16px;\n cursor: pointer;\n font-size: 0.9em;\n font-weight: 500;\n color: var(--primary-text-color);\n opacity: 0.6;\n border: none;\n border-bottom: 2px solid transparent;\n background: none;\n transition: opacity 0.15s;\n }\n\n .shared-tab:hover {\n opacity: 0.85;\n }\n\n .shared-tab.active {\n opacity: 1;\n border-bottom-color: var(--span-accent);\n }\n\n /* ── List view search ──────────────────────────────────── */\n\n .list-search-container {\n margin-bottom: 12px;\n position: relative;\n }\n\n .list-search {\n width: 100%;\n padding: 8px 36px 8px 12px;\n border-radius: 8px;\n border: 1px solid var(--divider-color, #333);\n background: var(--secondary-background-color, #2a2a2a);\n color: var(--primary-text-color);\n font-size: 0.9em;\n box-sizing: border-box;\n outline: none;\n }\n\n .list-search:focus {\n border-color: var(--span-accent);\n }\n\n .list-search-clear {\n position: absolute;\n right: 8px;\n top: 50%;\n transform: translateY(-50%);\n background: none;\n border: none;\n color: var(--secondary-text-color);\n cursor: pointer;\n padding: 2px;\n display: flex;\n align-items: center;\n opacity: 0.7;\n }\n\n .list-search-clear:hover {\n opacity: 1;\n }\n\n .list-unit-toggle {\n display: inline-flex;\n margin-bottom: 12px;\n }\n\n /* ── List rows ─────────────────────────────────────────── */\n\n .list-view {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n /* Each circuit is wrapped in a .list-cell so the row + its optional\n expanded chart stay together. In single-column flex mode the cell\n just stacks naturally. In multi-column grid mode the cell becomes\n one grid item, so the chart is always in the same column as its\n row. Area headers (rendered as siblings, not inside a cell) span\n all columns via their inline "grid-column: 1 / -1". */\n .list-cell {\n display: flex;\n flex-direction: column;\n min-width: 0;\n }\n .list-view[data-columns="2"],\n .list-view[data-columns="3"] {\n display: grid;\n grid-template-columns: repeat(var(--list-cols), minmax(0, 1fr));\n gap: 6px 8px;\n flex-direction: initial;\n }\n /* On narrow viewports a 2/3-column list would squeeze rows into an\n unreadable shape, so force stacking regardless of user preference. */\n @media (max-width: 599px) {\n .list-view[data-columns="2"],\n .list-view[data-columns="3"] {\n display: flex;\n flex-direction: column;\n }\n }\n\n .list-row {\n display: flex;\n align-items: center;\n padding: 12px 16px;\n gap: 10px;\n /* min-width: 0 lets the row shrink below the sum of its\n non-shrinking children when its parent .list-cell is in a\n narrow CSS-grid track (multi-column list mode). Without this\n the row would maintain its intrinsic min-content width and\n overflow the cell, leaving the name unshrunk and the\n truncation-fold observer with no signal to react to. */\n min-width: 0;\n background: var(--card-background-color, #1c1c1c);\n border: 1px solid var(--divider-color, #333);\n border-radius: 8px;\n cursor: pointer;\n transition: background 0.15s;\n }\n\n .list-row:hover {\n background: var(--secondary-background-color, #2a2a2a);\n }\n\n .list-row.circuit-off {\n opacity: 0.5;\n }\n\n .list-row.list-row-expanded {\n border-bottom-left-radius: 0;\n border-bottom-right-radius: 0;\n border-bottom-color: transparent;\n }\n\n .list-circuit-name {\n flex: 1;\n color: var(--primary-text-color);\n font-size: 0.9em;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .list-status-badge {\n font-size: 0.75em;\n font-weight: 600;\n padding: 2px 8px;\n border-radius: 4px;\n flex-shrink: 0;\n }\n\n .list-status-on {\n color: #4dd9af;\n }\n\n .list-status-off {\n color: #f44336;\n }\n\n .list-power-value {\n font-size: 0.9em;\n font-weight: 600;\n flex-shrink: 0;\n /* No min-width / text-align:right: the old 70px right-aligned\n cell left a visible blank column for short readings (e.g.\n "1.3A" in a 70px slot), which robbed horizontal space from\n .list-circuit-name on narrow rows. Let the value hug the\n preceding relay control and size to its content so the freed\n width flows back into the flex:1 name column. */\n }\n\n .list-expand-toggle {\n background: none;\n border: none;\n color: var(--secondary-text-color);\n cursor: pointer;\n padding: 4px;\n transition: transform 0.2s;\n display: flex;\n align-items: center;\n flex-shrink: 0;\n }\n\n .list-expand-toggle.expanded {\n transform: rotate(180deg);\n }\n\n .list-row .gear-icon {\n background: transparent;\n border: none;\n padding: 2px;\n cursor: pointer;\n color: #555;\n display: inline-flex;\n align-items: center;\n }\n .list-row .gear-icon:hover {\n color: var(--primary-text-color);\n }\n\n /* Truncation-driven fold for list rows. The .is-folded class is\n added/removed by the JS observer in src/core/truncation-fold.ts\n when the .list-circuit-name actually ellipsizes — pixel breakpoints\n can\'t track this because name length varies wildly per circuit\n ("Spa" vs "Commissioned PV System") and any single threshold\n misfires for the other end of the range. Switch to a two-row grid\n so the name gets the full width (paired only with the expand\n chevron) and the badges/controls/reading/gear drop to a secondary\n row underneath. Named areas keep the CSS readable despite the flat\n HTML child order. */\n .list-row.is-folded {\n display: grid;\n /* Row 1: name spans the row up to the chevron at the trailing\n column. Row 2: badge + util + shed + relay-toggle pack left,\n the 1fr column absorbs slack between the relay and the power\n reading, power + gear stay pinned to the right edge. The\n earlier layout placed the slack between the shedding icon and\n the relay, which the user flagged as wasted padding. */\n grid-template-columns: auto auto auto auto 1fr auto auto;\n grid-template-areas:\n "name name name name name name chevron"\n "badge util shed status . power gear";\n row-gap: 6px;\n column-gap: 8px;\n }\n .list-row.is-folded > .list-circuit-name {\n grid-area: name;\n justify-self: start;\n }\n .list-row.is-folded > .list-expand-toggle {\n grid-area: chevron;\n }\n .list-row.is-folded > .breaker-badge {\n grid-area: badge;\n }\n .list-row.is-folded > .utilization {\n grid-area: util;\n }\n .list-row.is-folded > .shedding-icon,\n .list-row.is-folded > .shedding-composite {\n grid-area: shed;\n }\n .list-row.is-folded > .toggle-pill,\n .list-row.is-folded > .list-status-badge {\n grid-area: status;\n }\n .list-row.is-folded > .list-power-value {\n grid-area: power;\n justify-self: end;\n }\n .list-row.is-folded > .gear-icon.circuit-gear {\n grid-area: gear;\n justify-self: end;\n }\n\n /* ── Expanded circuit content ──────────────────────────── */\n\n .list-expanded-content {\n padding: 0;\n background: var(--card-background-color, #1c1c1c);\n border: 1px solid var(--divider-color, #333);\n border-top: none;\n border-radius: 0 0 8px 8px;\n margin-top: -6px;\n margin-bottom: 2px;\n }\n\n .circuit-slot.circuit-chart-only {\n border: none;\n margin: 0;\n background: none;\n padding: 8px 12px;\n min-height: 0;\n }\n\n /* ── Area headers ──────────────────────────────────────── */\n\n .area-header {\n padding: 16px 12px 6px;\n font-weight: 600;\n font-size: 0.85em;\n color: var(--secondary-text-color);\n text-transform: uppercase;\n letter-spacing: 0.05em;\n }\n\n /* ── No results ────────────────────────────────────────── */\n\n .list-no-results {\n padding: 24px;\n text-align: center;\n color: var(--secondary-text-color);\n }\n\n'),C([Ht({attribute:!1})],VI.prototype,"hass",void 0),C([Bt()],VI.prototype,"_config",void 0),C([Bt()],VI.prototype,"_discovered",void 0),C([Bt()],VI.prototype,"_discovering",void 0),C([Bt()],VI.prototype,"_topology",void 0),C([Bt()],VI.prototype,"_activeTab",void 0),VI=C([(t=>(e,n)=>{void 0!==n?n.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)})(c)],VI);class qI extends HTMLElement{constructor(){super(...arguments),this._config={},this._hass=null,this._panels=null,this._availableRoles=null,this._built=!1,this._discovering=!1,this._panelSelect=null,this._daysInput=null,this._hoursInput=null,this._minsInput=null,this._metricSelect=null,this._checkboxes={},this._entityContainers={},this._tabStyleSelect=null}setConfig(t){this._config={...t},this._updateControls()}set hass(t){this._hass=t,this._panels?this._built||this._buildEditor():this._discovering||this._discoverPanels()}async _discoverPanels(){if(!this._hass)return;let t;this._discovering=!0;try{t=await async function(t){const e={type:"config_entries/get",domain:l},[n,i]=await Promise.all([t.callWS({type:"config/device_registry/list"}),t.callWS(e)]),r=new Set(i.map(t=>t.entry_id));return n.filter(t=>Zn(t,r))}(this._hass)}catch(t){return void console.warn("SPAN Panel: the card editor could not list the panels",t)}finally{this._discovering=!1}this._panels=t.map(t=>{const e=(t.identifiers??[]).find(t=>t[0]===l)?.[1]??"",n=t.name_by_user??t.name??i("editor.panel_label");return{device_id:t.id,label:`${n} (${e})`}}),this._buildEditor()}_buildEditor(){this.innerHTML="",this._built=!0;const t=document.createElement("div");t.style.padding="16px";const e="\n width: 100%;\n padding: 10px 12px;\n border-radius: 8px;\n border: 1px solid var(--divider-color, #333);\n background: var(--card-background-color, var(--secondary-background-color, #1c1c1c));\n color: var(--primary-text-color, #e0e0e0);\n font-size: 1em;\n cursor: pointer;\n appearance: auto;\n box-sizing: border-box;\n ",n="display: block; font-weight: 500; margin-bottom: 8px; color: var(--primary-text-color);",i="margin-bottom: 16px;";this._buildPanelSelector(t,e,n,i),this._buildTimeWindow(t,e,n,i),this._buildMetricSelector(t,e,n,i),this._buildTabStyleSelector(t,e,n,i),this._buildSectionCheckboxes(t,n,i),this.appendChild(t),this._populateMetricSelect(),this._config.device_id&&this._discoverAvailableRoles(this._config.device_id)}_buildPanelSelector(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.panel_label"),a.style.cssText=n;const s=document.createElement("select");s.style.cssText=e;const l=document.createElement("option");if(l.value="",l.textContent=i("editor.select_panel"),s.appendChild(l),this._panels)for(const t of this._panels){const e=document.createElement("option");e.value=t.device_id,e.textContent=t.label,t.device_id===this._config.device_id&&(e.selected=!0),s.appendChild(e)}s.addEventListener("change",()=>{this._config={...this._config,device_id:s.value},this._fireConfigChanged(),this._discoverAvailableRoles(s.value)}),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._panelSelect=s}_buildTimeWindow(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.chart_window"),a.style.cssText=n;const s=document.createElement("div");s.style.cssText="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;";const l=e+"width: 70px; cursor: text;",c=(t,e,n,i)=>{const r=document.createElement("div");r.style.cssText="display: flex; align-items: center; gap: 6px;";const o=document.createElement("input");o.type="number",o.min=e,o.max=n,o.value=String(t),o.style.cssText=l;const a=document.createElement("span");return a.textContent=i,a.style.cssText="font-size: 0.9em; color: var(--secondary-text-color);",r.appendChild(o),r.appendChild(a),{wrap:r,input:o}},u=parseInt(String(this._config.history_days))||0,d=parseInt(String(this._config.history_hours))||0,h=parseInt(String(this._config.history_minutes))||0,p=c(u,"0","30",i("editor.days")),f=c(d,"0","23",i("editor.hours")),g=c(h,"0","59",i("editor.minutes")),m=()=>{this._config={...this._config,history_days:parseInt(p.input.value)||0,history_hours:parseInt(f.input.value)||0,history_minutes:parseInt(g.input.value)||0},this._fireConfigChanged()};p.input.addEventListener("change",m),f.input.addEventListener("change",m),g.input.addEventListener("change",m),s.appendChild(p.wrap),s.appendChild(f.wrap),s.appendChild(g.wrap),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._daysInput=p.input,this._hoursInput=f.input,this._minsInput=g.input}_buildMetricSelector(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.chart_metric"),a.style.cssText=n;const s=document.createElement("select");s.style.cssText=e,s.addEventListener("change",()=>{this._config={...this._config,chart_metric:s.value},this._fireConfigChanged()}),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._metricSelect=s}_buildTabStyleSelector(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.tab_style"),a.style.cssText=n;const s=document.createElement("select");s.style.cssText=e;const l=[{value:"text",text:i("editor.tab_style_text")},{value:"icon",text:i("editor.tab_style_icon")}];for(const t of l){const e=document.createElement("option");e.value=t.value,e.textContent=t.text,t.value===(this._config.tab_style??"text")&&(e.selected=!0),s.appendChild(e)}s.addEventListener("change",()=>{this._config={...this._config,tab_style:s.value},this._fireConfigChanged()}),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._tabStyleSelect=s}_buildSectionCheckboxes(t,e,n){const r=document.createElement("div");r.style.cssText=n;const o=document.createElement("label");o.textContent=i("editor.visible_sections"),o.style.cssText=e,r.appendChild(o);const a=[{key:"show_panel",label:i("editor.panel_circuits"),subDeviceType:null},{key:"show_battery",label:i("editor.battery_bess"),subDeviceType:"bess"},{key:"show_evse",label:i("editor.ev_charger_evse"),subDeviceType:"evse"},{key:"show_solar",label:i("editor.solar_pv"),subDeviceType:"pv"}];this._checkboxes={},this._entityContainers={};for(const t of a){const e=document.createElement("div");e.style.cssText="display: flex; align-items: center; gap: 8px; margin-bottom: 6px; cursor: pointer;";const n=document.createElement("input");n.type="checkbox",n.checked=!1!==this._config[t.key],n.style.cssText="width: 18px; height: 18px; cursor: pointer; accent-color: var(--primary-color);";const i=document.createElement("span");i.textContent=t.label,i.style.cssText="font-size: 0.9em; color: var(--primary-text-color); cursor: pointer;",e.appendChild(n),e.appendChild(i),r.appendChild(e),this._checkboxes[t.key]=n;let o=null;t.subDeviceType&&(o=document.createElement("div"),o.style.cssText="padding-left: 26px;",o.style.display=n.checked?"block":"none",r.appendChild(o),this._entityContainers[t.subDeviceType]=o),n.addEventListener("change",()=>{this._config={...this._config,[t.key]:n.checked},o&&(o.style.display=n.checked?"block":"none"),this._fireConfigChanged()})}t.appendChild(r)}_populateEntityCheckboxes(t){const e=this._config.visible_sub_entities??{},n="font-size: 0.85em; color: var(--primary-text-color); cursor: pointer;";for(const[r,o]of Object.entries(this._entityContainers)){o.innerHTML="";for(const a of jI(t,r)){const t=document.createElement("div");if(t.textContent=a.name,t.style.cssText="font-size: 0.85em; font-weight: 500; color: var(--secondary-text-color); margin: 8px 0 4px;",o.appendChild(t),0===a.entities.length){const t=document.createElement("div");t.textContent=i("editor.no_entities"),t.style.cssText=n,o.appendChild(t);continue}for(const{entityId:t,label:i}of a.entities){const r=document.createElement("div");r.style.cssText="display: flex; align-items: center; gap: 8px; margin-bottom: 5px; cursor: pointer;";const a=document.createElement("input");a.type="checkbox",a.checked=!0===e[t],a.style.cssText="width: 16px; height: 16px; cursor: pointer; accent-color: var(--primary-color);";const s=document.createElement("span");s.textContent=i,s.style.cssText=n,r.appendChild(a),r.appendChild(s),o.appendChild(r),a.addEventListener("change",()=>{const e={...this._config.visible_sub_entities??{}};a.checked?e[t]=!0:delete e[t],this._config={...this._config,visible_sub_entities:e},this._fireConfigChanged()})}}}}async _discoverAvailableRoles(t){if(this._hass&&t)try{const e=await this._hass.callWS({type:`${l}/panel_topology`,device_id:t}),n=new Set;for(const t of Object.values(e.circuits??{}))for(const e of Object.keys(t.entities??{}))n.add(e);this._availableRoles=n,this._populateMetricSelect(),e.sub_devices&&this._populateEntityCheckboxes(e.sub_devices)}catch{this._availableRoles=null,this._populateMetricSelect()}}_populateMetricSelect(){const t=this._metricSelect;if(!t)return;const e=this._config.chart_metric??o;t.innerHTML="";for(const[n,i]of Object.entries(y)){if(this._availableRoles&&!this._availableRoles.has(i.entityRole))continue;const r=document.createElement("option");r.value=n,r.textContent=i.label(),n===e&&(r.selected=!0),t.appendChild(r)}}_updateControls(){if(this._panelSelect&&(this._panelSelect.value=this._config.device_id??""),this._daysInput&&(this._daysInput.value=String(parseInt(String(this._config.history_days))||0)),this._hoursInput&&(this._hoursInput.value=String(parseInt(String(this._config.history_hours))||0)),this._minsInput&&(this._minsInput.value=String(parseInt(String(this._config.history_minutes))||0)),this._metricSelect&&(this._metricSelect.value=this._config.chart_metric??o),this._checkboxes)for(const[t,e]of Object.entries(this._checkboxes))e.checked=!1!==this._config[t];this._tabStyleSelect&&(this._tabStyleSelect.value=this._config.tab_style??"text")}_fireConfigChanged(){this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:this._config}}))}}function UI(t){return function(t){const e={};for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}({device_id:t.device_id,history_days:t.history_days,history_hours:t.history_hours,history_minutes:t.history_minutes,chart_metric:t.chart_metric,show_panel:t.show_panel,show_battery:t.show_battery,show_evse:t.show_evse,show_solar:t.show_solar,visible_sub_entities:t.visible_sub_entities,tab_style:t.tab_style})}class GI extends HTMLElement{static getStubConfig(t){const e=WI(t),n=Object.values(t.devices??{}).find(t=>Zn(t,e));return n?{type:h,device_id:n.id}:{type:h}}static async generate(t){return{type:"grid",cards:[{...UI(t),type:u,grid_options:{columns:"full"}}]}}}GI.registryDependencies=[];try{customElements.get("span-panel-card-editor")||customElements.define("span-panel-card-editor",qI)}catch{}try{customElements.get(p)||customElements.define(p,GI)}catch{}!function(t){const e=window.customCards??(window.customCards=[]);e.some(e=>e.type===t.type)||e.push(t)}({type:c,name:"SPAN Panel",description:"Physical panel layout with live power charts matching the SPAN frontend",preview:!0,getEntitySuggestion:function(t,e){const n=t.entities?.[e];if(n?.platform!==l||!n.device_id||!t.devices)return null;const i=t.devices[n.device_id],r=i?function(t,e,n){const i=t.parent_device_id||t.via_device_id,r=i?e[i]:t;return r&&Zn(r,n)&&Kn(t,r)?r:null}(i,t.devices,WI(t)):null;return r?{config:{type:u,device_id:r.id}}:null}}),function(t){const e=window.customStrategies??(window.customStrategies=[]);e.some(e=>e.type===t.type&&e.strategyType===t.strategyType)||e.push(t)}({type:d,strategyType:"section",name:"SPAN Panel",description:"A SPAN panel's breaker layout and live power charts, at the section's full width"}),console.warn("%c SPAN-PANEL-CARD %c v0.12.0 ","background: var(--primary-color, #4dd9af); color: var(--text-primary-color, #000); font-weight: 700; padding: 2px 6px; border-radius: 4px 0 0 4px;","background: var(--secondary-background-color, #333); color: var(--primary-text-color, #fff); padding: 2px 6px; border-radius: 0 4px 4px 0;"); + `}};function zI(t){const e=new Set;for(const n of Object.values(t.entities??{})){if(n.platform!==l||!n.device_id)continue;const i=t.devices?.[n.device_id]?.config_entry_id;i&&e.add(i)}return e}function HI(t,e){return Yn(Object.entries(t)).filter(([,t])=>t.type===e).map(([t,e])=>{const n=jn(e),i=e.name??"",r=Object.entries(e.entities??{}).filter(([t])=>!n.has(t)).map(([t,e])=>{let n=e.original_name??t;return i&&n.startsWith(i+" ")&&(n=n.slice(i.length+1)),{entityId:t,label:n}});return{devId:t,name:i||t,entities:r}})}OI.styles=D('\n :host {\n --span-accent: var(--primary-color, #4dd9af);\n }\n\n /* Card shell — replaces . Theme variables (--ha-card-*) are\n stable HA contracts (not the deprecated component APIs flagged by the\n 2026.4 frontend blog), so they stay in place to keep visual parity\n with the rest of HA\'s dashboards. */\n .span-card {\n display: block;\n padding: 24px;\n background: var(--card-background-color, #1c1c1c);\n color: var(--primary-text-color, #e0e0e0);\n border-radius: var(--ha-card-border-radius, 12px);\n border: var(--ha-card-border-width, 1px) solid var(--ha-card-border-color, var(--divider-color, #333));\n box-shadow: var(--ha-card-box-shadow, none);\n }\n\n .panel-header {\n display: flex;\n flex-wrap: wrap;\n justify-content: space-between;\n align-items: flex-start;\n gap: 8px 16px;\n margin-bottom: 20px;\n padding-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n .header-left { flex: 1 1 300px; min-width: 0; }\n .header-center { flex: 0 0 auto; }\n .header-right { flex: 0 1 auto; min-width: 0; }\n\n .panel-identity {\n display: flex;\n align-items: center;\n flex-wrap: wrap;\n gap: 8px 12px;\n margin-bottom: 12px;\n }\n\n .panel-title {\n font-size: 1.8em;\n font-weight: 700;\n margin: 0;\n color: var(--primary-text-color, #fff);\n }\n\n .panel-serial {\n font-size: 0.85em;\n color: var(--secondary-text-color, #999);\n font-family: monospace;\n }\n\n .panel-stats {\n display: flex;\n flex-wrap: wrap;\n gap: 16px 32px;\n }\n\n /* Favorites view header: gear + slide-to-arm + right-anchored legend/W-A cluster. */\n .favorites-summary {\n padding: 8px 24px;\n border-bottom: 1px solid var(--divider-color, #e0e0e0);\n display: flex;\n align-items: center;\n gap: 12px;\n }\n /* Override the generic .gear-icon { margin-left: auto } rule so the\n favorites gear stays flush-left instead of floating to the right of\n the flex row (same idea as .panel-identity .panel-gear does for\n real-panel headers). */\n .favorites-summary .favorites-gear {\n margin-left: 0;\n }\n /* Right-anchored cluster wrapping the shedding legend + W/A unit toggle.\n margin-left:auto moved here from .favorites-summary-unit-toggle so the\n legend and toggle cluster together, matching the real-panel header\n layout. */\n .favorites-summary-right {\n margin-left: auto;\n display: flex;\n align-items: center;\n gap: 16px;\n }\n .favorites-subdevices-section {\n padding: 8px 16px 0;\n }\n\n /* Favorites view: responsive grid of per-contributing-panel status cards. */\n .favorites-panel-stats-grid {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));\n gap: 12px;\n padding: 12px 24px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n .favorites-panel-card {\n background: var(--secondary-background-color, rgba(255, 255, 255, 0.04));\n border: 1px solid var(--divider-color, #333);\n border-radius: 8px;\n padding: 10px 14px;\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n .favorites-panel-card-title {\n font-size: 0.85em;\n font-weight: 600;\n color: var(--primary-text-color);\n opacity: 0.85;\n }\n .favorites-panel-card .controls-note {\n margin: 2px 0 6px;\n }\n .favorites-panel-card .panel-stats {\n gap: 10px 20px;\n }\n .favorites-panel-card .stat-value {\n font-size: 1.15em;\n }\n\n .stat { display: flex; flex-direction: column; }\n .stat-label { font-size: 0.8em; color: var(--secondary-text-color, #999); margin-bottom: 2px; }\n .stat-row { display: flex; align-items: baseline; gap: 2px; }\n .stat-value { font-size: 1.5em; font-weight: 700; color: var(--primary-text-color, #fff); }\n /* A sum that left out a term with no reading: dimmed, and marked as at least this much. */\n .stat-value.stat-partial { opacity: 0.7; }\n .stat-value.stat-partial::after { content: "+"; }\n .stat-unit { font-size: 0.7em; font-weight: 400; color: var(--secondary-text-color, #999); }\n\n .header-right { display: flex; flex-direction: column; align-items: flex-end; gap: 8px; padding-top: 8px; }\n .header-right-top { display: flex; gap: 20px; align-items: center; }\n .meta-item { font-size: 0.8em; color: var(--secondary-text-color, #999); }\n\n .shedding-legend { display: flex; gap: 12px; flex-wrap: wrap; justify-content: flex-end; }\n .shedding-legend-item { display: inline-flex; align-items: center; gap: 3px; }\n .shedding-legend-item span-icon { --mdc-icon-size: 16px; }\n .shedding-legend-secondary { --mdc-icon-size: 12px; opacity: 0.8; }\n .shedding-legend-text { font-size: 9px; font-weight: 600; }\n .shedding-legend-label { font-size: 0.7em; color: var(--secondary-text-color, #999); }\n\n .panel-gear {\n background: none;\n border: none;\n cursor: pointer;\n color: var(--secondary-text-color);\n opacity: 0.6;\n padding: 4px;\n margin-left: 8px;\n vertical-align: middle;\n }\n .panel-gear:hover { opacity: 1; }\n .header-center {\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-top: 8px;\n }\n .panel-identity .panel-gear {\n margin-left: 0;\n }\n .slide-confirm {\n position: relative;\n display: inline-flex;\n align-items: center;\n width: 160px;\n height: 28px;\n border-radius: 14px;\n background: color-mix(in srgb, var(--primary-color, #4dd9af) 20%, var(--secondary-background-color, #333));\n vertical-align: middle;\n overflow: hidden;\n user-select: none;\n touch-action: none;\n }\n .slide-confirm-text {\n position: absolute;\n width: 100%;\n text-align: center;\n font-size: 0.65em;\n font-weight: 600;\n color: var(--secondary-text-color, #999);\n pointer-events: none;\n z-index: 0;\n }\n .slide-confirm-knob {\n position: absolute;\n left: 2px;\n top: 2px;\n width: 24px;\n height: 24px;\n border-radius: 50%;\n background: var(--secondary-text-color, #666);\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: grab;\n z-index: 1;\n transition: none;\n }\n .slide-confirm-knob span-icon {\n --mdc-icon-size: 14px;\n color: var(--card-background-color, #1c1c1c);\n }\n .slide-confirm-knob.snapping {\n transition: left 0.25s ease;\n }\n .slide-confirm.confirmed {\n background: color-mix(in srgb, var(--state-active-color, var(--span-accent)) 25%, transparent);\n }\n .slide-confirm.confirmed .slide-confirm-text {\n color: var(--state-active-color, var(--span-accent));\n }\n .slide-confirm.confirmed .slide-confirm-knob {\n background: var(--state-active-color, var(--span-accent));\n }\n .switches-disabled .toggle-pill {\n opacity: 0.3;\n pointer-events: none;\n }\n /* The slider where the user may operate none of the view\'s controls: dimmed, and never armed. */\n .slide-confirm.slide-confirm-forbidden {\n opacity: 0.5;\n cursor: not-allowed;\n }\n .slide-confirm.slide-confirm-forbidden .slide-confirm-knob {\n cursor: not-allowed;\n }\n /* Its note, saying why: on a line of its own under the panel\'s name, or under each panel\'s name in the Favorites stats grid. */\n .controls-note {\n margin: 0;\n font-size: 0.8em;\n color: var(--secondary-text-color, #727272);\n }\n .panel-identity .controls-note {\n flex-basis: 100%;\n }\n .unit-toggle {\n display: inline-flex;\n background: var(--secondary-background-color, #333);\n border-radius: 6px;\n overflow: hidden;\n margin-left: 8px;\n }\n .unit-btn {\n padding: 4px 10px;\n border: none;\n background: none;\n color: var(--secondary-text-color);\n font-size: 0.75em;\n font-weight: 600;\n cursor: pointer;\n }\n .unit-btn.unit-active {\n background: var(--primary-color, #4dd9af);\n color: var(--text-primary-color, #000);\n }\n\n .monitoring-summary {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 6px 16px;\n font-size: 0.8em;\n background: rgba(76, 175, 80, 0.1);\n border: 1px solid var(--divider-color, #333);\n border-top: none;\n }\n .monitoring-active { color: #4caf50; }\n .monitoring-counts { display: flex; gap: 12px; }\n .count-warning { color: #ff9800; }\n .count-alert { color: #f44336; }\n .count-overrides { color: var(--secondary-text-color); }\n\n .panel-grid {\n display: grid;\n /* Five columns: left tab label, left cell, explicit 8px spacer,\n right cell, right tab label. Spacer is in-band rather than a\n column-gap so we can keep inter-cell space without paying an\n equal gap between each cell and its tab label. The tab columns\n are sized to fit a 2-digit breaker number (the font is 0.85em\n of the panel body ≈ 14px glyph width). */\n grid-template-columns: 14px 1fr 8px 1fr 14px;\n column-gap: 0;\n row-gap: 8px;\n align-items: stretch;\n }\n\n .tab-label {\n display: flex;\n align-items: center;\n font-size: 0.85em;\n font-weight: 600;\n color: var(--secondary-text-color, #999);\n user-select: none;\n }\n .tab-left { justify-content: flex-start; }\n .tab-right { justify-content: flex-end; }\n\n .circuit-slot {\n background: var(--secondary-background-color, var(--card-background-color, #2a2a2a));\n border: 1px solid var(--divider-color, #333);\n border-radius: 12px;\n padding: 14px 16px 20px;\n min-height: 140px;\n transition: opacity 0.3s;\n position: relative;\n overflow: hidden;\n }\n\n .circuit-col-span { min-height: 280px; }\n .circuit-row-span { border-left: 3px solid var(--span-accent); }\n .circuit-off .circuit-name,\n .circuit-off .breaker-badge,\n .circuit-off .power-value,\n .circuit-off .chart-container { opacity: 0.35; }\n .circuit-off .toggle-pill,\n .circuit-off .gear-icon { opacity: 1; }\n\n .circuit-empty {\n opacity: 0.2;\n min-height: 60px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-style: dashed;\n }\n .empty-label { color: var(--secondary-text-color, #999); font-size: 0.85em; }\n\n .circuit-header {\n display: flex;\n justify-content: space-between;\n align-items: flex-start;\n margin-bottom: 6px;\n gap: 8px;\n }\n\n .circuit-info { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; }\n\n .breaker-badge {\n background: color-mix(in srgb, var(--span-accent) 15%, transparent);\n color: var(--span-accent);\n font-size: 0.7em;\n font-weight: 700;\n padding: 2px 3px;\n border-radius: 4px;\n white-space: nowrap;\n border: 1px solid color-mix(in srgb, var(--span-accent) 25%, transparent);\n flex-shrink: 0;\n }\n\n /* The pencil that marks a rating from a copied package, a button so a tap or a key can show what it says. */\n .rating-user-set {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 24px;\n min-height: 24px;\n margin-left: 2px;\n padding: 0 2px;\n border: none;\n border-radius: 3px;\n background: none;\n color: inherit;\n font: inherit;\n font-weight: 400;\n line-height: inherit;\n cursor: help;\n }\n .rating-user-set:focus-visible {\n outline: 2px solid var(--primary-color, #03a9f4);\n outline-offset: 1px;\n }\n .rating-copied-note {\n display: block;\n margin-top: 2px;\n font-size: 0.85em;\n color: var(--secondary-text-color, #727272);\n white-space: normal;\n }\n .rating-copied-note[hidden] {\n display: none;\n }\n\n .circuit-name {\n font-size: 0.9em;\n font-weight: 500;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--primary-text-color, #e0e0e0);\n }\n\n .circuit-controls { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }\n\n /* Truncation-driven fold for By Panel breaker cells. The .is-folded\n class is added/removed by the JS observer in\n src/core/truncation-fold.ts when the .circuit-name actually\n ellipsizes. Pixel thresholds can\'t get this right because name\n length varies wildly per circuit (e.g. "Spa" vs\n "Commissioned PV System") — only measuring the live name vs its\n container catches the exact moment of truncation.\n\n When folded the nested flex wrappers (.circuit-header,\n .circuit-info, .circuit-controls, .circuit-status) collapse via\n \'display: contents\' so the leaf elements participate directly in\n the outer grid: name gets the whole first row, readings/controls/\n gear drop to a second row, chart stays as the full-width third. */\n .circuit-slot.is-folded {\n display: grid;\n /* Columns: badges + relay-toggle pack tight on the left, slack\n absorbed by the 1fr column between the relay and the power\n reading, keeping power + gear pinned to the right edge. The\n previous layout placed the slack between the shedding icon and\n the relay, which read as wasted padding the user pointed out. */\n grid-template-columns: auto auto auto auto 1fr auto auto;\n /* Rows: name and controls sized to content; chart absorbs any\n extra cell height. Without the explicit 1fr on row 3, a tall\n cell (e.g. .circuit-col-span\'s 280px min-height for 240V\n double-pole breakers) distributes excess space equally across\n all three rows via the default align-content:stretch, which\n pushes the chart down and vertically inflates the badge and\n relay toggle to fill the controls row. */\n grid-template-rows: auto auto 1fr;\n grid-template-areas:\n "name name name name name name name"\n "badge util shed status . power gear"\n "chart chart chart chart chart chart chart";\n row-gap: 6px;\n column-gap: 8px;\n }\n .circuit-slot.is-folded > .circuit-header,\n .circuit-slot.is-folded > .circuit-status,\n .circuit-slot.is-folded > .circuit-header > .circuit-info,\n .circuit-slot.is-folded > .circuit-header > .circuit-controls {\n display: contents;\n }\n .circuit-slot.is-folded .circuit-name {\n grid-area: name;\n justify-self: start;\n }\n .circuit-slot.is-folded .breaker-badge {\n grid-area: badge;\n }\n .circuit-slot.is-folded .utilization {\n grid-area: util;\n }\n .circuit-slot.is-folded .shedding-icon,\n .circuit-slot.is-folded .shedding-composite {\n grid-area: shed;\n }\n .circuit-slot.is-folded .toggle-pill {\n grid-area: status;\n justify-self: end;\n }\n .circuit-slot.is-folded .power-value {\n grid-area: power;\n justify-self: end;\n }\n .circuit-slot.is-folded .gear-icon.circuit-gear {\n grid-area: gear;\n justify-self: end;\n }\n .circuit-slot.is-folded > .chart-container {\n grid-area: chart;\n }\n\n .power-value { font-size: 0.9em; color: var(--primary-text-color, #fff); white-space: nowrap; }\n .power-value strong { font-weight: 700; font-size: 1.1em; }\n .power-unit { font-size: 0.8em; font-weight: 400; color: var(--secondary-text-color, #999); margin-left: 1px; }\n .circuit-producer .power-value strong { color: var(--info-color, #4fc3f7); }\n\n .toggle-pill {\n display: flex;\n align-items: center;\n gap: 3px;\n padding: 2px 4px;\n border-radius: 10px;\n cursor: pointer;\n font-size: 0.65em;\n font-weight: 600;\n transition: background 0.2s;\n user-select: none;\n min-width: 40px;\n }\n .toggle-on {\n padding-left: 6px;\n background: color-mix(in srgb, var(--state-active-color, var(--span-accent)) 25%, transparent);\n color: var(--state-active-color, var(--span-accent));\n }\n .toggle-off {\n padding-right: 6px;\n background: color-mix(in srgb, var(--secondary-text-color) 15%, transparent);\n color: var(--secondary-text-color, #999);\n }\n .toggle-knob {\n width: 14px;\n height: 14px;\n border-radius: 50%;\n transition: background 0.2s, margin 0.2s;\n }\n .toggle-on .toggle-knob {\n background: var(--state-active-color, var(--span-accent));\n margin-left: auto;\n }\n .toggle-off .toggle-knob {\n background: var(--secondary-text-color, #999);\n margin-right: auto;\n order: -1;\n }\n /* A switch Home Assistant reports unavailable: the relay state is still\n shown, but the pill cannot be operated. */\n .toggle-pill.toggle-unavailable {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n /* Locked switches dim every pill to 0.3; an inert one stays dimmer still. */\n .switches-disabled .toggle-pill.toggle-unavailable {\n opacity: 0.2;\n }\n /* A switch the user may not operate: the relay state is still shown, and the\n pill, titled with why, sends nothing. Dimmer still while the switches are locked. */\n .toggle-pill.toggle-forbidden {\n opacity: 0.4;\n cursor: not-allowed;\n }\n .switches-disabled .toggle-pill.toggle-forbidden {\n opacity: 0.2;\n }\n\n .circuit-status {\n display: flex;\n align-items: center;\n gap: 4px;\n margin-top: 4px;\n padding: 0 4px;\n }\n .shedding-icon { opacity: 0.8; cursor: default; }\n .shedding-composite {\n display: inline-flex;\n align-items: center;\n gap: 2px;\n }\n .shedding-icon-secondary { opacity: 0.8; }\n .shedding-label {\n font-size: 10px;\n font-weight: 600;\n opacity: 0.8;\n }\n .gear-icon {\n background: none;\n border: none;\n cursor: pointer;\n padding: 2px;\n opacity: 0.6;\n transition: opacity 0.2s;\n margin-left: auto;\n }\n .gear-icon:hover { opacity: 1; }\n .utilization {\n font-size: 0.75em;\n font-weight: 600;\n }\n .utilization-normal { color: #4caf50; }\n .utilization-warning { color: #ff9800; }\n .utilization-alert { color: #f44336; }\n .circuit-alert {\n border-color: #f44336 !important;\n box-shadow: 0 0 8px rgba(244, 67, 54, 0.3);\n }\n .chart-container {\n width: 100%;\n aspect-ratio: 4 / 1;\n margin-top: 4px;\n overflow: hidden;\n min-width: 0;\n }\n\n .sub-devices {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n gap: 12px;\n margin-bottom: 20px;\n padding-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n\n /* Meters outside the panel: no breaker space, so a strip above the grid. */\n .meters-strip {\n display: flex;\n flex-wrap: wrap;\n gap: 12px;\n margin-bottom: 20px;\n padding-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n .meters-title { flex-basis: 100%; font-size: 0.7em; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--span-accent); }\n .meter-tile {\n flex: 1 1 220px;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 6px;\n background: var(--secondary-background-color, var(--card-background-color, #2a2a2a));\n border: 1px solid var(--divider-color, #333);\n border-radius: 12px;\n padding: 12px 16px;\n }\n .meter-name {\n font-size: 0.9em;\n font-weight: 500;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--primary-text-color, #e0e0e0);\n }\n .meter-readings { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; font-size: 0.85em; color: var(--secondary-text-color, #999); }\n .meter-value { font-size: 1.05em; color: var(--primary-text-color, #fff); white-space: nowrap; }\n .meter-value strong { font-weight: 700; font-size: 1.1em; }\n .meter-direction:empty { display: none; }\n\n .sub-device {\n background: var(--secondary-background-color, var(--card-background-color, #2a2a2a));\n border: 1px solid var(--divider-color, #333);\n border-radius: 12px;\n padding: 14px 16px;\n }\n .sub-device-bess,\n .sub-device-full {\n grid-column: 1 / -1;\n }\n\n .sub-device-header { display: flex; gap: 10px; align-items: baseline; margin-bottom: 8px; }\n .sub-device-type { font-size: 0.7em; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--span-accent); }\n .sub-device-name { font-size: 0.85em; color: var(--secondary-text-color, #999); flex: 1; }\n .sub-power-value { font-size: 0.9em; color: var(--primary-text-color, #fff); white-space: nowrap; }\n .sub-power-value strong { font-weight: 700; font-size: 1.1em; }\n .sub-device .chart-container { margin-bottom: 8px; aspect-ratio: auto; }\n\n .bess-charts {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(0, 1fr));\n gap: 12px;\n margin-bottom: 10px;\n }\n .bess-chart-col { min-width: 0; }\n .bess-chart-title {\n font-size: 0.75em;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.04em;\n color: var(--secondary-text-color, #999);\n margin-bottom: 4px;\n }\n .bess-chart-col .chart-container { aspect-ratio: auto; }\n .sub-entity { display: flex; gap: 6px; padding: 3px 0; font-size: 0.85em; }\n .sub-entity-name { color: var(--secondary-text-color, #999); }\n .sub-entity-value { font-weight: 500; color: var(--primary-text-color, #e0e0e0); }\n .sub-identity { font-size: 0.85em; color: var(--secondary-text-color, #999); margin: 2px 0 6px; }\n .sub-note { font-size: 0.85em; color: var(--secondary-text-color, #999); font-style: italic; margin-top: 4px; }\n .sub-power-caption { font-size: 0.75em; color: var(--secondary-text-color, #999); margin-right: 6px; text-transform: uppercase; }\n\n /* ── Shared tab bar ────────────────────────────────────── */\n\n .shared-tab-bar {\n display: flex;\n gap: 0;\n margin-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n\n .shared-tab {\n padding: 8px 16px;\n cursor: pointer;\n font-size: 0.9em;\n font-weight: 500;\n color: var(--primary-text-color);\n opacity: 0.6;\n border: none;\n border-bottom: 2px solid transparent;\n background: none;\n transition: opacity 0.15s;\n }\n\n .shared-tab:hover {\n opacity: 0.85;\n }\n\n .shared-tab.active {\n opacity: 1;\n border-bottom-color: var(--span-accent);\n }\n\n /* ── List view search ──────────────────────────────────── */\n\n .list-search-container {\n margin-bottom: 12px;\n position: relative;\n }\n\n .list-search {\n width: 100%;\n padding: 8px 36px 8px 12px;\n border-radius: 8px;\n border: 1px solid var(--divider-color, #333);\n background: var(--secondary-background-color, #2a2a2a);\n color: var(--primary-text-color);\n font-size: 0.9em;\n box-sizing: border-box;\n outline: none;\n }\n\n .list-search:focus {\n border-color: var(--span-accent);\n }\n\n .list-search-clear {\n position: absolute;\n right: 8px;\n top: 50%;\n transform: translateY(-50%);\n background: none;\n border: none;\n color: var(--secondary-text-color);\n cursor: pointer;\n padding: 2px;\n display: flex;\n align-items: center;\n opacity: 0.7;\n }\n\n .list-search-clear:hover {\n opacity: 1;\n }\n\n .list-unit-toggle {\n display: inline-flex;\n margin-bottom: 12px;\n }\n\n /* ── List rows ─────────────────────────────────────────── */\n\n .list-view {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n /* Each circuit is wrapped in a .list-cell so the row + its optional\n expanded chart stay together. In single-column flex mode the cell\n just stacks naturally. In multi-column grid mode the cell becomes\n one grid item, so the chart is always in the same column as its\n row. Area headers (rendered as siblings, not inside a cell) span\n all columns via their inline "grid-column: 1 / -1". */\n .list-cell {\n display: flex;\n flex-direction: column;\n min-width: 0;\n }\n .list-view[data-columns="2"],\n .list-view[data-columns="3"] {\n display: grid;\n grid-template-columns: repeat(var(--list-cols), minmax(0, 1fr));\n gap: 6px 8px;\n flex-direction: initial;\n }\n /* On narrow viewports a 2/3-column list would squeeze rows into an\n unreadable shape, so force stacking regardless of user preference. */\n @media (max-width: 599px) {\n .list-view[data-columns="2"],\n .list-view[data-columns="3"] {\n display: flex;\n flex-direction: column;\n }\n }\n\n .list-row {\n display: flex;\n align-items: center;\n padding: 12px 16px;\n gap: 10px;\n /* min-width: 0 lets the row shrink below the sum of its\n non-shrinking children when its parent .list-cell is in a\n narrow CSS-grid track (multi-column list mode). Without this\n the row would maintain its intrinsic min-content width and\n overflow the cell, leaving the name unshrunk and the\n truncation-fold observer with no signal to react to. */\n min-width: 0;\n background: var(--card-background-color, #1c1c1c);\n border: 1px solid var(--divider-color, #333);\n border-radius: 8px;\n cursor: pointer;\n transition: background 0.15s;\n }\n\n .list-row:hover {\n background: var(--secondary-background-color, #2a2a2a);\n }\n\n .list-row.circuit-off {\n opacity: 0.5;\n }\n\n .list-row.list-row-expanded {\n border-bottom-left-radius: 0;\n border-bottom-right-radius: 0;\n border-bottom-color: transparent;\n }\n\n .list-circuit-name {\n flex: 1;\n color: var(--primary-text-color);\n font-size: 0.9em;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .list-status-badge {\n font-size: 0.75em;\n font-weight: 600;\n padding: 2px 8px;\n border-radius: 4px;\n flex-shrink: 0;\n }\n\n .list-status-on {\n color: #4dd9af;\n }\n\n .list-status-off {\n color: #f44336;\n }\n\n .list-power-value {\n font-size: 0.9em;\n font-weight: 600;\n flex-shrink: 0;\n /* No min-width / text-align:right: the old 70px right-aligned\n cell left a visible blank column for short readings (e.g.\n "1.3A" in a 70px slot), which robbed horizontal space from\n .list-circuit-name on narrow rows. Let the value hug the\n preceding relay control and size to its content so the freed\n width flows back into the flex:1 name column. */\n }\n\n .list-expand-toggle {\n background: none;\n border: none;\n color: var(--secondary-text-color);\n cursor: pointer;\n padding: 4px;\n transition: transform 0.2s;\n display: flex;\n align-items: center;\n flex-shrink: 0;\n }\n\n .list-expand-toggle.expanded {\n transform: rotate(180deg);\n }\n\n .list-row .gear-icon {\n background: transparent;\n border: none;\n padding: 2px;\n cursor: pointer;\n color: #555;\n display: inline-flex;\n align-items: center;\n }\n .list-row .gear-icon:hover {\n color: var(--primary-text-color);\n }\n\n /* Truncation-driven fold for list rows. The .is-folded class is\n added/removed by the JS observer in src/core/truncation-fold.ts\n when the .list-circuit-name actually ellipsizes — pixel breakpoints\n can\'t track this because name length varies wildly per circuit\n ("Spa" vs "Commissioned PV System") and any single threshold\n misfires for the other end of the range. Switch to a two-row grid\n so the name gets the full width (paired only with the expand\n chevron) and the badges/controls/reading/gear drop to a secondary\n row underneath. Named areas keep the CSS readable despite the flat\n HTML child order. */\n .list-row.is-folded {\n display: grid;\n /* Row 1: name spans the row up to the chevron at the trailing\n column. Row 2: badge + util + shed + relay-toggle pack left,\n the 1fr column absorbs slack between the relay and the power\n reading, power + gear stay pinned to the right edge. The\n earlier layout placed the slack between the shedding icon and\n the relay, which the user flagged as wasted padding. */\n grid-template-columns: auto auto auto auto 1fr auto auto;\n grid-template-areas:\n "name name name name name name chevron"\n "badge util shed status . power gear";\n row-gap: 6px;\n column-gap: 8px;\n }\n .list-row.is-folded > .list-circuit-name {\n grid-area: name;\n justify-self: start;\n }\n .list-row.is-folded > .list-expand-toggle {\n grid-area: chevron;\n }\n .list-row.is-folded > .breaker-badge {\n grid-area: badge;\n }\n .list-row.is-folded > .utilization {\n grid-area: util;\n }\n .list-row.is-folded > .shedding-icon,\n .list-row.is-folded > .shedding-composite {\n grid-area: shed;\n }\n .list-row.is-folded > .toggle-pill,\n .list-row.is-folded > .list-status-badge {\n grid-area: status;\n }\n .list-row.is-folded > .list-power-value {\n grid-area: power;\n justify-self: end;\n }\n .list-row.is-folded > .gear-icon.circuit-gear {\n grid-area: gear;\n justify-self: end;\n }\n\n /* ── Expanded circuit content ──────────────────────────── */\n\n .list-expanded-content {\n padding: 0;\n background: var(--card-background-color, #1c1c1c);\n border: 1px solid var(--divider-color, #333);\n border-top: none;\n border-radius: 0 0 8px 8px;\n margin-top: -6px;\n margin-bottom: 2px;\n }\n\n .circuit-slot.circuit-chart-only {\n border: none;\n margin: 0;\n background: none;\n padding: 8px 12px;\n min-height: 0;\n }\n\n /* ── Area headers ──────────────────────────────────────── */\n\n .area-header {\n padding: 16px 12px 6px;\n font-weight: 600;\n font-size: 0.85em;\n color: var(--secondary-text-color);\n text-transform: uppercase;\n letter-spacing: 0.05em;\n }\n\n /* ── No results ────────────────────────────────────────── */\n\n .list-no-results {\n padding: 24px;\n text-align: center;\n color: var(--secondary-text-color);\n }\n\n'),C([Ht({attribute:!1})],OI.prototype,"hass",void 0),C([Bt()],OI.prototype,"_config",void 0),C([Bt()],OI.prototype,"_discovered",void 0),C([Bt()],OI.prototype,"_discovering",void 0),C([Bt()],OI.prototype,"_awaitingLoad",void 0),C([Bt()],OI.prototype,"_discoveryFailed",void 0),C([Bt()],OI.prototype,"_topology",void 0),C([Bt()],OI.prototype,"_activeTab",void 0),OI=C([(t=>(e,n)=>{void 0!==n?n.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)})(c)],OI);class BI extends HTMLElement{constructor(){super(...arguments),this._config={},this._hass=null,this._panels=null,this._availableRoles=null,this._built=!1,this._discovering=!1,this._panelSelect=null,this._daysInput=null,this._hoursInput=null,this._minsInput=null,this._metricSelect=null,this._checkboxes={},this._entityContainers={},this._tabStyleSelect=null}setConfig(t){this._config={...t},this._updateControls()}set hass(t){this._hass=t,this._panels?this._built||this._buildEditor():this._discovering||this._discoverPanels()}async _discoverPanels(){if(!this._hass)return;let t;this._discovering=!0;try{t=await async function(t){const e={type:"config_entries/get",domain:l},[n,i]=await Promise.all([t.callWS({type:"config/device_registry/list"}),t.callWS(e)]),r=new Set(i.map(t=>t.entry_id));return n.filter(t=>Zn(t,r))}(this._hass)}catch(t){return void console.warn("SPAN Panel: the card editor could not list the panels",t)}finally{this._discovering=!1}this._panels=t.map(t=>{const e=(t.identifiers??[]).find(t=>t[0]===l)?.[1]??"",n=t.name_by_user??t.name??i("editor.panel_label");return{device_id:t.id,label:`${n} (${e})`}}),this._buildEditor()}_buildEditor(){this.innerHTML="",this._built=!0;const t=document.createElement("div");t.style.padding="16px";const e="\n width: 100%;\n padding: 10px 12px;\n border-radius: 8px;\n border: 1px solid var(--divider-color, #333);\n background: var(--card-background-color, var(--secondary-background-color, #1c1c1c));\n color: var(--primary-text-color, #e0e0e0);\n font-size: 1em;\n cursor: pointer;\n appearance: auto;\n box-sizing: border-box;\n ",n="display: block; font-weight: 500; margin-bottom: 8px; color: var(--primary-text-color);",i="margin-bottom: 16px;";this._buildPanelSelector(t,e,n,i),this._buildTimeWindow(t,e,n,i),this._buildMetricSelector(t,e,n,i),this._buildTabStyleSelector(t,e,n,i),this._buildSectionCheckboxes(t,n,i),this.appendChild(t),this._populateMetricSelect(),this._config.device_id&&this._discoverAvailableRoles(this._config.device_id)}_buildPanelSelector(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.panel_label"),a.style.cssText=n;const s=document.createElement("select");s.style.cssText=e;const l=document.createElement("option");if(l.value="",l.textContent=i("editor.select_panel"),s.appendChild(l),this._panels)for(const t of this._panels){const e=document.createElement("option");e.value=t.device_id,e.textContent=t.label,t.device_id===this._config.device_id&&(e.selected=!0),s.appendChild(e)}s.addEventListener("change",()=>{this._config={...this._config,device_id:s.value},this._fireConfigChanged(),this._discoverAvailableRoles(s.value)}),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._panelSelect=s}_buildTimeWindow(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.chart_window"),a.style.cssText=n;const s=document.createElement("div");s.style.cssText="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;";const l=e+"width: 70px; cursor: text;",c=(t,e,n,i)=>{const r=document.createElement("div");r.style.cssText="display: flex; align-items: center; gap: 6px;";const o=document.createElement("input");o.type="number",o.min=e,o.max=n,o.value=String(t),o.style.cssText=l;const a=document.createElement("span");return a.textContent=i,a.style.cssText="font-size: 0.9em; color: var(--secondary-text-color);",r.appendChild(o),r.appendChild(a),{wrap:r,input:o}},u=parseInt(String(this._config.history_days))||0,d=parseInt(String(this._config.history_hours))||0,h=parseInt(String(this._config.history_minutes))||0,p=c(u,"0","30",i("editor.days")),f=c(d,"0","23",i("editor.hours")),g=c(h,"0","59",i("editor.minutes")),m=()=>{this._config={...this._config,history_days:parseInt(p.input.value)||0,history_hours:parseInt(f.input.value)||0,history_minutes:parseInt(g.input.value)||0},this._fireConfigChanged()};p.input.addEventListener("change",m),f.input.addEventListener("change",m),g.input.addEventListener("change",m),s.appendChild(p.wrap),s.appendChild(f.wrap),s.appendChild(g.wrap),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._daysInput=p.input,this._hoursInput=f.input,this._minsInput=g.input}_buildMetricSelector(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.chart_metric"),a.style.cssText=n;const s=document.createElement("select");s.style.cssText=e,s.addEventListener("change",()=>{this._config={...this._config,chart_metric:s.value},this._fireConfigChanged()}),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._metricSelect=s}_buildTabStyleSelector(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.tab_style"),a.style.cssText=n;const s=document.createElement("select");s.style.cssText=e;const l=[{value:"text",text:i("editor.tab_style_text")},{value:"icon",text:i("editor.tab_style_icon")}];for(const t of l){const e=document.createElement("option");e.value=t.value,e.textContent=t.text,t.value===(this._config.tab_style??"text")&&(e.selected=!0),s.appendChild(e)}s.addEventListener("change",()=>{this._config={...this._config,tab_style:s.value},this._fireConfigChanged()}),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._tabStyleSelect=s}_buildSectionCheckboxes(t,e,n){const r=document.createElement("div");r.style.cssText=n;const o=document.createElement("label");o.textContent=i("editor.visible_sections"),o.style.cssText=e,r.appendChild(o);const a=[{key:"show_panel",label:i("editor.panel_circuits"),subDeviceType:null},{key:"show_battery",label:i("editor.battery_bess"),subDeviceType:"bess"},{key:"show_evse",label:i("editor.ev_charger_evse"),subDeviceType:"evse"},{key:"show_solar",label:i("editor.solar_pv"),subDeviceType:"pv"}];this._checkboxes={},this._entityContainers={};for(const t of a){const e=document.createElement("div");e.style.cssText="display: flex; align-items: center; gap: 8px; margin-bottom: 6px; cursor: pointer;";const n=document.createElement("input");n.type="checkbox",n.checked=!1!==this._config[t.key],n.style.cssText="width: 18px; height: 18px; cursor: pointer; accent-color: var(--primary-color);";const i=document.createElement("span");i.textContent=t.label,i.style.cssText="font-size: 0.9em; color: var(--primary-text-color); cursor: pointer;",e.appendChild(n),e.appendChild(i),r.appendChild(e),this._checkboxes[t.key]=n;let o=null;t.subDeviceType&&(o=document.createElement("div"),o.style.cssText="padding-left: 26px;",o.style.display=n.checked?"block":"none",r.appendChild(o),this._entityContainers[t.subDeviceType]=o),n.addEventListener("change",()=>{this._config={...this._config,[t.key]:n.checked},o&&(o.style.display=n.checked?"block":"none"),this._fireConfigChanged()})}t.appendChild(r)}_populateEntityCheckboxes(t){const e=this._config.visible_sub_entities??{},n="font-size: 0.85em; color: var(--primary-text-color); cursor: pointer;";for(const[r,o]of Object.entries(this._entityContainers)){o.innerHTML="";for(const a of HI(t,r)){const t=document.createElement("div");if(t.textContent=a.name,t.style.cssText="font-size: 0.85em; font-weight: 500; color: var(--secondary-text-color); margin: 8px 0 4px;",o.appendChild(t),0===a.entities.length){const t=document.createElement("div");t.textContent=i("editor.no_entities"),t.style.cssText=n,o.appendChild(t);continue}for(const{entityId:t,label:i}of a.entities){const r=document.createElement("div");r.style.cssText="display: flex; align-items: center; gap: 8px; margin-bottom: 5px; cursor: pointer;";const a=document.createElement("input");a.type="checkbox",a.checked=!0===e[t],a.style.cssText="width: 16px; height: 16px; cursor: pointer; accent-color: var(--primary-color);";const s=document.createElement("span");s.textContent=i,s.style.cssText=n,r.appendChild(a),r.appendChild(s),o.appendChild(r),a.addEventListener("change",()=>{const e={...this._config.visible_sub_entities??{}};a.checked?e[t]=!0:delete e[t],this._config={...this._config,visible_sub_entities:e},this._fireConfigChanged()})}}}}async _discoverAvailableRoles(t){if(this._hass&&t)try{const e=await this._hass.callWS({type:`${l}/panel_topology`,device_id:t}),n=new Set;for(const t of Object.values(e.circuits??{}))for(const e of Object.keys(t.entities??{}))n.add(e);this._availableRoles=n,this._populateMetricSelect(),e.sub_devices&&this._populateEntityCheckboxes(e.sub_devices)}catch{this._availableRoles=null,this._populateMetricSelect()}}_populateMetricSelect(){const t=this._metricSelect;if(!t)return;const e=this._config.chart_metric??o;t.innerHTML="";for(const[n,i]of Object.entries(y)){if(this._availableRoles&&!this._availableRoles.has(i.entityRole))continue;const r=document.createElement("option");r.value=n,r.textContent=i.label(),n===e&&(r.selected=!0),t.appendChild(r)}}_updateControls(){if(this._panelSelect&&(this._panelSelect.value=this._config.device_id??""),this._daysInput&&(this._daysInput.value=String(parseInt(String(this._config.history_days))||0)),this._hoursInput&&(this._hoursInput.value=String(parseInt(String(this._config.history_hours))||0)),this._minsInput&&(this._minsInput.value=String(parseInt(String(this._config.history_minutes))||0)),this._metricSelect&&(this._metricSelect.value=this._config.chart_metric??o),this._checkboxes)for(const[t,e]of Object.entries(this._checkboxes))e.checked=!1!==this._config[t];this._tabStyleSelect&&(this._tabStyleSelect.value=this._config.tab_style??"text")}_fireConfigChanged(){this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:this._config}}))}}function FI(t){return function(t){const e={};for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}({device_id:t.device_id,history_days:t.history_days,history_hours:t.history_hours,history_minutes:t.history_minutes,chart_metric:t.chart_metric,show_panel:t.show_panel,show_battery:t.show_battery,show_evse:t.show_evse,show_solar:t.show_solar,visible_sub_entities:t.visible_sub_entities,tab_style:t.tab_style})}class $I extends HTMLElement{static getStubConfig(t){const e=zI(t),n=Object.values(t.devices??{}).find(t=>Zn(t,e));return n?{type:h,device_id:n.id}:{type:h}}static async generate(t){return{type:"grid",cards:[{...FI(t),type:u,grid_options:{columns:"full"}}]}}}$I.registryDependencies=[];try{customElements.get("span-panel-card-editor")||customElements.define("span-panel-card-editor",BI)}catch{}try{customElements.get(p)||customElements.define(p,$I)}catch{}!function(t){const e=window.customCards??(window.customCards=[]);e.some(e=>e.type===t.type)||e.push(t)}({type:c,name:"SPAN Panel",description:"Physical panel layout with live power charts matching the SPAN frontend",preview:!0,getEntitySuggestion:function(t,e){const n=t.entities?.[e];if(n?.platform!==l||!n.device_id||!t.devices)return null;const i=t.devices[n.device_id],r=i?function(t,e,n){const i=t.parent_device_id||t.via_device_id,r=i?e[i]:t;return r&&Zn(r,n)&&function(t,e){return void 0!==t.config_entry_id&&t.config_entry_id===e.config_entry_id}(t,r)?r:null}(i,t.devices,zI(t)):null;return r?{config:{type:u,device_id:r.id}}:null}}),function(t){const e=window.customStrategies??(window.customStrategies=[]);e.some(e=>e.type===t.type&&e.strategyType===t.strategyType)||e.push(t)}({type:d,strategyType:"section",name:"SPAN Panel",description:"A SPAN panel's breaker layout and live power charts, at the section's full width"}),console.warn("%c SPAN-PANEL-CARD %c v0.12.1-beta.1 ","background: var(--primary-color, #4dd9af); color: var(--text-primary-color, #000); font-weight: 700; padding: 2px 6px; border-radius: 4px 0 0 4px;","background: var(--secondary-background-color, #333); color: var(--primary-text-color, #fff); padding: 2px 6px; border-radius: 0 4px 4px 0;"); diff --git a/custom_components/span_panel/frontend/dist/span-panel.js b/custom_components/span_panel/frontend/dist/span-panel.js index 22333348..eb1f905c 100644 --- a/custom_components/span_panel/frontend/dist/span-panel.js +++ b/custom_components/span_panel/frontend/dist/span-panel.js @@ -1,15 +1,15 @@ -let t="en";const e={en:{"tab.panel":"Panel","tab.by_panel":"By Panel","tab.by_activity":"By Activity","tab.by_area":"By Area","tab.monitoring":"Monitoring","tab.settings":"Settings","tab.adopted":"Adopted","list.search_placeholder":"Search circuits...","list.unassigned_area":"Unassigned","list.no_results":"No circuits found","monitoring.heading":"Monitoring","monitoring.global_settings":"Global Settings","monitoring.enabled":"Enabled","monitoring.continuous":"Continuous (%)","monitoring.spike":"Spike (%)","monitoring.window":"Window (min)","monitoring.cooldown":"Cooldown (min)","monitoring.monitored_points":"Monitored Points","monitoring.col.name":"Name","monitoring.col.continuous":"Continuous","monitoring.col.spike":"Spike","monitoring.col.window":"Window","monitoring.col.cooldown":"Cooldown","monitoring.rating":"Rating","monitoring.all_none":"All / None","monitoring.reset":"Reset","monitoring.limit_invalid":"Enter a whole number from {min} to {max}.","monitoring.enable_invalid":"Monitoring was not turned on: correct the fields marked.","monitoring.point_field":"{field} for {name}","monitoring.reset_point":"Reset {name}","monitoring.admin_only":"Only an administrator can change monitoring.","notification.heading":"Notification Settings","notification.targets":"Notify Targets","notification.none_selected":"None selected","notification.targets_button":"Notify Targets: {targets}","notification.no_targets":"No notify targets found","notification.all_targets":"All","notification.event_bus_target":"Event Bus (HA event bus)","notification.priority":"Priority","notification.priority.default":"Default","notification.priority.passive":"Passive","notification.priority.active":"Active","notification.priority.time_sensitive":"Time-sensitive","notification.priority.critical":"Critical","notification.hint.critical":"Overrides silent/DND","notification.hint.time_sensitive":"Breaks through Focus","notification.hint.passive":"Delivers silently","notification.hint.active":"Standard delivery","notification.title_template":"Title Template","notification.message_template":"Message Template","notification.placeholders":"Placeholders:","notification.event_bus_help":"Event Bus fires event type","notification.event_bus_payload":"with payload:","notification.test_label":"Test Notification","notification.test_button":"Send Test","notification.test_sending":"Sending...","notification.test_sent":"Test notification sent","error.prefix":"Error:","error.failed_save":"Failed to save","error.failed":"Failed","error.panel_offline":"SPAN Panel unreachable","error.panel_reconnected":"SPAN Panel reconnected","error.panel_offline_named":"{name} unreachable","error.panel_reconnected_named":"{name} reconnected","error.discovery_failed":"Unable to connect to SPAN Panel","error.relay_failed":"Unable to toggle relay","error.shedding_failed":"Unable to update shedding priority","error.threshold_failed":"Unable to save threshold","error.graph_horizon_failed":"Unable to update graph time horizon","error.favorites_fetch_failed":"Unable to load favorites","error.favorites_toggle_failed":"Unable to update favorite","error.history_failed":"Unable to load historical data","error.monitoring_failed":"Unable to load monitoring status","error.graph_settings_failed":"Unable to load graph settings","error.areas_failed":"Area assignments may be out of sync","error.retry":"Retry","card.connecting":"Connecting to SPAN Panel...","monitoringRating.none":"no rating","monitoringRating.copied":"{package} from your SPAN app (the panel publishes {panel} A)","monitoringRating.copied_unnamed":"Copied from your SPAN app","monitoringRating.judged_copied":"Judged against {rating} A: {copied}","settings.heading":"Settings","settings.description":"General integration settings (entity naming, device prefix, circuit numbers) are managed through the integration's options flow.","settings.open_link":"Open SPAN Panel Integration Settings","adopted.heading":"Adopted entities","adopted.description":"Vendor readings and adopted devices arrive with minimal metadata. Curate one to set its device class, statistics class, and prominence — saved changes reload the integration and apply from the next startup on.","adopted.filter_placeholder":"Filter by entity or device name","adopted.no_results":"No adopted entities match this filter","adopted.none":"This panel publishes nothing to curate.","adopted.load_failed":"Unable to load adopted entities","adopted.count":"{count} adopted","adopted.vendor_readings":"VENDOR READINGS","adopted.adopted_device":"ADOPTED DEVICE","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURATED","adopted.stale":"STALE","adopted.stale_note":"The panel no longer supports what was saved for: {fields}","adopted.enable_entity":"Enable entity","adopted.enabled":"ENABLED","adopted.disabled":"DISABLED","adopted.enable_note":"Enabled when saved — curating never enables on its own","adopted.registry_unavailable":"Enable and name become available once this entity exists in the registry.","adopted.name":"Name","adopted.device_class":"Device class","adopted.device_class_note":"choices limited by the panel's unit ({unit})","adopted.device_class_note_unitless":"choices limited by what the panel publishes","adopted.no_device_class":"No device class","adopted.statistics_class":"Statistics class","adopted.statistics_note":"long-term statistics begin after the next reload","adopted.no_statistics":"No statistics","adopted.prominence":"Prominence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Display unit","adopted.unit_as_published":"As published","adopted.precision":"Precision","adopted.precision_default":"Default","adopted.read_only":"read-only","adopted.settable":"settable","adopted.save":"Save","adopted.clear":"Clear curation","adopted.reload_note":"Saving reloads the SPAN Panel integration","adopted.saved":"Saved — the integration is reloading","adopted.confirm_heading":"Confirm statistics class","adopted.confirm_setting":"You are setting {name} to {value}.","adopted.confirm_clearing_subject":"You are clearing the statistics class on {name}.","adopted.confirm_total_increasing":"Total increasing treats every drop in the value as a meter reset. If this reading can decrease for any other reason, long-term statistics will be permanently corrupted — fixing the class later does not repair history already written.","adopted.confirm_clearing":"Long-term statistics stop being compiled for this entity, and Home Assistant raises a repair against the statistics already collected under the class you are removing.","adopted.save_anyway":"Save anyway","adopted.cancel":"Cancel","adopted.warn_total_increasing":"Saved as total increasing — every drop in the reading now counts as a meter reset.","adopted.warn_statistics_removed":"This entity has no statistics class any more; Home Assistant will raise a repair against the statistics already collected.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Panel monitoring settings","header.graph_settings":"Graph time horizon settings","header.site":"Site","header.grid":"Grid","header.upstream":"Upstream","header.downstream":"Downstream","header.solar":"Solar","header.battery":"Battery","header.toggle_units":"Toggle Watts / Amps","header.enable_switches":"Enable Switches","header.switches_enabled":"Switches Enabled","controls.admin_only":"Only an administrator can operate this panel's controls.","controls.disabled":"Control of this panel is switched off in its options.","controls.read_only":"Your Home Assistant account can't operate this panel's controls.","controls.entity_unauthorized":"Your Home Assistant account can't operate this control.","controls.not_operable":"You can't operate this panel's controls.","grid.unknown":"Unknown","grid.configure":"Configure circuit","grid.configure_subdevice":"Configure device","grid.on":"On","grid.off":"Off","grid.shared_switch":"Switches every circuit in this space","meters.title":"Meters","meters.importing":"importing","meters.exporting":"exporting","meters.imported":"imported","meters.exported":"exported","subdevice.ev_charger":"EV Charger","subdevice.battery":"Battery","subdevice.fallback":"Sub-device","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Power","subdevice.solar":"Solar","subdevice.solar_inverter":"Solar inverter","subdevice.site_total":"Site total","subdevice.in_site_total":"Included in the site total","sidepanel.graph_settings":"Graph Settings","sidepanel.global_defaults":"Global defaults for all circuits","sidepanel.favorites_subtitle":"Favorites","sidepanel.global_default":"Global Default","sidepanel.list_view_columns":"List View Columns","sidepanel.columns":"Columns","sidepanel.circuit_scales":"Circuit Graph Scales","sidepanel.subdevice_scales":"Sub-Device Graph Scales","sidepanel.reset_to_global":"Reset to global default","sidepanel.relay":"Relay","sidepanel.breaker":"Breaker","sidepanel.capacity":"{amps} A capacity","monitoringRating.title":"Breaker ratings from the SPAN app","monitoringRating.panel_rating":"Panel publishes {panel} A","monitoringRating.other_breaker":"Other breaker (A)","monitoringRating.other_breaker_label":"Other breaker in the space of {circuit}","monitoringRating.reset":"Remove copied ratings","monitoringRating.invalid_other":"Enter the other breaker's rating as a whole number of amps, 1 or more.","monitoringRating.guidance":"If your SPAN app shows two ratings for this circuit, such as 20-20A, enter the second one here. SPAN Panel MAIN 32 panels report only the first, and monitoring then judges this space against both breakers together.","monitoringRating.guidance_two_spaces":"If your SPAN app shows two ratings for this circuit, such as 20-30A, enter the second one here.","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 panels report only the average of this circuit's two legs, which can hide an overloaded leg. We recommend turning monitoring off for this circuit.","monitoringRating.turn_off_monitoring":"Turn off monitoring","monitoringRating.threshold_warning":"This circuit's custom thresholds are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass.","monitoringRating.threshold_warning_global":"The global thresholds this circuit uses are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass; change them under {settings} on the {tab} tab.","monitoringRating.use_global_thresholds":"Use global thresholds","monitoringRating.note_title":"Tandem breakers on SPAN Panel MAIN 32","monitoringRating.note_problem":"SPAN Panel MAIN 32 panels do not report which breakers are tandems, or the rating of a tandem's second breaker. A tandem puts two breakers in one space, but the panel reports it as one circuit with only the first breaker's rating, while one sensor reads both breakers together. A 20-20 tandem shows 20 A here and can carry 40 A, so monitoring raises false alerts on it.","monitoringRating.note_steps":"To fix this, copy the ratings from your SPAN app:","monitoringRating.note_step_find":"In the SPAN app, find each circuit whose breaker shows two ratings, such as 20-20A.","monitoringRating.note_step_enter":"In the table below, type the second rating in that circuit's {column} field. Then press Enter or move to the next field.","monitoringRating.note_step_single":"Leave the field empty for a circuit with a single breaker.","monitoringRating.note_judged":"Monitoring then judges that space against both breakers together: 40 A for a 20-20. Only monitoring uses the copy, and the circuit's Breaker Rating sensor still shows what the panel reports. To remove a copied rating, select ✕ beside its field.","monitoringRating.note_thresholds":"If you raised a tandem's thresholds above 100% to stop its alerts, select {reset} on its row. Those thresholds now apply to both breakers together.","monitoringRating.note_two_spaces":"For a circuit that spans two spaces, enter the second rating the same way if your SPAN app shows two, such as 20-30A. SPAN Panel MAIN 32 panels report only the average of such a circuit's two legs, which can hide an overloaded leg, so the copy can't be applied and we recommend turning monitoring off for that circuit.","monitoringRating.note_guide":"Read more in the guide to tandem and multi-load breakers.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remove copied ratings for {circuit}","monitoringRating.table_threshold_warning":"This circuit's thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Select {reset} to use the global thresholds.","monitoringRating.table_threshold_warning_global":"The global thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Change them under {settings} above.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Unable to update the ratings copied from the SPAN app","sidepanel.judged_against":"Judged against: {rating}","sidepanel.shedding_priority":"Shedding Priority","sidepanel.priority_label":"Priority","sidepanel.monitoring":"Monitoring","sidepanel.global":"Global","sidepanel.custom":"Custom","sidepanel.continuous_pct":"Continuous %","sidepanel.spike_pct":"Spike %","sidepanel.window_duration":"Window duration","sidepanel.cooldown":"Cooldown","sidepanel.favorite":"Favorite","sidepanel.save_to_favorites":"Save to favorites","panel.favorites":"Favorites","status.monitoring":"Monitoring","status.circuits":"circuits","status.mains":"mains","status.warning":"warning","status.warnings":"warnings","status.alert":"alert","status.alerts":"alerts","status.override":"override","status.overrides":"overrides","card.no_device":"Open the card editor and select your SPAN Panel device.","card.device_not_found":"Panel device not found. Check device_id in card config.","card.topology_error":"Topology response missing panel_size and no circuits found. Update the SPAN Panel integration.","card.panel_size_error":"Could not determine panel_size. No circuits found and no panel_size attribute. Update the SPAN Panel integration.","editor.panel_label":"SPAN Panel","editor.select_panel":"Select a panel...","editor.chart_window":"Chart time window","editor.days":"days","editor.hours":"hours","editor.minutes":"minutes","editor.chart_metric":"Chart metric","editor.visible_sections":"Visible sections","editor.panel_circuits":"Panel circuits","editor.battery_bess":"Battery (BESS)","editor.ev_charger_evse":"EV Charger (EVSE)","editor.solar_pv":"Solar (PV)","editor.no_entities":"No entities to show","editor.tab_style":"Tab Style","editor.tab_style_text":"Text","editor.tab_style_icon":"Icon","metric.power":"Power","metric.current":"Current","metric.soc":"State of Charge","metric.soe":"State of Energy","shedding.always_on":"Critical","shedding.never":"Non-sheddable","shedding.soc_threshold":"SoC Threshold","shedding.off_grid":"Sheddable","shedding.unknown":"Unknown","shedding.select.never":"Stays on in an outage","shedding.select.soc_threshold":"Stays on until battery threshold","shedding.select.off_grid":"Turns off in an outage"},es:{"tab.panel":"Panel","tab.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","tab.settings":"Configuración","tab.adopted":"Adoptadas","list.search_placeholder":"Buscar circuitos...","list.unassigned_area":"Sin asignar","list.no_results":"No se encontraron circuitos","monitoring.heading":"Monitoreo","monitoring.global_settings":"Configuración Global","monitoring.enabled":"Activado","monitoring.continuous":"Continuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Ventana (min)","monitoring.cooldown":"Enfriamiento (min)","monitoring.monitored_points":"Puntos Monitoreados","monitoring.col.name":"Nombre","monitoring.col.continuous":"Continuo","monitoring.col.spike":"Pico","monitoring.col.window":"Ventana","monitoring.col.cooldown":"Enfriamiento","monitoring.rating":"Calibre","monitoring.all_none":"Todos / Ninguno","monitoring.reset":"Restablecer","monitoring.limit_invalid":"Introduzca un número entero de {min} a {max}.","monitoring.enable_invalid":"No se activó el monitoreo: corrija los campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Restablecer {name}","monitoring.admin_only":"Solo un administrador puede cambiar el monitoreo.","notification.heading":"Configuración de Notificaciones","notification.targets":"Destinos de Notificación","notification.none_selected":"Ninguno seleccionado","notification.targets_button":"Destinos de Notificación: {targets}","notification.no_targets":"No se encontraron destinos de notificación","notification.all_targets":"Todos","notification.event_bus_target":"Bus de Eventos (bus de eventos de HA)","notification.priority":"Prioridad","notification.priority.default":"Predeterminado","notification.priority.passive":"Pasivo","notification.priority.active":"Activo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Anula silencio/No molestar","notification.hint.time_sensitive":"Atraviesa el modo Concentración","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega estándar","notification.title_template":"Plantilla de Título","notification.message_template":"Plantilla de Mensaje","notification.placeholders":"Variables:","notification.event_bus_help":"El Bus de Eventos dispara el tipo de evento","notification.event_bus_payload":"con datos:","notification.test_label":"Notificación de prueba","notification.test_button":"Enviar prueba","notification.test_sending":"Enviando...","notification.test_sent":"Notificación de prueba enviada","error.prefix":"Error:","error.failed_save":"Error al guardar","error.failed":"Falló","error.panel_offline":"SPAN Panel inaccesible","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inaccesible","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"No se puede conectar al SPAN Panel","error.relay_failed":"No se pudo cambiar el relé","error.shedding_failed":"No se pudo actualizar la prioridad de desconexión","error.threshold_failed":"No se pudo guardar el umbral","error.graph_horizon_failed":"No se pudo actualizar el horizonte temporal del gráfico","error.favorites_fetch_failed":"No se pudieron cargar los favoritos","error.favorites_toggle_failed":"No se pudo actualizar el favorito","error.history_failed":"No se pudieron cargar los datos históricos","error.monitoring_failed":"No se pudo cargar el estado de monitoreo","error.graph_settings_failed":"No se pudo cargar la configuración del gráfico","error.areas_failed":"Las asignaciones de áreas pueden estar desincronizadas","error.retry":"Reintentar","card.connecting":"Conectando al SPAN Panel...","monitoringRating.none":"sin calibre","monitoringRating.copied":"{package} de su app de SPAN (el panel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado de su app de SPAN","monitoringRating.judged_copied":"Evaluado según {rating} A: {copied}","settings.heading":"Configuración","settings.description":"La configuración general de la integración (nombres de entidades, prefijo de dispositivo, números de circuito) se administra a través del flujo de opciones de la integración.","settings.open_link":"Abrir Configuración de Integración SPAN Panel","adopted.heading":"Entidades adoptadas","adopted.description":"Las lecturas del proveedor y los dispositivos adoptados llegan con metadatos mínimos. Cura una para definir su clase de dispositivo, clase de estadísticas y prominencia — los cambios guardados recargan la integración y se aplican desde el siguiente arranque.","adopted.filter_placeholder":"Filtrar por nombre de entidad o dispositivo","adopted.no_results":"Ninguna entidad adoptada coincide con este filtro","adopted.none":"Este panel no publica nada que curar.","adopted.load_failed":"No se pudieron cargar las entidades adoptadas","adopted.count":"{count} adoptadas","adopted.vendor_readings":"LECTURAS DEL PROVEEDOR","adopted.adopted_device":"DISPOSITIVO ADOPTADO","adopted.via_panel":"vía SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"El panel ya no admite lo guardado para: {fields}","adopted.enable_entity":"Activar entidad","adopted.enabled":"ACTIVADA","adopted.disabled":"DESACTIVADA","adopted.enable_note":"Se activa al guardar — curar nunca activa por sí solo","adopted.registry_unavailable":"La activación y el nombre estarán disponibles cuando esta entidad exista en el registro.","adopted.name":"Nombre","adopted.device_class":"Clase de dispositivo","adopted.device_class_note":"opciones limitadas por la unidad del panel ({unit})","adopted.device_class_note_unitless":"opciones limitadas por lo que publica el panel","adopted.no_device_class":"Sin clase de dispositivo","adopted.statistics_class":"Clase de estadísticas","adopted.statistics_note":"las estadísticas a largo plazo comienzan tras la próxima recarga","adopted.no_statistics":"Sin estadísticas","adopted.prominence":"Prominencia","adopted.diagnostic":"Diagnóstico","adopted.standard":"Estándar","adopted.display_unit":"Unidad mostrada","adopted.unit_as_published":"Tal como se publica","adopted.precision":"Precisión","adopted.precision_default":"Predeterminada","adopted.read_only":"solo lectura","adopted.settable":"editable","adopted.save":"Guardar","adopted.clear":"Borrar curación","adopted.reload_note":"Guardar recarga la integración SPAN Panel","adopted.saved":"Guardado — la integración se está recargando","adopted.confirm_heading":"Confirmar clase de estadísticas","adopted.confirm_setting":"Vas a definir {name} como {value}.","adopted.confirm_clearing_subject":"Vas a borrar la clase de estadísticas de {name}.","adopted.confirm_total_increasing":"Total creciente interpreta cada caída del valor como un reinicio del contador. Si esta lectura puede disminuir por cualquier otro motivo, las estadísticas a largo plazo quedarán corrompidas de forma permanente — corregir la clase más tarde no repara el historial ya escrito.","adopted.confirm_clearing":"Dejarán de compilarse estadísticas a largo plazo para esta entidad, y Home Assistant abrirá una reparación sobre las estadísticas ya recogidas bajo la clase que estás quitando.","adopted.save_anyway":"Guardar de todos modos","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Guardado como total creciente — cada caída de la lectura cuenta ahora como un reinicio del contador.","adopted.warn_statistics_removed":"Esta entidad ya no tiene clase de estadísticas; Home Assistant abrirá una reparación sobre las estadísticas ya recogidas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configuración de monitoreo del panel","header.graph_settings":"Configuración del horizonte temporal del gráfico","header.site":"Sitio","header.grid":"Red","header.upstream":"Aguas arriba","header.downstream":"Aguas abajo","header.solar":"Solar","header.battery":"Batería","header.toggle_units":"Alternar Watts / Amperios","header.enable_switches":"Habilitar Interruptores","header.switches_enabled":"Interruptores Habilitados","controls.admin_only":"Solo un administrador puede operar los controles de este panel.","controls.disabled":"El control de este panel está desactivado en sus opciones.","controls.read_only":"Su cuenta de Home Assistant no puede operar los controles de este panel.","controls.entity_unauthorized":"Su cuenta de Home Assistant no puede operar este control.","controls.not_operable":"No puede operar los controles de este panel.","grid.unknown":"Desconocido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Enc","grid.off":"Apag","grid.shared_switch":"Conmuta todos los circuitos de este espacio","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Cargador EV","subdevice.battery":"Batería","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potencia","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total del sitio","subdevice.in_site_total":"Incluido en el total del sitio","sidepanel.graph_settings":"Configuración de Gráficos","sidepanel.global_defaults":"Valores predeterminados globales para todos los circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Predeterminado Global","sidepanel.list_view_columns":"Columnas de la lista","sidepanel.columns":"Columnas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Restablecer al valor global","sidepanel.relay":"Relé","sidepanel.breaker":"Interruptor","sidepanel.capacity":"capacidad de {amps} A","monitoringRating.title":"Calibres de interruptor de la app de SPAN","monitoringRating.panel_rating":"El panel publica {panel} A","monitoringRating.other_breaker":"Otro interruptor (A)","monitoringRating.other_breaker_label":"Otro interruptor en el espacio de {circuit}","monitoringRating.reset":"Quitar los calibres copiados","monitoringRating.invalid_other":"Introduzca el calibre del otro interruptor como un número entero de amperios, 1 o más.","monitoringRating.guidance":"Si su app de SPAN muestra dos calibres para este circuito, como 20-20A, introduzca aquí el segundo. Los paneles SPAN Panel MAIN 32 informan solo el primero, y el monitoreo juzga entonces este espacio según ambos interruptores juntos.","monitoringRating.guidance_two_spaces":"Si su app de SPAN muestra dos calibres para este circuito, como 20-30A, introduzca aquí el segundo.","monitoringRating.averaged_legs":"Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de este circuito, lo que puede ocultar una fase sobrecargada. Recomendamos desactivar el monitoreo de este circuito.","monitoringRating.turn_off_monitoring":"Desactivar el monitoreo","monitoringRating.threshold_warning":"Los umbrales personalizados de este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real.","monitoringRating.threshold_warning_global":"Los umbrales globales que usa este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real; cámbielos en {settings}, en la pestaña {tab}.","monitoringRating.use_global_thresholds":"Usar los umbrales globales","monitoringRating.note_title":"Interruptores tándem en SPAN Panel MAIN 32","monitoringRating.note_problem":"Los paneles SPAN Panel MAIN 32 no informan qué interruptores son tándem ni el calibre del segundo interruptor de un tándem. Un tándem pone dos interruptores en un espacio, pero el panel lo informa como un solo circuito con solo el calibre del primer interruptor, mientras un solo sensor lee ambos interruptores juntos. Un tándem 20-20 muestra 20 A aquí y puede llevar 40 A, por lo que el monitoreo genera falsas alertas en él.","monitoringRating.note_steps":"Para corregirlo, copie los calibres de su app de SPAN:","monitoringRating.note_step_find":"En la app de SPAN, busque cada circuito cuyo interruptor muestre dos calibres, como 20-20A.","monitoringRating.note_step_enter":"En la tabla de abajo, escriba el segundo calibre en el campo {column} de ese circuito. Luego pulse Intro o pase al siguiente campo.","monitoringRating.note_step_single":"Deje el campo vacío para un circuito con un solo interruptor.","monitoringRating.note_judged":"El monitoreo juzga entonces ese espacio según ambos interruptores juntos: 40 A para un 20-20. Solo el monitoreo usa la copia, y el sensor Breaker Rating del circuito sigue mostrando lo que informa el panel. Para quitar un calibre copiado, seleccione ✕ junto a su campo.","monitoringRating.note_thresholds":"Si subió los umbrales de un tándem por encima del 100 % para detener sus alertas, seleccione {reset} en su fila. Esos umbrales se aplican ahora a ambos interruptores juntos.","monitoringRating.note_two_spaces":"Para un circuito que ocupa dos espacios, introduzca el segundo calibre del mismo modo si su app de SPAN muestra dos, como 20-30A. Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de un circuito así, lo que puede ocultar una fase sobrecargada, por lo que la copia no se puede aplicar y recomendamos desactivar el monitoreo de ese circuito.","monitoringRating.note_guide":"Lea más en la guía de interruptores tándem y de cargas múltiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Quitar los calibres copiados de {circuit}","monitoringRating.table_threshold_warning":"Los umbrales de este circuito superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Seleccione {reset} para usar los umbrales globales.","monitoringRating.table_threshold_warning_global":"Los umbrales globales superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Cámbielos en {settings}, arriba.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"No se pudieron actualizar los calibres copiados de la app de SPAN","sidepanel.judged_against":"Evaluado según: {rating}","sidepanel.shedding_priority":"Prioridad de Desconexción","sidepanel.priority_label":"Prioridad","sidepanel.monitoring":"Monitoreo","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Continuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duración de ventana","sidepanel.cooldown":"Enfriamiento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Guardar en favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoreo","status.circuits":"circuitos","status.mains":"alimentación","status.warning":"advertencia","status.warnings":"advertencias","status.alert":"alerta","status.alerts":"alertas","status.override":"anulación","status.overrides":"anulaciones","card.no_device":"Abra el editor de tarjeta y seleccione su dispositivo SPAN Panel.","card.device_not_found":"Dispositivo de panel no encontrado. Verifique device_id en la configuración de la tarjeta.","card.topology_error":"La respuesta de topología no contiene panel_size y no se encontraron circuitos. Actualice la integración SPAN Panel.","card.panel_size_error":"No se pudo determinar panel_size. No se encontraron circuitos ni atributo panel_size. Actualice la integración SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Seleccione un panel...","editor.chart_window":"Ventana de tiempo del gráfico","editor.days":"días","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica del gráfico","editor.visible_sections":"Secciones visibles","editor.panel_circuits":"Circuitos del panel","editor.battery_bess":"Batería (BESS)","editor.ev_charger_evse":"Cargador EV (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"No hay entidades para mostrar","editor.tab_style":"Estilo de pestañas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícono","metric.power":"Potencia","metric.current":"Corriente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energía","shedding.always_on":"Crítico","shedding.never":"No desconectable","shedding.soc_threshold":"Umbral SoC","shedding.off_grid":"Desconectable","shedding.unknown":"Desconocido","shedding.select.never":"Permanece encendido en un corte","shedding.select.soc_threshold":"Encendido hasta umbral de batería","shedding.select.off_grid":"Se apaga en un corte"},fr:{"tab.panel":"Panneau","tab.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","tab.settings":"Paramètres","tab.adopted":"Adoptées","list.search_placeholder":"Rechercher des circuits...","list.unassigned_area":"Non attribué","list.no_results":"Aucun circuit trouvé","monitoring.heading":"Surveillance","monitoring.global_settings":"Paramètres Globaux","monitoring.enabled":"Activé","monitoring.continuous":"Continu (%)","monitoring.spike":"Pic (%)","monitoring.window":"Fenêtre (min)","monitoring.cooldown":"Refroidissement (min)","monitoring.monitored_points":"Points Surveillés","monitoring.col.name":"Nom","monitoring.col.continuous":"Continu","monitoring.col.spike":"Pic","monitoring.col.window":"Fenêtre","monitoring.col.cooldown":"Refroidissement","monitoring.rating":"Calibre","monitoring.all_none":"Tous / Aucun","monitoring.reset":"Réinitialiser","monitoring.limit_invalid":"Saisissez un nombre entier de {min} à {max}.","monitoring.enable_invalid":"La surveillance n'a pas été activée : corrigez les champs signalés.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Réinitialiser {name}","monitoring.admin_only":"Seul un administrateur peut modifier la surveillance.","notification.heading":"Paramètres de Notification","notification.targets":"Cibles de Notification","notification.none_selected":"Aucune sélection","notification.targets_button":"Cibles de Notification : {targets}","notification.no_targets":"Aucune cible de notification trouvée","notification.all_targets":"Tous","notification.event_bus_target":"Bus d'événements (bus d'événements HA)","notification.priority":"Priorité","notification.priority.default":"Par défaut","notification.priority.passive":"Passif","notification.priority.active":"Actif","notification.priority.time_sensitive":"Urgent","notification.priority.critical":"Critique","notification.hint.critical":"Outrepasse silencieux/NPD","notification.hint.time_sensitive":"Traverse le mode Concentration","notification.hint.passive":"Livraison silencieuse","notification.hint.active":"Livraison standard","notification.title_template":"Modèle de Titre","notification.message_template":"Modèle de Message","notification.placeholders":"Variables :","notification.event_bus_help":"Le Bus d'événements déclenche le type d'événement","notification.event_bus_payload":"avec les données :","notification.test_label":"Notification de test","notification.test_button":"Envoyer un test","notification.test_sending":"Envoi...","notification.test_sent":"Notification de test envoyée","error.prefix":"Erreur :","error.failed_save":"Échec de la sauvegarde","error.failed":"Échoué","error.panel_offline":"SPAN Panel inaccessible","error.panel_reconnected":"SPAN Panel reconnecté","error.panel_offline_named":"{name} inaccessible","error.panel_reconnected_named":"{name} reconnecté","error.discovery_failed":"Impossible de se connecter au SPAN Panel","error.relay_failed":"Impossible de basculer le relais","error.shedding_failed":"Impossible de mettre à jour la priorité de délestage","error.threshold_failed":"Impossible d'enregistrer le seuil","error.graph_horizon_failed":"Impossible de mettre à jour l'horizon temporel du graphique","error.favorites_fetch_failed":"Impossible de charger les favoris","error.favorites_toggle_failed":"Impossible de mettre à jour le favori","error.history_failed":"Impossible de charger les données historiques","error.monitoring_failed":"Impossible de charger l'état de surveillance","error.graph_settings_failed":"Impossible de charger les paramètres du graphique","error.areas_failed":"Les affectations de zones peuvent être désynchronisées","error.retry":"Réessayer","card.connecting":"Connexion au SPAN Panel...","monitoringRating.none":"aucun calibre","monitoringRating.copied":"{package} depuis votre application SPAN (le panneau publie {panel} A)","monitoringRating.copied_unnamed":"Copié depuis votre application SPAN","monitoringRating.judged_copied":"Évalué selon {rating} A : {copied}","settings.heading":"Paramètres","settings.description":"Les paramètres généraux de l'intégration (noms d'entités, préfixe de l'appareil, numéros de circuit) sont gérés via le flux d'options de l'intégration.","settings.open_link":"Ouvrir les Paramètres d'Intégration SPAN Panel","adopted.heading":"Entités adoptées","adopted.description":"Les relevés du fournisseur et les appareils adoptés arrivent avec des métadonnées minimales. Curez-en un pour définir sa classe d'appareil, sa classe de statistiques et sa proéminence — les modifications enregistrées rechargent l'intégration et s'appliquent dès le prochain démarrage.","adopted.filter_placeholder":"Filtrer par nom d'entité ou d'appareil","adopted.no_results":"Aucune entité adoptée ne correspond à ce filtre","adopted.none":"Ce panneau ne publie rien à curer.","adopted.load_failed":"Impossible de charger les entités adoptées","adopted.count":"{count} adoptées","adopted.vendor_readings":"RELEVÉS DU FOURNISSEUR","adopted.adopted_device":"APPAREIL ADOPTÉ","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURÉE","adopted.stale":"OBSOLÈTE","adopted.stale_note":"Le panneau ne prend plus en charge ce qui a été enregistré pour : {fields}","adopted.enable_entity":"Activer l'entité","adopted.enabled":"ACTIVÉE","adopted.disabled":"DÉSACTIVÉE","adopted.enable_note":"Activée à l'enregistrement — la curation n'active jamais d'elle-même","adopted.registry_unavailable":"L'activation et le nom seront disponibles dès que cette entité existera dans le registre.","adopted.name":"Nom","adopted.device_class":"Classe d'appareil","adopted.device_class_note":"choix limités par l'unité du panneau ({unit})","adopted.device_class_note_unitless":"choix limités par ce que le panneau publie","adopted.no_device_class":"Aucune classe d'appareil","adopted.statistics_class":"Classe de statistiques","adopted.statistics_note":"les statistiques à long terme commencent après le prochain rechargement","adopted.no_statistics":"Aucune statistique","adopted.prominence":"Proéminence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Unité affichée","adopted.unit_as_published":"Telle que publiée","adopted.precision":"Précision","adopted.precision_default":"Par défaut","adopted.read_only":"lecture seule","adopted.settable":"modifiable","adopted.save":"Enregistrer","adopted.clear":"Effacer la curation","adopted.reload_note":"L'enregistrement recharge l'intégration SPAN Panel","adopted.saved":"Enregistré — l'intégration se recharge","adopted.confirm_heading":"Confirmer la classe de statistiques","adopted.confirm_setting":"Vous définissez {name} sur {value}.","adopted.confirm_clearing_subject":"Vous effacez la classe de statistiques de {name}.","adopted.confirm_total_increasing":"Total croissant interprète chaque baisse de la valeur comme une remise à zéro du compteur. Si ce relevé peut diminuer pour une autre raison, les statistiques à long terme seront corrompues de façon permanente — corriger la classe plus tard ne répare pas l'historique déjà écrit.","adopted.confirm_clearing":"Les statistiques à long terme cesseront d'être compilées pour cette entité, et Home Assistant ouvrira une réparation sur les statistiques déjà collectées sous la classe que vous retirez.","adopted.save_anyway":"Enregistrer quand même","adopted.cancel":"Annuler","adopted.warn_total_increasing":"Enregistré en total croissant — chaque baisse du relevé compte désormais comme une remise à zéro du compteur.","adopted.warn_statistics_removed":"Cette entité n'a plus de classe de statistiques ; Home Assistant ouvrira une réparation sur les statistiques déjà collectées.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Paramètres de surveillance du panneau","header.graph_settings":"Paramètres d'horizon temporel du graphique","header.site":"Site","header.grid":"Réseau","header.upstream":"Amont","header.downstream":"Aval","header.solar":"Solaire","header.battery":"Batterie","header.toggle_units":"Basculer Watts / Ampères","header.enable_switches":"Activer les interrupteurs","header.switches_enabled":"Interrupteurs activés","controls.admin_only":"Seul un administrateur peut utiliser les commandes de ce panneau.","controls.disabled":"La commande de ce panneau est désactivée dans ses options.","controls.read_only":"Votre compte Home Assistant ne peut pas utiliser les commandes de ce panneau.","controls.entity_unauthorized":"Votre compte Home Assistant ne peut pas utiliser cette commande.","controls.not_operable":"Vous ne pouvez pas utiliser les commandes de ce panneau.","grid.unknown":"Inconnu","grid.configure":"Configurer le circuit","grid.configure_subdevice":"Configurer l'appareil","grid.on":"On","grid.off":"Off","grid.shared_switch":"Commute tous les circuits de cet emplacement","meters.title":"Compteurs","meters.importing":"en import","meters.exporting":"en export","meters.imported":"importés","meters.exported":"exportés","subdevice.ev_charger":"Chargeur VE","subdevice.battery":"Batterie","subdevice.fallback":"Sous-appareil","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Puissance","subdevice.solar":"Solaire","subdevice.solar_inverter":"Onduleur solaire","subdevice.site_total":"Total du site","subdevice.in_site_total":"Inclus dans le total du site","sidepanel.graph_settings":"Paramètres des Graphiques","sidepanel.global_defaults":"Valeurs par défaut globales pour tous les circuits","sidepanel.favorites_subtitle":"Favoris","sidepanel.global_default":"Défaut Global","sidepanel.list_view_columns":"Colonnes de la liste","sidepanel.columns":"Colonnes","sidepanel.circuit_scales":"Échelles des Graphiques de Circuits","sidepanel.subdevice_scales":"Échelles des Graphiques de Sous-Appareils","sidepanel.reset_to_global":"Réinitialiser à la valeur globale","sidepanel.relay":"Relais","sidepanel.breaker":"Disjoncteur","sidepanel.capacity":"capacité de {amps} A","monitoringRating.title":"Calibres des disjoncteurs dans l'application SPAN","monitoringRating.panel_rating":"Le panneau publie {panel} A","monitoringRating.other_breaker":"Autre disjoncteur (A)","monitoringRating.other_breaker_label":"Autre disjoncteur dans l'emplacement de {circuit}","monitoringRating.reset":"Supprimer les calibres copiés","monitoringRating.invalid_other":"Saisissez le calibre de l'autre disjoncteur en nombre entier d'ampères, 1 ou plus.","monitoringRating.guidance":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-20A, saisissez ici le second. Les panneaux SPAN Panel MAIN 32 n'indiquent que le premier, et la surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble.","monitoringRating.guidance_two_spaces":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-30A, saisissez ici le second.","monitoringRating.averaged_legs":"Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases de ce circuit, ce qui peut masquer une phase en surcharge. Nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.turn_off_monitoring":"Désactiver la surveillance","monitoringRating.threshold_warning":"Les seuils personnalisés de ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge.","monitoringRating.threshold_warning_global":"Les seuils globaux qu'utilise ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge ; modifiez-les dans {settings}, onglet {tab}.","monitoringRating.use_global_thresholds":"Utiliser les seuils globaux","monitoringRating.note_title":"Disjoncteurs tandem sur SPAN Panel MAIN 32","monitoringRating.note_problem":"Les panneaux SPAN Panel MAIN 32 n'indiquent pas quels disjoncteurs sont des tandems, ni le calibre du second disjoncteur d'un tandem. Un tandem place deux disjoncteurs dans un emplacement, mais le panneau l'indique comme un seul circuit avec le calibre du premier disjoncteur seulement, tandis qu'un seul capteur lit les deux disjoncteurs ensemble. Un tandem 20-20 affiche 20 A ici et peut supporter 40 A, si bien que la surveillance déclenche de fausses alertes sur lui.","monitoringRating.note_steps":"Pour corriger cela, copiez les calibres depuis votre application SPAN :","monitoringRating.note_step_find":"Dans l'application SPAN, trouvez chaque circuit dont le disjoncteur affiche deux calibres, par exemple 20-20A.","monitoringRating.note_step_enter":"Dans le tableau ci-dessous, saisissez le second calibre dans le champ {column} de ce circuit. Appuyez ensuite sur Entrée ou passez au champ suivant.","monitoringRating.note_step_single":"Laissez le champ vide pour un circuit à disjoncteur unique.","monitoringRating.note_judged":"La surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble : 40 A pour un 20-20. Seule la surveillance utilise la copie, et le capteur Breaker Rating du circuit affiche toujours ce que le panneau indique. Pour supprimer un calibre copié, sélectionnez ✕ à côté de son champ.","monitoringRating.note_thresholds":"Si vous avez relevé les seuils d'un tandem au-dessus de 100 % pour faire cesser ses alertes, sélectionnez {reset} sur sa ligne. Ces seuils s'appliquent désormais aux deux disjoncteurs ensemble.","monitoringRating.note_two_spaces":"Pour un circuit qui occupe deux emplacements, saisissez le second calibre de la même façon si votre application SPAN en affiche deux, par exemple 20-30A. Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases d'un tel circuit, ce qui peut masquer une phase en surcharge : la copie ne peut donc pas être appliquée, et nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.note_guide":"Pour en savoir plus, consultez le guide des disjoncteurs tandem et à charges multiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Supprimer les calibres copiés de {circuit}","monitoringRating.table_threshold_warning":"Les seuils de ce circuit dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Sélectionnez {reset} pour utiliser les seuils globaux.","monitoringRating.table_threshold_warning_global":"Les seuils globaux dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Modifiez-les dans {settings} ci-dessus.","monitoringRating.warning_announcement":"{circuit} : {warning}","error.package_ratings_failed":"Impossible de mettre à jour les calibres copiés depuis l'application SPAN","sidepanel.judged_against":"Évalué selon : {rating}","sidepanel.shedding_priority":"Priorité de Délestage","sidepanel.priority_label":"Priorité","sidepanel.monitoring":"Surveillance","sidepanel.global":"Global","sidepanel.custom":"Personnalisé","sidepanel.continuous_pct":"Continu %","sidepanel.spike_pct":"Pic %","sidepanel.window_duration":"Durée de fenêtre","sidepanel.cooldown":"Refroidissement","sidepanel.favorite":"Favori","sidepanel.save_to_favorites":"Enregistrer dans les favoris","panel.favorites":"Favoris","status.monitoring":"Surveillance","status.circuits":"circuits","status.mains":"alimentation","status.warning":"avertissement","status.warnings":"avertissements","status.alert":"alerte","status.alerts":"alertes","status.override":"remplacement","status.overrides":"remplacements","card.no_device":"Ouvrez l'éditeur de carte et sélectionnez votre appareil SPAN Panel.","card.device_not_found":"Appareil de panneau introuvable. Vérifiez device_id dans la configuration de la carte.","card.topology_error":"La réponse de topologie ne contient pas panel_size et aucun circuit trouvé. Mettez à jour l'intégration SPAN Panel.","card.panel_size_error":"Impossible de déterminer panel_size. Aucun circuit trouvé et aucun attribut panel_size. Mettez à jour l'intégration SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Sélectionnez un panneau...","editor.chart_window":"Fenêtre de temps du graphique","editor.days":"jours","editor.hours":"heures","editor.minutes":"minutes","editor.chart_metric":"Métrique du graphique","editor.visible_sections":"Sections visibles","editor.panel_circuits":"Circuits du panneau","editor.battery_bess":"Batterie (BESS)","editor.ev_charger_evse":"Chargeur VE (EVSE)","editor.solar_pv":"Solaire (PV)","editor.no_entities":"Aucune entité à afficher","editor.tab_style":"Style des onglets","editor.tab_style_text":"Texte","editor.tab_style_icon":"Icône","metric.power":"Puissance","metric.current":"Courant","metric.soc":"État de Charge","metric.soe":"État d'Énergie","shedding.always_on":"Critique","shedding.never":"Non délestable","shedding.soc_threshold":"Seuil SoC","shedding.off_grid":"Délestable","shedding.unknown":"Inconnu","shedding.select.never":"Reste allumé en cas de coupure","shedding.select.soc_threshold":"Allumé jusqu'au seuil batterie","shedding.select.off_grid":"S'éteint en cas de coupure"},ja:{"tab.panel":"パネル","tab.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","tab.settings":"設定","tab.adopted":"採用済み","list.search_placeholder":"回路を検索...","list.unassigned_area":"未割り当て","list.no_results":"回路が見つかりません","monitoring.heading":"モニタリング","monitoring.global_settings":"グローバル設定","monitoring.enabled":"有効","monitoring.continuous":"継続 (%)","monitoring.spike":"スパイク (%)","monitoring.window":"ウィンドウ (分)","monitoring.cooldown":"クールダウン (分)","monitoring.monitored_points":"監視ポイント","monitoring.col.name":"名前","monitoring.col.continuous":"継続","monitoring.col.spike":"スパイク","monitoring.col.window":"ウィンドウ","monitoring.col.cooldown":"クールダウン","monitoring.rating":"定格","monitoring.all_none":"全選択 / 全解除","monitoring.reset":"リセット","monitoring.limit_invalid":"{min} から {max} までの整数を入力してください。","monitoring.enable_invalid":"モニタリングは有効になっていません。マークされた項目を修正してください。","monitoring.point_field":"{name}の{field}","monitoring.reset_point":"{name}をリセット","monitoring.admin_only":"モニタリングを変更できるのは管理者のみです。","notification.heading":"通知設定","notification.targets":"通知先","notification.none_selected":"未選択","notification.targets_button":"通知先: {targets}","notification.no_targets":"通知先が見つかりません","notification.all_targets":"すべて","notification.event_bus_target":"イベントバス (HAイベントバス)","notification.priority":"優先度","notification.priority.default":"デフォルト","notification.priority.passive":"パッシブ","notification.priority.active":"アクティブ","notification.priority.time_sensitive":"緊急","notification.priority.critical":"重大","notification.hint.critical":"サイレント/おやすみモードを無視","notification.hint.time_sensitive":"集中モードを突破","notification.hint.passive":"サイレント配信","notification.hint.active":"標準配信","notification.title_template":"タイトルテンプレート","notification.message_template":"メッセージテンプレート","notification.placeholders":"プレースホルダー:","notification.event_bus_help":"イベントバスが発行するイベントタイプ","notification.event_bus_payload":"ペイロード:","notification.test_label":"テスト通知","notification.test_button":"テスト送信","notification.test_sending":"送信中...","notification.test_sent":"テスト通知を送信しました","error.prefix":"エラー:","error.failed_save":"保存に失敗","error.failed":"失敗","error.panel_offline":"SPANパネルに接続できません","error.panel_reconnected":"SPANパネルが再接続されました","error.panel_offline_named":"{name}に接続できません","error.panel_reconnected_named":"{name}が再接続されました","error.discovery_failed":"SPANパネルへの接続に失敗しました","error.relay_failed":"リレーの切り替えに失敗しました","error.shedding_failed":"シェディング優先度の更新に失敗しました","error.threshold_failed":"しきい値の保存に失敗しました","error.graph_horizon_failed":"グラフの時間範囲の更新に失敗しました","error.favorites_fetch_failed":"お気に入りの読み込みに失敗しました","error.favorites_toggle_failed":"お気に入りの更新に失敗しました","error.history_failed":"履歴データの読み込みに失敗しました","error.monitoring_failed":"監視ステータスの読み込みに失敗しました","error.graph_settings_failed":"グラフ設定の読み込みに失敗しました","error.areas_failed":"エリア割り当てが同期されていない可能性があります","error.retry":"再試行","card.connecting":"SPANパネルに接続中...","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","settings.heading":"設定","settings.description":"統合の一般設定(エンティティ名、デバイスプレフィックス、回路番号)は統合のオプションフローで管理されます。","settings.open_link":"SPAN Panel統合設定を開く","adopted.heading":"採用済みエンティティ","adopted.description":"ベンダーの測定値と採用済みデバイスは最小限のメタデータで登録されます。キュレーションでデバイスクラス、統計クラス、表示区分を設定できます。保存すると統合が再読み込みされ、次回の起動から適用されます。","adopted.filter_placeholder":"エンティティ名またはデバイス名で絞り込み","adopted.no_results":"この条件に一致する採用済みエンティティはありません","adopted.none":"このパネルにキュレーション対象はありません。","adopted.load_failed":"採用済みエンティティを読み込めません","adopted.count":"{count} 件","adopted.vendor_readings":"ベンダー測定値","adopted.adopted_device":"採用済みデバイス","adopted.via_panel":"SPAN Panel 経由","adopted.curated":"キュレーション済み","adopted.stale":"無効","adopted.stale_note":"パネルは保存された次の項目をサポートしなくなりました: {fields}","adopted.enable_entity":"エンティティを有効化","adopted.enabled":"有効","adopted.disabled":"無効","adopted.enable_note":"保存時に有効化されます — キュレーション自体が有効化することはありません","adopted.registry_unavailable":"有効化・名前は、このエンティティがレジストリに登録された後に利用できます。","adopted.name":"名前","adopted.device_class":"デバイスクラス","adopted.device_class_note":"パネルの単位({unit})により選択肢が制限されます","adopted.device_class_note_unitless":"パネルが公開する内容により選択肢が制限されます","adopted.no_device_class":"デバイスクラスなし","adopted.statistics_class":"統計クラス","adopted.statistics_note":"長期統計は次回の再読み込み後に開始されます","adopted.no_statistics":"統計なし","adopted.prominence":"表示区分","adopted.diagnostic":"診断","adopted.standard":"標準","adopted.display_unit":"表示単位","adopted.unit_as_published":"公開されたまま","adopted.precision":"小数点以下桁数","adopted.precision_default":"既定","adopted.read_only":"読み取り専用","adopted.settable":"書き込み可","adopted.save":"保存","adopted.clear":"キュレーションを消去","adopted.reload_note":"保存すると SPAN Panel 統合が再読み込みされます","adopted.saved":"保存しました — 統合を再読み込みしています","adopted.confirm_heading":"統計クラスの確認","adopted.confirm_setting":"{name} を {value} に設定しようとしています。","adopted.confirm_clearing_subject":"{name} の統計クラスを消去しようとしています。","adopted.confirm_total_increasing":"積算増加は値の低下をすべてメーターのリセットとして扱います。この測定値が他の理由でも下がる場合、長期統計は恒久的に破損します。後からクラスを直しても、既に書き込まれた履歴は修復されません。","adopted.confirm_clearing":"このエンティティの長期統計は収集されなくなり、削除するクラスの下で既に収集された統計について Home Assistant が修復項目を作成します。","adopted.save_anyway":"それでも保存","adopted.cancel":"キャンセル","adopted.warn_total_increasing":"積算増加として保存しました — 測定値の低下はすべてメーターのリセットとして数えられます。","adopted.warn_statistics_removed":"このエンティティに統計クラスはなくなりました。既に収集された統計について Home Assistant が修復項目を作成します。","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"パネルモニタリング設定","header.graph_settings":"グラフ時間範囲設定","header.site":"サイト","header.grid":"グリッド","header.upstream":"上流","header.downstream":"下流","header.solar":"ソーラー","header.battery":"バッテリー","header.toggle_units":"ワット/アンペア切り替え","header.enable_switches":"スイッチを有効化","header.switches_enabled":"スイッチ有効","controls.admin_only":"このパネルのコントロールを操作できるのは管理者のみです。","controls.disabled":"このパネルのコントロールはオプションで無効になっています。","controls.read_only":"お使いのHome Assistantアカウントでは、このパネルのコントロールを操作できません。","controls.entity_unauthorized":"お使いのHome Assistantアカウントでは、このコントロールを操作できません。","controls.not_operable":"このパネルのコントロールは操作できません。","grid.unknown":"不明","grid.configure":"回路を設定","grid.configure_subdevice":"デバイスを設定","grid.on":"オン","grid.off":"オフ","grid.shared_switch":"このスペースのすべての回路を切り替えます","meters.title":"メーター","meters.importing":"受電中","meters.exporting":"送電中","meters.imported":"受電","meters.exported":"送電","subdevice.ev_charger":"EV充電器","subdevice.battery":"バッテリー","subdevice.fallback":"サブデバイス","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"電力","subdevice.solar":"ソーラー","subdevice.solar_inverter":"ソーラーインバーター","subdevice.site_total":"サイト合計","subdevice.in_site_total":"サイト合計に含まれます","sidepanel.graph_settings":"グラフ設定","sidepanel.global_defaults":"全回路のグローバルデフォルト","sidepanel.favorites_subtitle":"お気に入り","sidepanel.global_default":"グローバルデフォルト","sidepanel.list_view_columns":"リスト表示の列数","sidepanel.columns":"列","sidepanel.circuit_scales":"回路グラフスケール","sidepanel.subdevice_scales":"サブデバイスグラフスケール","sidepanel.reset_to_global":"グローバルにリセット","sidepanel.relay":"リレー","sidepanel.breaker":"ブレーカー","sidepanel.capacity":"容量 {amps} A","monitoringRating.title":"SPAN アプリのブレーカー定格","monitoringRating.panel_rating":"パネルの公開値 {panel} A","monitoringRating.other_breaker":"もう一方のブレーカー (A)","monitoringRating.other_breaker_label":"{circuit} のスペースにあるもう一方のブレーカー","monitoringRating.reset":"コピーした定格を削除","monitoringRating.invalid_other":"もう一方のブレーカーの定格を 1 以上の整数のアンペアで入力してください。","monitoringRating.guidance":"SPAN アプリでこの回路に 20-20A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。SPAN Panel MAIN 32 パネルが報告するのは 1 つ目だけで、モニタリングはこのスペースを両方のブレーカーの合計で判定します。","monitoringRating.guidance_two_spaces":"SPAN アプリでこの回路に 20-30A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 パネルはこの回路の 2 本の線の平均値しか報告しないため、過負荷の線が見えなくなることがあります。この回路のモニタリングをオフにすることをおすすめします。","monitoringRating.turn_off_monitoring":"モニタリングをオフにする","monitoringRating.threshold_warning":"この回路のカスタムしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。","monitoringRating.threshold_warning_global":"この回路が使用するグローバルしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。{tab}タブの{settings}で変更してください。","monitoringRating.use_global_thresholds":"グローバルしきい値を使用","monitoringRating.note_title":"SPAN Panel MAIN 32 のタンデムブレーカー","monitoringRating.note_problem":"SPAN Panel MAIN 32 パネルは、どのブレーカーがタンデムかも、タンデムの 2 つ目のブレーカーの定格も報告しません。タンデムは 1 つのスペースに 2 つのブレーカーを収めますが、パネルはそれを 1 つ目のブレーカーの定格だけを持つ 1 つの回路として報告し、1 つのセンサーが両方のブレーカーの合計を読み取ります。20-20 のタンデムはここでは 20 A と表示されますが 40 A まで流せるため、モニタリングが誤ったアラートを出します。","monitoringRating.note_steps":"これを直すには、次の手順で SPAN アプリから定格をコピーします。","monitoringRating.note_step_find":"SPAN アプリで、ブレーカーに 20-20A のように 2 つの定格が表示されている回路をすべて探します。","monitoringRating.note_step_enter":"下の表で、その回路の{column}フィールドに 2 つ目の定格を入力します。続けて Enter キーを押すか、次のフィールドに移動します。","monitoringRating.note_step_single":"ブレーカーが 1 つだけの回路では、フィールドを空のままにします。","monitoringRating.note_judged":"するとモニタリングは、そのスペースを両方のブレーカーの合計で判定します。20-20 なら 40 A です。コピーを使うのはモニタリングだけで、回路の Breaker Rating センサーは引き続きパネルが報告する値を表示します。コピーした定格を削除するには、フィールドの横の ✕ を選択します。","monitoringRating.note_thresholds":"アラートを止めるためにタンデムのしきい値を 100% より上に上げていた場合は、その行の{reset}を選択してください。それらのしきい値は今後、両方のブレーカーの合計に適用されます。","monitoringRating.note_two_spaces":"2 つのスペースにまたがる回路でも、SPAN アプリに 20-30A のように 2 つの定格が表示されていれば、同じ方法で 2 つ目の定格を入力します。SPAN Panel MAIN 32 パネルはそのような回路の 2 本の線の平均値しか報告せず、過負荷の線が見えなくなることがあるため、コピーは適用できません。その回路のモニタリングをオフにすることをおすすめします。","monitoringRating.note_guide":"詳しくは、タンデムブレーカーと複数負荷ブレーカーのガイドをご覧ください。","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"{circuit} のコピーした定格を削除","monitoringRating.table_threshold_warning":"この回路のしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。{reset}を選択するとグローバルしきい値を使用します。","monitoringRating.table_threshold_warning_global":"グローバルしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。上の{settings}で変更してください。","monitoringRating.warning_announcement":"{circuit}:{warning}","error.package_ratings_failed":"SPAN アプリからコピーした定格の更新に失敗しました","sidepanel.judged_against":"判定基準: {rating}","sidepanel.shedding_priority":"シェディング優先度","sidepanel.priority_label":"優先度","sidepanel.monitoring":"モニタリング","sidepanel.global":"グローバル","sidepanel.custom":"カスタム","sidepanel.continuous_pct":"継続 %","sidepanel.spike_pct":"スパイク %","sidepanel.window_duration":"ウィンドウ時間","sidepanel.cooldown":"クールダウン","sidepanel.favorite":"お気に入り","sidepanel.save_to_favorites":"お気に入りに保存","panel.favorites":"お気に入り","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","card.device_not_found":"パネルデバイスが見つかりません。カード設定のdevice_idを確認してください。","card.topology_error":"トポロジー応答にpanel_sizeがなく、回路が見つかりません。SPAN Panel統合を更新してください。","card.panel_size_error":"panel_sizeを判定できません。回路がpanel_size属性が見つかりません。SPAN Panel統合を更新してください。","editor.panel_label":"SPAN Panel","editor.select_panel":"パネルを選択...","editor.chart_window":"グラフ時間ウィンドウ","editor.days":"日","editor.hours":"時間","editor.minutes":"分","editor.chart_metric":"グラフ指標","editor.visible_sections":"表示セクション","editor.panel_circuits":"パネル回路","editor.battery_bess":"バッテリー (BESS)","editor.ev_charger_evse":"EV充電器 (EVSE)","editor.solar_pv":"ソーラー (PV)","editor.no_entities":"表示するエンティティがありません","editor.tab_style":"タブスタイル","editor.tab_style_text":"テキスト","editor.tab_style_icon":"アイコン","metric.power":"電力","metric.current":"電流","metric.soc":"充電状態","metric.soe":"エネルギー状態","shedding.always_on":"重要","shedding.never":"切断不可","shedding.soc_threshold":"SoCしきい値","shedding.off_grid":"切断可能","shedding.unknown":"不明","shedding.select.never":"停電時もオンを維持","shedding.select.soc_threshold":"バッテリーしきい値までオン","shedding.select.off_grid":"停電時にオフ"},pt:{"tab.panel":"Painel","tab.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","tab.settings":"Configurações","tab.adopted":"Adotadas","list.search_placeholder":"Pesquisar circuitos...","list.unassigned_area":"Não atribuído","list.no_results":"Nenhum circuito encontrado","monitoring.heading":"Monitoramento","monitoring.global_settings":"Configurações Globais","monitoring.enabled":"Ativado","monitoring.continuous":"Contínuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Janela (min)","monitoring.cooldown":"Resfriamento (min)","monitoring.monitored_points":"Pontos Monitorados","monitoring.col.name":"Nome","monitoring.col.continuous":"Contínuo","monitoring.col.spike":"Pico","monitoring.col.window":"Janela","monitoring.col.cooldown":"Resfriamento","monitoring.rating":"Corrente nominal","monitoring.all_none":"Todos / Nenhum","monitoring.reset":"Redefinir","monitoring.limit_invalid":"Digite um número inteiro de {min} a {max}.","monitoring.enable_invalid":"O monitoramento não foi ativado: corrija os campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Redefinir {name}","monitoring.admin_only":"Somente um administrador pode alterar o monitoramento.","notification.heading":"Configurações de Notificação","notification.targets":"Destinos de Notificação","notification.none_selected":"Nenhum selecionado","notification.targets_button":"Destinos de Notificação: {targets}","notification.no_targets":"Nenhum destino de notificação encontrado","notification.all_targets":"Todos","notification.event_bus_target":"Barramento de Eventos (barramento de eventos do HA)","notification.priority":"Prioridade","notification.priority.default":"Padrão","notification.priority.passive":"Passivo","notification.priority.active":"Ativo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Substitui silencioso/Não perturbar","notification.hint.time_sensitive":"Atravessa o modo Foco","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega padrão","notification.title_template":"Modelo de Título","notification.message_template":"Modelo de Mensagem","notification.placeholders":"Variáveis:","notification.event_bus_help":"O Barramento de Eventos dispara o tipo de evento","notification.event_bus_payload":"com dados:","notification.test_label":"Notificação de teste","notification.test_button":"Enviar teste","notification.test_sending":"Enviando...","notification.test_sent":"Notificação de teste enviada","error.prefix":"Erro:","error.failed_save":"Falha ao salvar","error.failed":"Falhou","error.panel_offline":"SPAN Panel inacessível","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inacessível","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"Não foi possível conectar ao SPAN Panel","error.relay_failed":"Não foi possível alternar o relé","error.shedding_failed":"Não foi possível atualizar a prioridade de desligamento","error.threshold_failed":"Não foi possível salvar o limite","error.graph_horizon_failed":"Não foi possível atualizar o horizonte temporal do gráfico","error.favorites_fetch_failed":"Não foi possível carregar os favoritos","error.favorites_toggle_failed":"Não foi possível atualizar o favorito","error.history_failed":"Não foi possível carregar os dados históricos","error.monitoring_failed":"Não foi possível carregar o status de monitoramento","error.graph_settings_failed":"Não foi possível carregar as configurações do gráfico","error.areas_failed":"As atribuições de áreas podem estar fora de sincronização","error.retry":"Tentar novamente","card.connecting":"Conectando ao SPAN Panel...","monitoringRating.none":"sem corrente nominal","monitoringRating.copied":"{package} do seu app SPAN (o painel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado do seu app SPAN","monitoringRating.judged_copied":"Avaliado com base em {rating} A: {copied}","settings.heading":"Configurações","settings.description":"As configurações gerais da integração (nomes de entidades, prefixo do dispositivo, números de circuito) são gerenciadas através do fluxo de opções da integração.","settings.open_link":"Abrir Configurações de Integração SPAN Panel","adopted.heading":"Entidades adotadas","adopted.description":"As leituras do fornecedor e os dispositivos adotados chegam com metadados mínimos. Faça a curadoria de uma para definir sua classe de dispositivo, classe de estatísticas e proeminência — alterações salvas recarregam a integração e valem a partir da próxima inicialização.","adopted.filter_placeholder":"Filtrar por nome de entidade ou dispositivo","adopted.no_results":"Nenhuma entidade adotada corresponde a este filtro","adopted.none":"Este painel não publica nada para curadoria.","adopted.load_failed":"Não foi possível carregar as entidades adotadas","adopted.count":"{count} adotadas","adopted.vendor_readings":"LEITURAS DO FORNECEDOR","adopted.adopted_device":"DISPOSITIVO ADOTADO","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"O painel não suporta mais o que foi salvo para: {fields}","adopted.enable_entity":"Ativar entidade","adopted.enabled":"ATIVADA","adopted.disabled":"DESATIVADA","adopted.enable_note":"Ativada ao salvar — a curadoria nunca ativa por conta própria","adopted.registry_unavailable":"Ativação e nome ficam disponíveis assim que esta entidade existir no registro.","adopted.name":"Nome","adopted.device_class":"Classe de dispositivo","adopted.device_class_note":"opções limitadas pela unidade do painel ({unit})","adopted.device_class_note_unitless":"opções limitadas pelo que o painel publica","adopted.no_device_class":"Sem classe de dispositivo","adopted.statistics_class":"Classe de estatísticas","adopted.statistics_note":"as estatísticas de longo prazo começam após a próxima recarga","adopted.no_statistics":"Sem estatísticas","adopted.prominence":"Proeminência","adopted.diagnostic":"Diagnóstico","adopted.standard":"Padrão","adopted.display_unit":"Unidade exibida","adopted.unit_as_published":"Como publicada","adopted.precision":"Precisão","adopted.precision_default":"Padrão","adopted.read_only":"somente leitura","adopted.settable":"editável","adopted.save":"Salvar","adopted.clear":"Limpar curadoria","adopted.reload_note":"Salvar recarrega a integração SPAN Panel","adopted.saved":"Salvo — a integração está recarregando","adopted.confirm_heading":"Confirmar classe de estatísticas","adopted.confirm_setting":"Você está definindo {name} como {value}.","adopted.confirm_clearing_subject":"Você está limpando a classe de estatísticas de {name}.","adopted.confirm_total_increasing":"Total crescente trata toda queda do valor como uma reinicialização do medidor. Se esta leitura puder diminuir por qualquer outro motivo, as estatísticas de longo prazo ficarão permanentemente corrompidas — corrigir a classe depois não repara o histórico já gravado.","adopted.confirm_clearing":"As estatísticas de longo prazo deixarão de ser compiladas para esta entidade, e o Home Assistant abrirá um reparo sobre as estatísticas já coletadas na classe que você está removendo.","adopted.save_anyway":"Salvar mesmo assim","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Salvo como total crescente — cada queda da leitura agora conta como uma reinicialização do medidor.","adopted.warn_statistics_removed":"Esta entidade não tem mais classe de estatísticas; o Home Assistant abrirá um reparo sobre as estatísticas já coletadas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configurações de monitoramento do painel","header.graph_settings":"Configurações do horizonte temporal do gráfico","header.site":"Local","header.grid":"Rede","header.upstream":"Montante","header.downstream":"Jusante","header.solar":"Solar","header.battery":"Bateria","header.toggle_units":"Alternar Watts / Amperes","header.enable_switches":"Ativar Interruptores","header.switches_enabled":"Interruptores Ativados","controls.admin_only":"Somente um administrador pode operar os controles deste painel.","controls.disabled":"O controle deste painel está desativado nas suas opções.","controls.read_only":"Sua conta do Home Assistant não pode operar os controles deste painel.","controls.entity_unauthorized":"Sua conta do Home Assistant não pode operar este controle.","controls.not_operable":"Você não pode operar os controles deste painel.","grid.unknown":"Desconhecido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Lig","grid.off":"Des","grid.shared_switch":"Liga e desliga todos os circuitos deste espaço","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Carregador VE","subdevice.battery":"Bateria","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potência","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total do local","subdevice.in_site_total":"Incluído no total do local","sidepanel.graph_settings":"Configurações de Gráficos","sidepanel.global_defaults":"Padrões globais para todos os circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Padrão Global","sidepanel.list_view_columns":"Colunas da Lista","sidepanel.columns":"Colunas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Redefinir para o padrão global","sidepanel.relay":"Relé","sidepanel.breaker":"Disjuntor","sidepanel.capacity":"capacidade de {amps} A","monitoringRating.title":"Correntes nominais dos disjuntores no app SPAN","monitoringRating.panel_rating":"O painel publica {panel} A","monitoringRating.other_breaker":"Outro disjuntor (A)","monitoringRating.other_breaker_label":"Outro disjuntor no espaço de {circuit}","monitoringRating.reset":"Remover as correntes nominais copiadas","monitoringRating.invalid_other":"Digite a corrente nominal do outro disjuntor como um número inteiro de amperes, 1 ou mais.","monitoringRating.guidance":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-20A, digite a segunda aqui. Os painéis SPAN Panel MAIN 32 informam apenas a primeira, e o monitoramento então avalia este espaço pelos dois disjuntores juntos.","monitoringRating.guidance_two_spaces":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-30A, digite a segunda aqui.","monitoringRating.averaged_legs":"Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases deste circuito, o que pode esconder uma fase sobrecarregada. Recomendamos desativar o monitoramento deste circuito.","monitoringRating.turn_off_monitoring":"Desativar o monitoramento","monitoringRating.threshold_warning":"Os limites personalizados deste circuito passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real.","monitoringRating.threshold_warning_global":"Os limites globais que este circuito usa passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real; altere-os em {settings}, na aba {tab}.","monitoringRating.use_global_thresholds":"Usar os limites globais","monitoringRating.note_title":"Disjuntores tandem no SPAN Panel MAIN 32","monitoringRating.note_problem":"Os painéis SPAN Panel MAIN 32 não informam quais disjuntores são tandem, nem a corrente nominal do segundo disjuntor de um tandem. Um tandem coloca dois disjuntores em um espaço, mas o painel o informa como um único circuito com apenas a corrente nominal do primeiro disjuntor, enquanto um único sensor lê os dois disjuntores juntos. Um tandem 20-20 mostra 20 A aqui e pode conduzir 40 A, então o monitoramento gera alertas falsos nele.","monitoringRating.note_steps":"Para corrigir isso, copie as correntes nominais do seu app SPAN:","monitoringRating.note_step_find":"No app SPAN, encontre cada circuito cujo disjuntor mostra duas correntes nominais, como 20-20A.","monitoringRating.note_step_enter":"Na tabela abaixo, digite a segunda corrente nominal no campo {column} desse circuito. Depois pressione Enter ou vá para o próximo campo.","monitoringRating.note_step_single":"Deixe o campo vazio para um circuito com um único disjuntor.","monitoringRating.note_judged":"O monitoramento então avalia esse espaço pelos dois disjuntores juntos: 40 A para um 20-20. Só o monitoramento usa a cópia, e o sensor Breaker Rating do circuito continua mostrando o que o painel informa. Para remover uma corrente nominal copiada, selecione ✕ ao lado do seu campo.","monitoringRating.note_thresholds":"Se você aumentou os limites de um tandem acima de 100% para interromper os alertas dele, selecione {reset} na linha dele. Esses limites agora se aplicam aos dois disjuntores juntos.","monitoringRating.note_two_spaces":"Para um circuito que ocupa dois espaços, digite a segunda corrente nominal da mesma forma se o seu app SPAN mostrar duas, como 20-30A. Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases de um circuito assim, o que pode esconder uma fase sobrecarregada, então a cópia não pode ser aplicada e recomendamos desativar o monitoramento desse circuito.","monitoringRating.note_guide":"Leia mais no guia de disjuntores tandem e de cargas múltiplas.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remover as correntes nominais copiadas de {circuit}","monitoringRating.table_threshold_warning":"Os limites deste circuito passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Selecione {reset} para usar os limites globais.","monitoringRating.table_threshold_warning_global":"Os limites globais passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Altere-os em {settings}, acima.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Não foi possível atualizar as correntes nominais copiadas do app SPAN","sidepanel.judged_against":"Avaliado com base em: {rating}","sidepanel.shedding_priority":"Prioridade de Desligamento","sidepanel.priority_label":"Prioridade","sidepanel.monitoring":"Monitoramento","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Contínuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duração da janela","sidepanel.cooldown":"Resfriamento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Salvar nos favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoramento","status.circuits":"circuitos","status.mains":"alimentação","status.warning":"aviso","status.warnings":"avisos","status.alert":"alerta","status.alerts":"alertas","status.override":"substituição","status.overrides":"substituições","card.no_device":"Abra o editor do cartão e selecione seu dispositivo SPAN Panel.","card.device_not_found":"Dispositivo do painel não encontrado. Verifique device_id na configuração do cartão.","card.topology_error":"A resposta de topologia não contém panel_size e nenhum circuito encontrado. Atualize a integração SPAN Panel.","card.panel_size_error":"Não foi possível determinar panel_size. Nenhum circuito encontrado e nenhum atributo panel_size. Atualize a integração SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Selecione um painel...","editor.chart_window":"Janela de tempo do gráfico","editor.days":"dias","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica do gráfico","editor.visible_sections":"Seções visíveis","editor.panel_circuits":"Circuitos do painel","editor.battery_bess":"Bateria (BESS)","editor.ev_charger_evse":"Carregador VE (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"Nenhuma entidade para mostrar","editor.tab_style":"Estilo das abas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícone","metric.power":"Potência","metric.current":"Corrente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energia","shedding.always_on":"Crítico","shedding.never":"Não desligável","shedding.soc_threshold":"Limite SoC","shedding.off_grid":"Desligável","shedding.unknown":"Desconhecido","shedding.select.never":"Permanece ligado em uma queda","shedding.select.soc_threshold":"Ligado até limite da bateria","shedding.select.off_grid":"Desliga em uma queda"}};function n(n){return e[t]?.[n]??e.en?.[n]??n}function i(n,i){return(e[t]?.[n]??e.en?.[n]??n).replace(/\{(\w+)\}/g,(t,e)=>Object.prototype.hasOwnProperty.call(i,e)?i[e]:`{${e}}`)}const r="power",o="5m",a={"5m":{ms:3e5,refreshMs:1e3,useRealtime:!0},"1h":{ms:36e5,refreshMs:3e4,useRealtime:!1},"1d":{ms:864e5,refreshMs:6e4,useRealtime:!1},"1w":{ms:6048e5,refreshMs:6e4,useRealtime:!1},"1M":{ms:2592e6,refreshMs:6e4,useRealtime:!1}},s="span_panel",l="bess",c="evse",d="pv",u="sub_",h={power:{entityRole:"power",label:()=>n("metric.power"),unit:t=>Math.abs(t)>=1e3?"kW":"W",format:t=>{const e=Math.abs(t);return e>=1e3?(e/1e3).toFixed(1):e<10&&e>0?e.toFixed(1):String(Math.round(e))}},current:{entityRole:"current",label:()=>n("metric.current"),unit:()=>"A",format:t=>Math.abs(t).toFixed(1)}},p={soc:{entityRole:"soc",label:()=>n("metric.soc"),unit:()=>"%",format:t=>String(Math.round(t)),fixedMin:0,fixedMax:100},soe:{entityRole:"soe",label:()=>n("metric.soe"),unit:()=>"kWh",format:t=>t.toFixed(1)},power:h.power},f={always_on:{icon:"mdi:battery",icon2:"mdi:router-wireless",color:"#4caf50",label:()=>n("shedding.always_on")},never:{icon:"mdi:battery",color:"#4caf50",label:()=>n("shedding.never")},soc_threshold:{icon:"mdi:battery-alert-variant-outline",color:"#9c27b0",label:()=>n("shedding.soc_threshold"),textLabel:"SoC"},off_grid:{icon:"mdi:transmission-tower",color:"#ff9800",label:()=>n("shedding.off_grid")},unknown:{icon:"mdi:help-circle-outline",color:"#888",label:()=>n("shedding.unknown")}},g=Object.keys(f).filter(t=>"unknown"!==t&&"always_on"!==t);var m=function(t,e){return m=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},m(t,e)};function v(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}m(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function _(t,e,n,i){var r,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(r=t[s])&&(a=(o<3?r(a):o>3?r(e,n,a):r(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}"function"==typeof SuppressedError&&SuppressedError; +let t="en";const e={en:{"tab.panel":"Panel","tab.by_panel":"By Panel","tab.by_activity":"By Activity","tab.by_area":"By Area","tab.monitoring":"Monitoring","tab.settings":"Settings","tab.adopted":"Adopted","list.search_placeholder":"Search circuits...","list.unassigned_area":"Unassigned","list.no_results":"No circuits found","monitoring.heading":"Monitoring","monitoring.global_settings":"Global Settings","monitoring.enabled":"Enabled","monitoring.continuous":"Continuous (%)","monitoring.spike":"Spike (%)","monitoring.window":"Window (min)","monitoring.cooldown":"Cooldown (min)","monitoring.monitored_points":"Monitored Points","monitoring.col.name":"Name","monitoring.col.continuous":"Continuous","monitoring.col.spike":"Spike","monitoring.col.window":"Window","monitoring.col.cooldown":"Cooldown","monitoring.rating":"Rating","monitoring.all_none":"All / None","monitoring.reset":"Reset","monitoring.limit_invalid":"Enter a whole number from {min} to {max}.","monitoring.enable_invalid":"Monitoring was not turned on: correct the fields marked.","monitoring.point_field":"{field} for {name}","monitoring.reset_point":"Reset {name}","monitoring.admin_only":"Only an administrator can change monitoring.","notification.heading":"Notification Settings","notification.targets":"Notify Targets","notification.none_selected":"None selected","notification.targets_button":"Notify Targets: {targets}","notification.no_targets":"No notify targets found","notification.all_targets":"All","notification.event_bus_target":"Event Bus (HA event bus)","notification.priority":"Priority","notification.priority.default":"Default","notification.priority.passive":"Passive","notification.priority.active":"Active","notification.priority.time_sensitive":"Time-sensitive","notification.priority.critical":"Critical","notification.hint.critical":"Overrides silent/DND","notification.hint.time_sensitive":"Breaks through Focus","notification.hint.passive":"Delivers silently","notification.hint.active":"Standard delivery","notification.title_template":"Title Template","notification.message_template":"Message Template","notification.placeholders":"Placeholders:","notification.event_bus_help":"Event Bus fires event type","notification.event_bus_payload":"with payload:","notification.test_label":"Test Notification","notification.test_button":"Send Test","notification.test_sending":"Sending...","notification.test_sent":"Test notification sent","error.prefix":"Error:","error.failed_save":"Failed to save","error.failed":"Failed","error.panel_offline":"SPAN Panel unreachable","error.panel_reconnected":"SPAN Panel reconnected","error.panel_offline_named":"{name} unreachable","error.panel_reconnected_named":"{name} reconnected","error.discovery_failed":"Unable to connect to SPAN Panel","error.relay_failed":"Unable to toggle relay","error.shedding_failed":"Unable to update shedding priority","error.threshold_failed":"Unable to save threshold","error.graph_horizon_failed":"Unable to update graph time horizon","error.favorites_fetch_failed":"Unable to load favorites","error.favorites_toggle_failed":"Unable to update favorite","error.history_failed":"Unable to load historical data","error.monitoring_failed":"Unable to load monitoring status","error.graph_settings_failed":"Unable to load graph settings","error.areas_failed":"Area assignments may be out of sync","error.retry":"Retry","card.connecting":"Connecting to SPAN Panel...","card.waiting_for_load":"Waiting for SPAN Panel to load...","monitoringRating.none":"no rating","monitoringRating.copied":"{package} from your SPAN app (the panel publishes {panel} A)","monitoringRating.copied_unnamed":"Copied from your SPAN app","monitoringRating.judged_copied":"Judged against {rating} A: {copied}","settings.heading":"Settings","settings.description":"General integration settings (entity naming, device prefix, circuit numbers) are managed through the integration's options flow.","settings.open_link":"Open SPAN Panel Integration Settings","adopted.heading":"Adopted entities","adopted.description":"Vendor readings and adopted devices arrive with minimal metadata. Curate one to set its device class, statistics class, and prominence — saved changes reload the integration and apply from the next startup on.","adopted.filter_placeholder":"Filter by entity or device name","adopted.no_results":"No adopted entities match this filter","adopted.none":"This panel publishes nothing to curate.","adopted.load_failed":"Unable to load adopted entities","adopted.count":"{count} adopted","adopted.vendor_readings":"VENDOR READINGS","adopted.adopted_device":"ADOPTED DEVICE","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURATED","adopted.stale":"STALE","adopted.stale_note":"The panel no longer supports what was saved for: {fields}","adopted.enable_entity":"Enable entity","adopted.enabled":"ENABLED","adopted.disabled":"DISABLED","adopted.enable_note":"Enabled when saved — curating never enables on its own","adopted.registry_unavailable":"Enable and name become available once this entity exists in the registry.","adopted.name":"Name","adopted.device_class":"Device class","adopted.device_class_note":"choices limited by the panel's unit ({unit})","adopted.device_class_note_unitless":"choices limited by what the panel publishes","adopted.no_device_class":"No device class","adopted.statistics_class":"Statistics class","adopted.statistics_note":"long-term statistics begin after the next reload","adopted.no_statistics":"No statistics","adopted.prominence":"Prominence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Display unit","adopted.unit_as_published":"As published","adopted.precision":"Precision","adopted.precision_default":"Default","adopted.read_only":"read-only","adopted.settable":"settable","adopted.save":"Save","adopted.clear":"Clear curation","adopted.reload_note":"Saving reloads the SPAN Panel integration","adopted.saved":"Saved — the integration is reloading","adopted.confirm_heading":"Confirm statistics class","adopted.confirm_setting":"You are setting {name} to {value}.","adopted.confirm_clearing_subject":"You are clearing the statistics class on {name}.","adopted.confirm_total_increasing":"Total increasing treats every drop in the value as a meter reset. If this reading can decrease for any other reason, long-term statistics will be permanently corrupted — fixing the class later does not repair history already written.","adopted.confirm_clearing":"Long-term statistics stop being compiled for this entity, and Home Assistant raises a repair against the statistics already collected under the class you are removing.","adopted.save_anyway":"Save anyway","adopted.cancel":"Cancel","adopted.warn_total_increasing":"Saved as total increasing — every drop in the reading now counts as a meter reset.","adopted.warn_statistics_removed":"This entity has no statistics class any more; Home Assistant will raise a repair against the statistics already collected.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Panel monitoring settings","header.graph_settings":"Graph time horizon settings","header.site":"Site","header.grid":"Grid","header.upstream":"Upstream","header.downstream":"Downstream","header.solar":"Solar","header.battery":"Battery","header.toggle_units":"Toggle Watts / Amps","header.enable_switches":"Enable Switches","header.switches_enabled":"Switches Enabled","controls.admin_only":"Only an administrator can operate this panel's controls.","controls.disabled":"Control of this panel is switched off in its options.","controls.read_only":"Your Home Assistant account can't operate this panel's controls.","controls.entity_unauthorized":"Your Home Assistant account can't operate this control.","controls.not_operable":"You can't operate this panel's controls.","grid.unknown":"Unknown","grid.configure":"Configure circuit","grid.configure_subdevice":"Configure device","grid.on":"On","grid.off":"Off","grid.shared_switch":"Switches every circuit in this space","meters.title":"Meters","meters.importing":"importing","meters.exporting":"exporting","meters.imported":"imported","meters.exported":"exported","subdevice.ev_charger":"EV Charger","subdevice.battery":"Battery","subdevice.fallback":"Sub-device","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Power","subdevice.solar":"Solar","subdevice.solar_inverter":"Solar inverter","subdevice.site_total":"Site total","subdevice.in_site_total":"Included in the site total","sidepanel.graph_settings":"Graph Settings","sidepanel.global_defaults":"Global defaults for all circuits","sidepanel.favorites_subtitle":"Favorites","sidepanel.global_default":"Global Default","sidepanel.list_view_columns":"List View Columns","sidepanel.columns":"Columns","sidepanel.circuit_scales":"Circuit Graph Scales","sidepanel.subdevice_scales":"Sub-Device Graph Scales","sidepanel.reset_to_global":"Reset to global default","sidepanel.relay":"Relay","sidepanel.breaker":"Breaker","sidepanel.capacity":"{amps} A capacity","monitoringRating.title":"Breaker ratings from the SPAN app","monitoringRating.panel_rating":"Panel publishes {panel} A","monitoringRating.other_breaker":"Other breaker (A)","monitoringRating.other_breaker_label":"Other breaker in the space of {circuit}","monitoringRating.reset":"Remove copied ratings","monitoringRating.invalid_other":"Enter the other breaker's rating as a whole number of amps, 1 or more.","monitoringRating.guidance":"If your SPAN app shows two ratings for this circuit, such as 20-20A, enter the second one here. SPAN Panel MAIN 32 panels report only the first, and monitoring then judges this space against both breakers together.","monitoringRating.guidance_two_spaces":"If your SPAN app shows two ratings for this circuit, such as 20-30A, enter the second one here.","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 panels report only the average of this circuit's two legs, which can hide an overloaded leg. We recommend turning monitoring off for this circuit.","monitoringRating.turn_off_monitoring":"Turn off monitoring","monitoringRating.threshold_warning":"This circuit's custom thresholds are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass.","monitoringRating.threshold_warning_global":"The global thresholds this circuit uses are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass; change them under {settings} on the {tab} tab.","monitoringRating.use_global_thresholds":"Use global thresholds","monitoringRating.note_title":"Tandem breakers on SPAN Panel MAIN 32","monitoringRating.note_problem":"SPAN Panel MAIN 32 panels do not report which breakers are tandems, or the rating of a tandem's second breaker. A tandem puts two breakers in one space, but the panel reports it as one circuit with only the first breaker's rating, while one sensor reads both breakers together. A 20-20 tandem shows 20 A here and can carry 40 A, so monitoring raises false alerts on it.","monitoringRating.note_steps":"To fix this, copy the ratings from your SPAN app:","monitoringRating.note_step_find":"In the SPAN app, find each circuit whose breaker shows two ratings, such as 20-20A.","monitoringRating.note_step_enter":"In the table below, type the second rating in that circuit's {column} field. Then press Enter or move to the next field.","monitoringRating.note_step_single":"Leave the field empty for a circuit with a single breaker.","monitoringRating.note_judged":"Monitoring then judges that space against both breakers together: 40 A for a 20-20. Only monitoring uses the copy, and the circuit's Breaker Rating sensor still shows what the panel reports. To remove a copied rating, select ✕ beside its field.","monitoringRating.note_thresholds":"If you raised a tandem's thresholds above 100% to stop its alerts, select {reset} on its row. Those thresholds now apply to both breakers together.","monitoringRating.note_two_spaces":"For a circuit that spans two spaces, enter the second rating the same way if your SPAN app shows two, such as 20-30A. SPAN Panel MAIN 32 panels report only the average of such a circuit's two legs, which can hide an overloaded leg, so the copy can't be applied and we recommend turning monitoring off for that circuit.","monitoringRating.note_guide":"Read more in the guide to tandem and multi-load breakers.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remove copied ratings for {circuit}","monitoringRating.table_threshold_warning":"This circuit's thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Select {reset} to use the global thresholds.","monitoringRating.table_threshold_warning_global":"The global thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Change them under {settings} above.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Unable to update the ratings copied from the SPAN app","sidepanel.judged_against":"Judged against: {rating}","sidepanel.shedding_priority":"Shedding Priority","sidepanel.priority_label":"Priority","sidepanel.monitoring":"Monitoring","sidepanel.global":"Global","sidepanel.custom":"Custom","sidepanel.continuous_pct":"Continuous %","sidepanel.spike_pct":"Spike %","sidepanel.window_duration":"Window duration","sidepanel.cooldown":"Cooldown","sidepanel.favorite":"Favorite","sidepanel.save_to_favorites":"Save to favorites","panel.favorites":"Favorites","status.monitoring":"Monitoring","status.circuits":"circuits","status.mains":"mains","status.warning":"warning","status.warnings":"warnings","status.alert":"alert","status.alerts":"alerts","status.override":"override","status.overrides":"overrides","card.no_device":"Open the card editor and select your SPAN Panel device.","card.device_not_found":"Panel device not found. Check device_id in card config.","card.topology_error":"Topology response missing panel_size and no circuits found. Update the SPAN Panel integration.","editor.panel_label":"SPAN Panel","editor.select_panel":"Select a panel...","editor.chart_window":"Chart time window","editor.days":"days","editor.hours":"hours","editor.minutes":"minutes","editor.chart_metric":"Chart metric","editor.visible_sections":"Visible sections","editor.panel_circuits":"Panel circuits","editor.battery_bess":"Battery (BESS)","editor.ev_charger_evse":"EV Charger (EVSE)","editor.solar_pv":"Solar (PV)","editor.no_entities":"No entities to show","editor.tab_style":"Tab Style","editor.tab_style_text":"Text","editor.tab_style_icon":"Icon","metric.power":"Power","metric.current":"Current","metric.soc":"State of Charge","metric.soe":"State of Energy","shedding.always_on":"Critical","shedding.never":"Non-sheddable","shedding.soc_threshold":"SoC Threshold","shedding.off_grid":"Sheddable","shedding.unknown":"Unknown","shedding.select.never":"Stays on in an outage","shedding.select.soc_threshold":"Stays on until battery threshold","shedding.select.off_grid":"Turns off in an outage"},es:{"tab.panel":"Panel","tab.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","tab.settings":"Configuración","tab.adopted":"Adoptadas","list.search_placeholder":"Buscar circuitos...","list.unassigned_area":"Sin asignar","list.no_results":"No se encontraron circuitos","monitoring.heading":"Monitoreo","monitoring.global_settings":"Configuración Global","monitoring.enabled":"Activado","monitoring.continuous":"Continuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Ventana (min)","monitoring.cooldown":"Enfriamiento (min)","monitoring.monitored_points":"Puntos Monitoreados","monitoring.col.name":"Nombre","monitoring.col.continuous":"Continuo","monitoring.col.spike":"Pico","monitoring.col.window":"Ventana","monitoring.col.cooldown":"Enfriamiento","monitoring.rating":"Calibre","monitoring.all_none":"Todos / Ninguno","monitoring.reset":"Restablecer","monitoring.limit_invalid":"Introduzca un número entero de {min} a {max}.","monitoring.enable_invalid":"No se activó el monitoreo: corrija los campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Restablecer {name}","monitoring.admin_only":"Solo un administrador puede cambiar el monitoreo.","notification.heading":"Configuración de Notificaciones","notification.targets":"Destinos de Notificación","notification.none_selected":"Ninguno seleccionado","notification.targets_button":"Destinos de Notificación: {targets}","notification.no_targets":"No se encontraron destinos de notificación","notification.all_targets":"Todos","notification.event_bus_target":"Bus de Eventos (bus de eventos de HA)","notification.priority":"Prioridad","notification.priority.default":"Predeterminado","notification.priority.passive":"Pasivo","notification.priority.active":"Activo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Anula silencio/No molestar","notification.hint.time_sensitive":"Atraviesa el modo Concentración","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega estándar","notification.title_template":"Plantilla de Título","notification.message_template":"Plantilla de Mensaje","notification.placeholders":"Variables:","notification.event_bus_help":"El Bus de Eventos dispara el tipo de evento","notification.event_bus_payload":"con datos:","notification.test_label":"Notificación de prueba","notification.test_button":"Enviar prueba","notification.test_sending":"Enviando...","notification.test_sent":"Notificación de prueba enviada","error.prefix":"Error:","error.failed_save":"Error al guardar","error.failed":"Falló","error.panel_offline":"SPAN Panel inaccesible","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inaccesible","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"No se puede conectar al SPAN Panel","error.relay_failed":"No se pudo cambiar el relé","error.shedding_failed":"No se pudo actualizar la prioridad de desconexión","error.threshold_failed":"No se pudo guardar el umbral","error.graph_horizon_failed":"No se pudo actualizar el horizonte temporal del gráfico","error.favorites_fetch_failed":"No se pudieron cargar los favoritos","error.favorites_toggle_failed":"No se pudo actualizar el favorito","error.history_failed":"No se pudieron cargar los datos históricos","error.monitoring_failed":"No se pudo cargar el estado de monitoreo","error.graph_settings_failed":"No se pudo cargar la configuración del gráfico","error.areas_failed":"Las asignaciones de áreas pueden estar desincronizadas","error.retry":"Reintentar","card.connecting":"Conectando al SPAN Panel...","card.waiting_for_load":"Esperando a que cargue el SPAN Panel...","monitoringRating.none":"sin calibre","monitoringRating.copied":"{package} de su app de SPAN (el panel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado de su app de SPAN","monitoringRating.judged_copied":"Evaluado según {rating} A: {copied}","settings.heading":"Configuración","settings.description":"La configuración general de la integración (nombres de entidades, prefijo de dispositivo, números de circuito) se administra a través del flujo de opciones de la integración.","settings.open_link":"Abrir Configuración de Integración SPAN Panel","adopted.heading":"Entidades adoptadas","adopted.description":"Las lecturas del proveedor y los dispositivos adoptados llegan con metadatos mínimos. Cura una para definir su clase de dispositivo, clase de estadísticas y prominencia — los cambios guardados recargan la integración y se aplican desde el siguiente arranque.","adopted.filter_placeholder":"Filtrar por nombre de entidad o dispositivo","adopted.no_results":"Ninguna entidad adoptada coincide con este filtro","adopted.none":"Este panel no publica nada que curar.","adopted.load_failed":"No se pudieron cargar las entidades adoptadas","adopted.count":"{count} adoptadas","adopted.vendor_readings":"LECTURAS DEL PROVEEDOR","adopted.adopted_device":"DISPOSITIVO ADOPTADO","adopted.via_panel":"vía SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"El panel ya no admite lo guardado para: {fields}","adopted.enable_entity":"Activar entidad","adopted.enabled":"ACTIVADA","adopted.disabled":"DESACTIVADA","adopted.enable_note":"Se activa al guardar — curar nunca activa por sí solo","adopted.registry_unavailable":"La activación y el nombre estarán disponibles cuando esta entidad exista en el registro.","adopted.name":"Nombre","adopted.device_class":"Clase de dispositivo","adopted.device_class_note":"opciones limitadas por la unidad del panel ({unit})","adopted.device_class_note_unitless":"opciones limitadas por lo que publica el panel","adopted.no_device_class":"Sin clase de dispositivo","adopted.statistics_class":"Clase de estadísticas","adopted.statistics_note":"las estadísticas a largo plazo comienzan tras la próxima recarga","adopted.no_statistics":"Sin estadísticas","adopted.prominence":"Prominencia","adopted.diagnostic":"Diagnóstico","adopted.standard":"Estándar","adopted.display_unit":"Unidad mostrada","adopted.unit_as_published":"Tal como se publica","adopted.precision":"Precisión","adopted.precision_default":"Predeterminada","adopted.read_only":"solo lectura","adopted.settable":"editable","adopted.save":"Guardar","adopted.clear":"Borrar curación","adopted.reload_note":"Guardar recarga la integración SPAN Panel","adopted.saved":"Guardado — la integración se está recargando","adopted.confirm_heading":"Confirmar clase de estadísticas","adopted.confirm_setting":"Vas a definir {name} como {value}.","adopted.confirm_clearing_subject":"Vas a borrar la clase de estadísticas de {name}.","adopted.confirm_total_increasing":"Total creciente interpreta cada caída del valor como un reinicio del contador. Si esta lectura puede disminuir por cualquier otro motivo, las estadísticas a largo plazo quedarán corrompidas de forma permanente — corregir la clase más tarde no repara el historial ya escrito.","adopted.confirm_clearing":"Dejarán de compilarse estadísticas a largo plazo para esta entidad, y Home Assistant abrirá una reparación sobre las estadísticas ya recogidas bajo la clase que estás quitando.","adopted.save_anyway":"Guardar de todos modos","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Guardado como total creciente — cada caída de la lectura cuenta ahora como un reinicio del contador.","adopted.warn_statistics_removed":"Esta entidad ya no tiene clase de estadísticas; Home Assistant abrirá una reparación sobre las estadísticas ya recogidas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configuración de monitoreo del panel","header.graph_settings":"Configuración del horizonte temporal del gráfico","header.site":"Sitio","header.grid":"Red","header.upstream":"Aguas arriba","header.downstream":"Aguas abajo","header.solar":"Solar","header.battery":"Batería","header.toggle_units":"Alternar Watts / Amperios","header.enable_switches":"Habilitar Interruptores","header.switches_enabled":"Interruptores Habilitados","controls.admin_only":"Solo un administrador puede operar los controles de este panel.","controls.disabled":"El control de este panel está desactivado en sus opciones.","controls.read_only":"Su cuenta de Home Assistant no puede operar los controles de este panel.","controls.entity_unauthorized":"Su cuenta de Home Assistant no puede operar este control.","controls.not_operable":"No puede operar los controles de este panel.","grid.unknown":"Desconocido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Enc","grid.off":"Apag","grid.shared_switch":"Conmuta todos los circuitos de este espacio","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Cargador EV","subdevice.battery":"Batería","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potencia","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total del sitio","subdevice.in_site_total":"Incluido en el total del sitio","sidepanel.graph_settings":"Configuración de Gráficos","sidepanel.global_defaults":"Valores predeterminados globales para todos los circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Predeterminado Global","sidepanel.list_view_columns":"Columnas de la lista","sidepanel.columns":"Columnas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Restablecer al valor global","sidepanel.relay":"Relé","sidepanel.breaker":"Interruptor","sidepanel.capacity":"capacidad de {amps} A","monitoringRating.title":"Calibres de interruptor de la app de SPAN","monitoringRating.panel_rating":"El panel publica {panel} A","monitoringRating.other_breaker":"Otro interruptor (A)","monitoringRating.other_breaker_label":"Otro interruptor en el espacio de {circuit}","monitoringRating.reset":"Quitar los calibres copiados","monitoringRating.invalid_other":"Introduzca el calibre del otro interruptor como un número entero de amperios, 1 o más.","monitoringRating.guidance":"Si su app de SPAN muestra dos calibres para este circuito, como 20-20A, introduzca aquí el segundo. Los paneles SPAN Panel MAIN 32 informan solo el primero, y el monitoreo juzga entonces este espacio según ambos interruptores juntos.","monitoringRating.guidance_two_spaces":"Si su app de SPAN muestra dos calibres para este circuito, como 20-30A, introduzca aquí el segundo.","monitoringRating.averaged_legs":"Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de este circuito, lo que puede ocultar una fase sobrecargada. Recomendamos desactivar el monitoreo de este circuito.","monitoringRating.turn_off_monitoring":"Desactivar el monitoreo","monitoringRating.threshold_warning":"Los umbrales personalizados de este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real.","monitoringRating.threshold_warning_global":"Los umbrales globales que usa este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real; cámbielos en {settings}, en la pestaña {tab}.","monitoringRating.use_global_thresholds":"Usar los umbrales globales","monitoringRating.note_title":"Interruptores tándem en SPAN Panel MAIN 32","monitoringRating.note_problem":"Los paneles SPAN Panel MAIN 32 no informan qué interruptores son tándem ni el calibre del segundo interruptor de un tándem. Un tándem pone dos interruptores en un espacio, pero el panel lo informa como un solo circuito con solo el calibre del primer interruptor, mientras un solo sensor lee ambos interruptores juntos. Un tándem 20-20 muestra 20 A aquí y puede llevar 40 A, por lo que el monitoreo genera falsas alertas en él.","monitoringRating.note_steps":"Para corregirlo, copie los calibres de su app de SPAN:","monitoringRating.note_step_find":"En la app de SPAN, busque cada circuito cuyo interruptor muestre dos calibres, como 20-20A.","monitoringRating.note_step_enter":"En la tabla de abajo, escriba el segundo calibre en el campo {column} de ese circuito. Luego pulse Intro o pase al siguiente campo.","monitoringRating.note_step_single":"Deje el campo vacío para un circuito con un solo interruptor.","monitoringRating.note_judged":"El monitoreo juzga entonces ese espacio según ambos interruptores juntos: 40 A para un 20-20. Solo el monitoreo usa la copia, y el sensor Breaker Rating del circuito sigue mostrando lo que informa el panel. Para quitar un calibre copiado, seleccione ✕ junto a su campo.","monitoringRating.note_thresholds":"Si subió los umbrales de un tándem por encima del 100 % para detener sus alertas, seleccione {reset} en su fila. Esos umbrales se aplican ahora a ambos interruptores juntos.","monitoringRating.note_two_spaces":"Para un circuito que ocupa dos espacios, introduzca el segundo calibre del mismo modo si su app de SPAN muestra dos, como 20-30A. Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de un circuito así, lo que puede ocultar una fase sobrecargada, por lo que la copia no se puede aplicar y recomendamos desactivar el monitoreo de ese circuito.","monitoringRating.note_guide":"Lea más en la guía de interruptores tándem y de cargas múltiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Quitar los calibres copiados de {circuit}","monitoringRating.table_threshold_warning":"Los umbrales de este circuito superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Seleccione {reset} para usar los umbrales globales.","monitoringRating.table_threshold_warning_global":"Los umbrales globales superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Cámbielos en {settings}, arriba.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"No se pudieron actualizar los calibres copiados de la app de SPAN","sidepanel.judged_against":"Evaluado según: {rating}","sidepanel.shedding_priority":"Prioridad de Desconexción","sidepanel.priority_label":"Prioridad","sidepanel.monitoring":"Monitoreo","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Continuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duración de ventana","sidepanel.cooldown":"Enfriamiento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Guardar en favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoreo","status.circuits":"circuitos","status.mains":"alimentación","status.warning":"advertencia","status.warnings":"advertencias","status.alert":"alerta","status.alerts":"alertas","status.override":"anulación","status.overrides":"anulaciones","card.no_device":"Abra el editor de tarjeta y seleccione su dispositivo SPAN Panel.","card.device_not_found":"Dispositivo de panel no encontrado. Verifique device_id en la configuración de la tarjeta.","card.topology_error":"La respuesta de topología no contiene panel_size y no se encontraron circuitos. Actualice la integración SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Seleccione un panel...","editor.chart_window":"Ventana de tiempo del gráfico","editor.days":"días","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica del gráfico","editor.visible_sections":"Secciones visibles","editor.panel_circuits":"Circuitos del panel","editor.battery_bess":"Batería (BESS)","editor.ev_charger_evse":"Cargador EV (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"No hay entidades para mostrar","editor.tab_style":"Estilo de pestañas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícono","metric.power":"Potencia","metric.current":"Corriente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energía","shedding.always_on":"Crítico","shedding.never":"No desconectable","shedding.soc_threshold":"Umbral SoC","shedding.off_grid":"Desconectable","shedding.unknown":"Desconocido","shedding.select.never":"Permanece encendido en un corte","shedding.select.soc_threshold":"Encendido hasta umbral de batería","shedding.select.off_grid":"Se apaga en un corte"},fr:{"tab.panel":"Panneau","tab.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","tab.settings":"Paramètres","tab.adopted":"Adoptées","list.search_placeholder":"Rechercher des circuits...","list.unassigned_area":"Non attribué","list.no_results":"Aucun circuit trouvé","monitoring.heading":"Surveillance","monitoring.global_settings":"Paramètres Globaux","monitoring.enabled":"Activé","monitoring.continuous":"Continu (%)","monitoring.spike":"Pic (%)","monitoring.window":"Fenêtre (min)","monitoring.cooldown":"Refroidissement (min)","monitoring.monitored_points":"Points Surveillés","monitoring.col.name":"Nom","monitoring.col.continuous":"Continu","monitoring.col.spike":"Pic","monitoring.col.window":"Fenêtre","monitoring.col.cooldown":"Refroidissement","monitoring.rating":"Calibre","monitoring.all_none":"Tous / Aucun","monitoring.reset":"Réinitialiser","monitoring.limit_invalid":"Saisissez un nombre entier de {min} à {max}.","monitoring.enable_invalid":"La surveillance n'a pas été activée : corrigez les champs signalés.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Réinitialiser {name}","monitoring.admin_only":"Seul un administrateur peut modifier la surveillance.","notification.heading":"Paramètres de Notification","notification.targets":"Cibles de Notification","notification.none_selected":"Aucune sélection","notification.targets_button":"Cibles de Notification : {targets}","notification.no_targets":"Aucune cible de notification trouvée","notification.all_targets":"Tous","notification.event_bus_target":"Bus d'événements (bus d'événements HA)","notification.priority":"Priorité","notification.priority.default":"Par défaut","notification.priority.passive":"Passif","notification.priority.active":"Actif","notification.priority.time_sensitive":"Urgent","notification.priority.critical":"Critique","notification.hint.critical":"Outrepasse silencieux/NPD","notification.hint.time_sensitive":"Traverse le mode Concentration","notification.hint.passive":"Livraison silencieuse","notification.hint.active":"Livraison standard","notification.title_template":"Modèle de Titre","notification.message_template":"Modèle de Message","notification.placeholders":"Variables :","notification.event_bus_help":"Le Bus d'événements déclenche le type d'événement","notification.event_bus_payload":"avec les données :","notification.test_label":"Notification de test","notification.test_button":"Envoyer un test","notification.test_sending":"Envoi...","notification.test_sent":"Notification de test envoyée","error.prefix":"Erreur :","error.failed_save":"Échec de la sauvegarde","error.failed":"Échoué","error.panel_offline":"SPAN Panel inaccessible","error.panel_reconnected":"SPAN Panel reconnecté","error.panel_offline_named":"{name} inaccessible","error.panel_reconnected_named":"{name} reconnecté","error.discovery_failed":"Impossible de se connecter au SPAN Panel","error.relay_failed":"Impossible de basculer le relais","error.shedding_failed":"Impossible de mettre à jour la priorité de délestage","error.threshold_failed":"Impossible d'enregistrer le seuil","error.graph_horizon_failed":"Impossible de mettre à jour l'horizon temporel du graphique","error.favorites_fetch_failed":"Impossible de charger les favoris","error.favorites_toggle_failed":"Impossible de mettre à jour le favori","error.history_failed":"Impossible de charger les données historiques","error.monitoring_failed":"Impossible de charger l'état de surveillance","error.graph_settings_failed":"Impossible de charger les paramètres du graphique","error.areas_failed":"Les affectations de zones peuvent être désynchronisées","error.retry":"Réessayer","card.connecting":"Connexion au SPAN Panel...","card.waiting_for_load":"En attente du chargement du SPAN Panel...","monitoringRating.none":"aucun calibre","monitoringRating.copied":"{package} depuis votre application SPAN (le panneau publie {panel} A)","monitoringRating.copied_unnamed":"Copié depuis votre application SPAN","monitoringRating.judged_copied":"Évalué selon {rating} A : {copied}","settings.heading":"Paramètres","settings.description":"Les paramètres généraux de l'intégration (noms d'entités, préfixe de l'appareil, numéros de circuit) sont gérés via le flux d'options de l'intégration.","settings.open_link":"Ouvrir les Paramètres d'Intégration SPAN Panel","adopted.heading":"Entités adoptées","adopted.description":"Les relevés du fournisseur et les appareils adoptés arrivent avec des métadonnées minimales. Curez-en un pour définir sa classe d'appareil, sa classe de statistiques et sa proéminence — les modifications enregistrées rechargent l'intégration et s'appliquent dès le prochain démarrage.","adopted.filter_placeholder":"Filtrer par nom d'entité ou d'appareil","adopted.no_results":"Aucune entité adoptée ne correspond à ce filtre","adopted.none":"Ce panneau ne publie rien à curer.","adopted.load_failed":"Impossible de charger les entités adoptées","adopted.count":"{count} adoptées","adopted.vendor_readings":"RELEVÉS DU FOURNISSEUR","adopted.adopted_device":"APPAREIL ADOPTÉ","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURÉE","adopted.stale":"OBSOLÈTE","adopted.stale_note":"Le panneau ne prend plus en charge ce qui a été enregistré pour : {fields}","adopted.enable_entity":"Activer l'entité","adopted.enabled":"ACTIVÉE","adopted.disabled":"DÉSACTIVÉE","adopted.enable_note":"Activée à l'enregistrement — la curation n'active jamais d'elle-même","adopted.registry_unavailable":"L'activation et le nom seront disponibles dès que cette entité existera dans le registre.","adopted.name":"Nom","adopted.device_class":"Classe d'appareil","adopted.device_class_note":"choix limités par l'unité du panneau ({unit})","adopted.device_class_note_unitless":"choix limités par ce que le panneau publie","adopted.no_device_class":"Aucune classe d'appareil","adopted.statistics_class":"Classe de statistiques","adopted.statistics_note":"les statistiques à long terme commencent après le prochain rechargement","adopted.no_statistics":"Aucune statistique","adopted.prominence":"Proéminence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Unité affichée","adopted.unit_as_published":"Telle que publiée","adopted.precision":"Précision","adopted.precision_default":"Par défaut","adopted.read_only":"lecture seule","adopted.settable":"modifiable","adopted.save":"Enregistrer","adopted.clear":"Effacer la curation","adopted.reload_note":"L'enregistrement recharge l'intégration SPAN Panel","adopted.saved":"Enregistré — l'intégration se recharge","adopted.confirm_heading":"Confirmer la classe de statistiques","adopted.confirm_setting":"Vous définissez {name} sur {value}.","adopted.confirm_clearing_subject":"Vous effacez la classe de statistiques de {name}.","adopted.confirm_total_increasing":"Total croissant interprète chaque baisse de la valeur comme une remise à zéro du compteur. Si ce relevé peut diminuer pour une autre raison, les statistiques à long terme seront corrompues de façon permanente — corriger la classe plus tard ne répare pas l'historique déjà écrit.","adopted.confirm_clearing":"Les statistiques à long terme cesseront d'être compilées pour cette entité, et Home Assistant ouvrira une réparation sur les statistiques déjà collectées sous la classe que vous retirez.","adopted.save_anyway":"Enregistrer quand même","adopted.cancel":"Annuler","adopted.warn_total_increasing":"Enregistré en total croissant — chaque baisse du relevé compte désormais comme une remise à zéro du compteur.","adopted.warn_statistics_removed":"Cette entité n'a plus de classe de statistiques ; Home Assistant ouvrira une réparation sur les statistiques déjà collectées.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Paramètres de surveillance du panneau","header.graph_settings":"Paramètres d'horizon temporel du graphique","header.site":"Site","header.grid":"Réseau","header.upstream":"Amont","header.downstream":"Aval","header.solar":"Solaire","header.battery":"Batterie","header.toggle_units":"Basculer Watts / Ampères","header.enable_switches":"Activer les interrupteurs","header.switches_enabled":"Interrupteurs activés","controls.admin_only":"Seul un administrateur peut utiliser les commandes de ce panneau.","controls.disabled":"La commande de ce panneau est désactivée dans ses options.","controls.read_only":"Votre compte Home Assistant ne peut pas utiliser les commandes de ce panneau.","controls.entity_unauthorized":"Votre compte Home Assistant ne peut pas utiliser cette commande.","controls.not_operable":"Vous ne pouvez pas utiliser les commandes de ce panneau.","grid.unknown":"Inconnu","grid.configure":"Configurer le circuit","grid.configure_subdevice":"Configurer l'appareil","grid.on":"On","grid.off":"Off","grid.shared_switch":"Commute tous les circuits de cet emplacement","meters.title":"Compteurs","meters.importing":"en import","meters.exporting":"en export","meters.imported":"importés","meters.exported":"exportés","subdevice.ev_charger":"Chargeur VE","subdevice.battery":"Batterie","subdevice.fallback":"Sous-appareil","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Puissance","subdevice.solar":"Solaire","subdevice.solar_inverter":"Onduleur solaire","subdevice.site_total":"Total du site","subdevice.in_site_total":"Inclus dans le total du site","sidepanel.graph_settings":"Paramètres des Graphiques","sidepanel.global_defaults":"Valeurs par défaut globales pour tous les circuits","sidepanel.favorites_subtitle":"Favoris","sidepanel.global_default":"Défaut Global","sidepanel.list_view_columns":"Colonnes de la liste","sidepanel.columns":"Colonnes","sidepanel.circuit_scales":"Échelles des Graphiques de Circuits","sidepanel.subdevice_scales":"Échelles des Graphiques de Sous-Appareils","sidepanel.reset_to_global":"Réinitialiser à la valeur globale","sidepanel.relay":"Relais","sidepanel.breaker":"Disjoncteur","sidepanel.capacity":"capacité de {amps} A","monitoringRating.title":"Calibres des disjoncteurs dans l'application SPAN","monitoringRating.panel_rating":"Le panneau publie {panel} A","monitoringRating.other_breaker":"Autre disjoncteur (A)","monitoringRating.other_breaker_label":"Autre disjoncteur dans l'emplacement de {circuit}","monitoringRating.reset":"Supprimer les calibres copiés","monitoringRating.invalid_other":"Saisissez le calibre de l'autre disjoncteur en nombre entier d'ampères, 1 ou plus.","monitoringRating.guidance":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-20A, saisissez ici le second. Les panneaux SPAN Panel MAIN 32 n'indiquent que le premier, et la surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble.","monitoringRating.guidance_two_spaces":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-30A, saisissez ici le second.","monitoringRating.averaged_legs":"Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases de ce circuit, ce qui peut masquer une phase en surcharge. Nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.turn_off_monitoring":"Désactiver la surveillance","monitoringRating.threshold_warning":"Les seuils personnalisés de ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge.","monitoringRating.threshold_warning_global":"Les seuils globaux qu'utilise ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge ; modifiez-les dans {settings}, onglet {tab}.","monitoringRating.use_global_thresholds":"Utiliser les seuils globaux","monitoringRating.note_title":"Disjoncteurs tandem sur SPAN Panel MAIN 32","monitoringRating.note_problem":"Les panneaux SPAN Panel MAIN 32 n'indiquent pas quels disjoncteurs sont des tandems, ni le calibre du second disjoncteur d'un tandem. Un tandem place deux disjoncteurs dans un emplacement, mais le panneau l'indique comme un seul circuit avec le calibre du premier disjoncteur seulement, tandis qu'un seul capteur lit les deux disjoncteurs ensemble. Un tandem 20-20 affiche 20 A ici et peut supporter 40 A, si bien que la surveillance déclenche de fausses alertes sur lui.","monitoringRating.note_steps":"Pour corriger cela, copiez les calibres depuis votre application SPAN :","monitoringRating.note_step_find":"Dans l'application SPAN, trouvez chaque circuit dont le disjoncteur affiche deux calibres, par exemple 20-20A.","monitoringRating.note_step_enter":"Dans le tableau ci-dessous, saisissez le second calibre dans le champ {column} de ce circuit. Appuyez ensuite sur Entrée ou passez au champ suivant.","monitoringRating.note_step_single":"Laissez le champ vide pour un circuit à disjoncteur unique.","monitoringRating.note_judged":"La surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble : 40 A pour un 20-20. Seule la surveillance utilise la copie, et le capteur Breaker Rating du circuit affiche toujours ce que le panneau indique. Pour supprimer un calibre copié, sélectionnez ✕ à côté de son champ.","monitoringRating.note_thresholds":"Si vous avez relevé les seuils d'un tandem au-dessus de 100 % pour faire cesser ses alertes, sélectionnez {reset} sur sa ligne. Ces seuils s'appliquent désormais aux deux disjoncteurs ensemble.","monitoringRating.note_two_spaces":"Pour un circuit qui occupe deux emplacements, saisissez le second calibre de la même façon si votre application SPAN en affiche deux, par exemple 20-30A. Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases d'un tel circuit, ce qui peut masquer une phase en surcharge : la copie ne peut donc pas être appliquée, et nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.note_guide":"Pour en savoir plus, consultez le guide des disjoncteurs tandem et à charges multiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Supprimer les calibres copiés de {circuit}","monitoringRating.table_threshold_warning":"Les seuils de ce circuit dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Sélectionnez {reset} pour utiliser les seuils globaux.","monitoringRating.table_threshold_warning_global":"Les seuils globaux dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Modifiez-les dans {settings} ci-dessus.","monitoringRating.warning_announcement":"{circuit} : {warning}","error.package_ratings_failed":"Impossible de mettre à jour les calibres copiés depuis l'application SPAN","sidepanel.judged_against":"Évalué selon : {rating}","sidepanel.shedding_priority":"Priorité de Délestage","sidepanel.priority_label":"Priorité","sidepanel.monitoring":"Surveillance","sidepanel.global":"Global","sidepanel.custom":"Personnalisé","sidepanel.continuous_pct":"Continu %","sidepanel.spike_pct":"Pic %","sidepanel.window_duration":"Durée de fenêtre","sidepanel.cooldown":"Refroidissement","sidepanel.favorite":"Favori","sidepanel.save_to_favorites":"Enregistrer dans les favoris","panel.favorites":"Favoris","status.monitoring":"Surveillance","status.circuits":"circuits","status.mains":"alimentation","status.warning":"avertissement","status.warnings":"avertissements","status.alert":"alerte","status.alerts":"alertes","status.override":"remplacement","status.overrides":"remplacements","card.no_device":"Ouvrez l'éditeur de carte et sélectionnez votre appareil SPAN Panel.","card.device_not_found":"Appareil de panneau introuvable. Vérifiez device_id dans la configuration de la carte.","card.topology_error":"La réponse de topologie ne contient pas panel_size et aucun circuit trouvé. Mettez à jour l'intégration SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Sélectionnez un panneau...","editor.chart_window":"Fenêtre de temps du graphique","editor.days":"jours","editor.hours":"heures","editor.minutes":"minutes","editor.chart_metric":"Métrique du graphique","editor.visible_sections":"Sections visibles","editor.panel_circuits":"Circuits du panneau","editor.battery_bess":"Batterie (BESS)","editor.ev_charger_evse":"Chargeur VE (EVSE)","editor.solar_pv":"Solaire (PV)","editor.no_entities":"Aucune entité à afficher","editor.tab_style":"Style des onglets","editor.tab_style_text":"Texte","editor.tab_style_icon":"Icône","metric.power":"Puissance","metric.current":"Courant","metric.soc":"État de Charge","metric.soe":"État d'Énergie","shedding.always_on":"Critique","shedding.never":"Non délestable","shedding.soc_threshold":"Seuil SoC","shedding.off_grid":"Délestable","shedding.unknown":"Inconnu","shedding.select.never":"Reste allumé en cas de coupure","shedding.select.soc_threshold":"Allumé jusqu'au seuil batterie","shedding.select.off_grid":"S'éteint en cas de coupure"},ja:{"tab.panel":"パネル","tab.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","tab.settings":"設定","tab.adopted":"採用済み","list.search_placeholder":"回路を検索...","list.unassigned_area":"未割り当て","list.no_results":"回路が見つかりません","monitoring.heading":"モニタリング","monitoring.global_settings":"グローバル設定","monitoring.enabled":"有効","monitoring.continuous":"継続 (%)","monitoring.spike":"スパイク (%)","monitoring.window":"ウィンドウ (分)","monitoring.cooldown":"クールダウン (分)","monitoring.monitored_points":"監視ポイント","monitoring.col.name":"名前","monitoring.col.continuous":"継続","monitoring.col.spike":"スパイク","monitoring.col.window":"ウィンドウ","monitoring.col.cooldown":"クールダウン","monitoring.rating":"定格","monitoring.all_none":"全選択 / 全解除","monitoring.reset":"リセット","monitoring.limit_invalid":"{min} から {max} までの整数を入力してください。","monitoring.enable_invalid":"モニタリングは有効になっていません。マークされた項目を修正してください。","monitoring.point_field":"{name}の{field}","monitoring.reset_point":"{name}をリセット","monitoring.admin_only":"モニタリングを変更できるのは管理者のみです。","notification.heading":"通知設定","notification.targets":"通知先","notification.none_selected":"未選択","notification.targets_button":"通知先: {targets}","notification.no_targets":"通知先が見つかりません","notification.all_targets":"すべて","notification.event_bus_target":"イベントバス (HAイベントバス)","notification.priority":"優先度","notification.priority.default":"デフォルト","notification.priority.passive":"パッシブ","notification.priority.active":"アクティブ","notification.priority.time_sensitive":"緊急","notification.priority.critical":"重大","notification.hint.critical":"サイレント/おやすみモードを無視","notification.hint.time_sensitive":"集中モードを突破","notification.hint.passive":"サイレント配信","notification.hint.active":"標準配信","notification.title_template":"タイトルテンプレート","notification.message_template":"メッセージテンプレート","notification.placeholders":"プレースホルダー:","notification.event_bus_help":"イベントバスが発行するイベントタイプ","notification.event_bus_payload":"ペイロード:","notification.test_label":"テスト通知","notification.test_button":"テスト送信","notification.test_sending":"送信中...","notification.test_sent":"テスト通知を送信しました","error.prefix":"エラー:","error.failed_save":"保存に失敗","error.failed":"失敗","error.panel_offline":"SPANパネルに接続できません","error.panel_reconnected":"SPANパネルが再接続されました","error.panel_offline_named":"{name}に接続できません","error.panel_reconnected_named":"{name}が再接続されました","error.discovery_failed":"SPANパネルへの接続に失敗しました","error.relay_failed":"リレーの切り替えに失敗しました","error.shedding_failed":"シェディング優先度の更新に失敗しました","error.threshold_failed":"しきい値の保存に失敗しました","error.graph_horizon_failed":"グラフの時間範囲の更新に失敗しました","error.favorites_fetch_failed":"お気に入りの読み込みに失敗しました","error.favorites_toggle_failed":"お気に入りの更新に失敗しました","error.history_failed":"履歴データの読み込みに失敗しました","error.monitoring_failed":"監視ステータスの読み込みに失敗しました","error.graph_settings_failed":"グラフ設定の読み込みに失敗しました","error.areas_failed":"エリア割り当てが同期されていない可能性があります","error.retry":"再試行","card.connecting":"SPANパネルに接続中...","card.waiting_for_load":"SPANパネルの読み込みを待機中...","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","settings.heading":"設定","settings.description":"統合の一般設定(エンティティ名、デバイスプレフィックス、回路番号)は統合のオプションフローで管理されます。","settings.open_link":"SPAN Panel統合設定を開く","adopted.heading":"採用済みエンティティ","adopted.description":"ベンダーの測定値と採用済みデバイスは最小限のメタデータで登録されます。キュレーションでデバイスクラス、統計クラス、表示区分を設定できます。保存すると統合が再読み込みされ、次回の起動から適用されます。","adopted.filter_placeholder":"エンティティ名またはデバイス名で絞り込み","adopted.no_results":"この条件に一致する採用済みエンティティはありません","adopted.none":"このパネルにキュレーション対象はありません。","adopted.load_failed":"採用済みエンティティを読み込めません","adopted.count":"{count} 件","adopted.vendor_readings":"ベンダー測定値","adopted.adopted_device":"採用済みデバイス","adopted.via_panel":"SPAN Panel 経由","adopted.curated":"キュレーション済み","adopted.stale":"無効","adopted.stale_note":"パネルは保存された次の項目をサポートしなくなりました: {fields}","adopted.enable_entity":"エンティティを有効化","adopted.enabled":"有効","adopted.disabled":"無効","adopted.enable_note":"保存時に有効化されます — キュレーション自体が有効化することはありません","adopted.registry_unavailable":"有効化・名前は、このエンティティがレジストリに登録された後に利用できます。","adopted.name":"名前","adopted.device_class":"デバイスクラス","adopted.device_class_note":"パネルの単位({unit})により選択肢が制限されます","adopted.device_class_note_unitless":"パネルが公開する内容により選択肢が制限されます","adopted.no_device_class":"デバイスクラスなし","adopted.statistics_class":"統計クラス","adopted.statistics_note":"長期統計は次回の再読み込み後に開始されます","adopted.no_statistics":"統計なし","adopted.prominence":"表示区分","adopted.diagnostic":"診断","adopted.standard":"標準","adopted.display_unit":"表示単位","adopted.unit_as_published":"公開されたまま","adopted.precision":"小数点以下桁数","adopted.precision_default":"既定","adopted.read_only":"読み取り専用","adopted.settable":"書き込み可","adopted.save":"保存","adopted.clear":"キュレーションを消去","adopted.reload_note":"保存すると SPAN Panel 統合が再読み込みされます","adopted.saved":"保存しました — 統合を再読み込みしています","adopted.confirm_heading":"統計クラスの確認","adopted.confirm_setting":"{name} を {value} に設定しようとしています。","adopted.confirm_clearing_subject":"{name} の統計クラスを消去しようとしています。","adopted.confirm_total_increasing":"積算増加は値の低下をすべてメーターのリセットとして扱います。この測定値が他の理由でも下がる場合、長期統計は恒久的に破損します。後からクラスを直しても、既に書き込まれた履歴は修復されません。","adopted.confirm_clearing":"このエンティティの長期統計は収集されなくなり、削除するクラスの下で既に収集された統計について Home Assistant が修復項目を作成します。","adopted.save_anyway":"それでも保存","adopted.cancel":"キャンセル","adopted.warn_total_increasing":"積算増加として保存しました — 測定値の低下はすべてメーターのリセットとして数えられます。","adopted.warn_statistics_removed":"このエンティティに統計クラスはなくなりました。既に収集された統計について Home Assistant が修復項目を作成します。","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"パネルモニタリング設定","header.graph_settings":"グラフ時間範囲設定","header.site":"サイト","header.grid":"グリッド","header.upstream":"上流","header.downstream":"下流","header.solar":"ソーラー","header.battery":"バッテリー","header.toggle_units":"ワット/アンペア切り替え","header.enable_switches":"スイッチを有効化","header.switches_enabled":"スイッチ有効","controls.admin_only":"このパネルのコントロールを操作できるのは管理者のみです。","controls.disabled":"このパネルのコントロールはオプションで無効になっています。","controls.read_only":"お使いのHome Assistantアカウントでは、このパネルのコントロールを操作できません。","controls.entity_unauthorized":"お使いのHome Assistantアカウントでは、このコントロールを操作できません。","controls.not_operable":"このパネルのコントロールは操作できません。","grid.unknown":"不明","grid.configure":"回路を設定","grid.configure_subdevice":"デバイスを設定","grid.on":"オン","grid.off":"オフ","grid.shared_switch":"このスペースのすべての回路を切り替えます","meters.title":"メーター","meters.importing":"受電中","meters.exporting":"送電中","meters.imported":"受電","meters.exported":"送電","subdevice.ev_charger":"EV充電器","subdevice.battery":"バッテリー","subdevice.fallback":"サブデバイス","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"電力","subdevice.solar":"ソーラー","subdevice.solar_inverter":"ソーラーインバーター","subdevice.site_total":"サイト合計","subdevice.in_site_total":"サイト合計に含まれます","sidepanel.graph_settings":"グラフ設定","sidepanel.global_defaults":"全回路のグローバルデフォルト","sidepanel.favorites_subtitle":"お気に入り","sidepanel.global_default":"グローバルデフォルト","sidepanel.list_view_columns":"リスト表示の列数","sidepanel.columns":"列","sidepanel.circuit_scales":"回路グラフスケール","sidepanel.subdevice_scales":"サブデバイスグラフスケール","sidepanel.reset_to_global":"グローバルにリセット","sidepanel.relay":"リレー","sidepanel.breaker":"ブレーカー","sidepanel.capacity":"容量 {amps} A","monitoringRating.title":"SPAN アプリのブレーカー定格","monitoringRating.panel_rating":"パネルの公開値 {panel} A","monitoringRating.other_breaker":"もう一方のブレーカー (A)","monitoringRating.other_breaker_label":"{circuit} のスペースにあるもう一方のブレーカー","monitoringRating.reset":"コピーした定格を削除","monitoringRating.invalid_other":"もう一方のブレーカーの定格を 1 以上の整数のアンペアで入力してください。","monitoringRating.guidance":"SPAN アプリでこの回路に 20-20A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。SPAN Panel MAIN 32 パネルが報告するのは 1 つ目だけで、モニタリングはこのスペースを両方のブレーカーの合計で判定します。","monitoringRating.guidance_two_spaces":"SPAN アプリでこの回路に 20-30A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 パネルはこの回路の 2 本の線の平均値しか報告しないため、過負荷の線が見えなくなることがあります。この回路のモニタリングをオフにすることをおすすめします。","monitoringRating.turn_off_monitoring":"モニタリングをオフにする","monitoringRating.threshold_warning":"この回路のカスタムしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。","monitoringRating.threshold_warning_global":"この回路が使用するグローバルしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。{tab}タブの{settings}で変更してください。","monitoringRating.use_global_thresholds":"グローバルしきい値を使用","monitoringRating.note_title":"SPAN Panel MAIN 32 のタンデムブレーカー","monitoringRating.note_problem":"SPAN Panel MAIN 32 パネルは、どのブレーカーがタンデムかも、タンデムの 2 つ目のブレーカーの定格も報告しません。タンデムは 1 つのスペースに 2 つのブレーカーを収めますが、パネルはそれを 1 つ目のブレーカーの定格だけを持つ 1 つの回路として報告し、1 つのセンサーが両方のブレーカーの合計を読み取ります。20-20 のタンデムはここでは 20 A と表示されますが 40 A まで流せるため、モニタリングが誤ったアラートを出します。","monitoringRating.note_steps":"これを直すには、次の手順で SPAN アプリから定格をコピーします。","monitoringRating.note_step_find":"SPAN アプリで、ブレーカーに 20-20A のように 2 つの定格が表示されている回路をすべて探します。","monitoringRating.note_step_enter":"下の表で、その回路の{column}フィールドに 2 つ目の定格を入力します。続けて Enter キーを押すか、次のフィールドに移動します。","monitoringRating.note_step_single":"ブレーカーが 1 つだけの回路では、フィールドを空のままにします。","monitoringRating.note_judged":"するとモニタリングは、そのスペースを両方のブレーカーの合計で判定します。20-20 なら 40 A です。コピーを使うのはモニタリングだけで、回路の Breaker Rating センサーは引き続きパネルが報告する値を表示します。コピーした定格を削除するには、フィールドの横の ✕ を選択します。","monitoringRating.note_thresholds":"アラートを止めるためにタンデムのしきい値を 100% より上に上げていた場合は、その行の{reset}を選択してください。それらのしきい値は今後、両方のブレーカーの合計に適用されます。","monitoringRating.note_two_spaces":"2 つのスペースにまたがる回路でも、SPAN アプリに 20-30A のように 2 つの定格が表示されていれば、同じ方法で 2 つ目の定格を入力します。SPAN Panel MAIN 32 パネルはそのような回路の 2 本の線の平均値しか報告せず、過負荷の線が見えなくなることがあるため、コピーは適用できません。その回路のモニタリングをオフにすることをおすすめします。","monitoringRating.note_guide":"詳しくは、タンデムブレーカーと複数負荷ブレーカーのガイドをご覧ください。","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"{circuit} のコピーした定格を削除","monitoringRating.table_threshold_warning":"この回路のしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。{reset}を選択するとグローバルしきい値を使用します。","monitoringRating.table_threshold_warning_global":"グローバルしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。上の{settings}で変更してください。","monitoringRating.warning_announcement":"{circuit}:{warning}","error.package_ratings_failed":"SPAN アプリからコピーした定格の更新に失敗しました","sidepanel.judged_against":"判定基準: {rating}","sidepanel.shedding_priority":"シェディング優先度","sidepanel.priority_label":"優先度","sidepanel.monitoring":"モニタリング","sidepanel.global":"グローバル","sidepanel.custom":"カスタム","sidepanel.continuous_pct":"継続 %","sidepanel.spike_pct":"スパイク %","sidepanel.window_duration":"ウィンドウ時間","sidepanel.cooldown":"クールダウン","sidepanel.favorite":"お気に入り","sidepanel.save_to_favorites":"お気に入りに保存","panel.favorites":"お気に入り","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","card.device_not_found":"パネルデバイスが見つかりません。カード設定のdevice_idを確認してください。","card.topology_error":"トポロジー応答にpanel_sizeがなく、回路が見つかりません。SPAN Panel統合を更新してください。","editor.panel_label":"SPAN Panel","editor.select_panel":"パネルを選択...","editor.chart_window":"グラフ時間ウィンドウ","editor.days":"日","editor.hours":"時間","editor.minutes":"分","editor.chart_metric":"グラフ指標","editor.visible_sections":"表示セクション","editor.panel_circuits":"パネル回路","editor.battery_bess":"バッテリー (BESS)","editor.ev_charger_evse":"EV充電器 (EVSE)","editor.solar_pv":"ソーラー (PV)","editor.no_entities":"表示するエンティティがありません","editor.tab_style":"タブスタイル","editor.tab_style_text":"テキスト","editor.tab_style_icon":"アイコン","metric.power":"電力","metric.current":"電流","metric.soc":"充電状態","metric.soe":"エネルギー状態","shedding.always_on":"重要","shedding.never":"切断不可","shedding.soc_threshold":"SoCしきい値","shedding.off_grid":"切断可能","shedding.unknown":"不明","shedding.select.never":"停電時もオンを維持","shedding.select.soc_threshold":"バッテリーしきい値までオン","shedding.select.off_grid":"停電時にオフ"},pt:{"tab.panel":"Painel","tab.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","tab.settings":"Configurações","tab.adopted":"Adotadas","list.search_placeholder":"Pesquisar circuitos...","list.unassigned_area":"Não atribuído","list.no_results":"Nenhum circuito encontrado","monitoring.heading":"Monitoramento","monitoring.global_settings":"Configurações Globais","monitoring.enabled":"Ativado","monitoring.continuous":"Contínuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Janela (min)","monitoring.cooldown":"Resfriamento (min)","monitoring.monitored_points":"Pontos Monitorados","monitoring.col.name":"Nome","monitoring.col.continuous":"Contínuo","monitoring.col.spike":"Pico","monitoring.col.window":"Janela","monitoring.col.cooldown":"Resfriamento","monitoring.rating":"Corrente nominal","monitoring.all_none":"Todos / Nenhum","monitoring.reset":"Redefinir","monitoring.limit_invalid":"Digite um número inteiro de {min} a {max}.","monitoring.enable_invalid":"O monitoramento não foi ativado: corrija os campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Redefinir {name}","monitoring.admin_only":"Somente um administrador pode alterar o monitoramento.","notification.heading":"Configurações de Notificação","notification.targets":"Destinos de Notificação","notification.none_selected":"Nenhum selecionado","notification.targets_button":"Destinos de Notificação: {targets}","notification.no_targets":"Nenhum destino de notificação encontrado","notification.all_targets":"Todos","notification.event_bus_target":"Barramento de Eventos (barramento de eventos do HA)","notification.priority":"Prioridade","notification.priority.default":"Padrão","notification.priority.passive":"Passivo","notification.priority.active":"Ativo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Substitui silencioso/Não perturbar","notification.hint.time_sensitive":"Atravessa o modo Foco","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega padrão","notification.title_template":"Modelo de Título","notification.message_template":"Modelo de Mensagem","notification.placeholders":"Variáveis:","notification.event_bus_help":"O Barramento de Eventos dispara o tipo de evento","notification.event_bus_payload":"com dados:","notification.test_label":"Notificação de teste","notification.test_button":"Enviar teste","notification.test_sending":"Enviando...","notification.test_sent":"Notificação de teste enviada","error.prefix":"Erro:","error.failed_save":"Falha ao salvar","error.failed":"Falhou","error.panel_offline":"SPAN Panel inacessível","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inacessível","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"Não foi possível conectar ao SPAN Panel","error.relay_failed":"Não foi possível alternar o relé","error.shedding_failed":"Não foi possível atualizar a prioridade de desligamento","error.threshold_failed":"Não foi possível salvar o limite","error.graph_horizon_failed":"Não foi possível atualizar o horizonte temporal do gráfico","error.favorites_fetch_failed":"Não foi possível carregar os favoritos","error.favorites_toggle_failed":"Não foi possível atualizar o favorito","error.history_failed":"Não foi possível carregar os dados históricos","error.monitoring_failed":"Não foi possível carregar o status de monitoramento","error.graph_settings_failed":"Não foi possível carregar as configurações do gráfico","error.areas_failed":"As atribuições de áreas podem estar fora de sincronização","error.retry":"Tentar novamente","card.connecting":"Conectando ao SPAN Panel...","card.waiting_for_load":"Aguardando o carregamento do SPAN Panel...","monitoringRating.none":"sem corrente nominal","monitoringRating.copied":"{package} do seu app SPAN (o painel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado do seu app SPAN","monitoringRating.judged_copied":"Avaliado com base em {rating} A: {copied}","settings.heading":"Configurações","settings.description":"As configurações gerais da integração (nomes de entidades, prefixo do dispositivo, números de circuito) são gerenciadas através do fluxo de opções da integração.","settings.open_link":"Abrir Configurações de Integração SPAN Panel","adopted.heading":"Entidades adotadas","adopted.description":"As leituras do fornecedor e os dispositivos adotados chegam com metadados mínimos. Faça a curadoria de uma para definir sua classe de dispositivo, classe de estatísticas e proeminência — alterações salvas recarregam a integração e valem a partir da próxima inicialização.","adopted.filter_placeholder":"Filtrar por nome de entidade ou dispositivo","adopted.no_results":"Nenhuma entidade adotada corresponde a este filtro","adopted.none":"Este painel não publica nada para curadoria.","adopted.load_failed":"Não foi possível carregar as entidades adotadas","adopted.count":"{count} adotadas","adopted.vendor_readings":"LEITURAS DO FORNECEDOR","adopted.adopted_device":"DISPOSITIVO ADOTADO","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"O painel não suporta mais o que foi salvo para: {fields}","adopted.enable_entity":"Ativar entidade","adopted.enabled":"ATIVADA","adopted.disabled":"DESATIVADA","adopted.enable_note":"Ativada ao salvar — a curadoria nunca ativa por conta própria","adopted.registry_unavailable":"Ativação e nome ficam disponíveis assim que esta entidade existir no registro.","adopted.name":"Nome","adopted.device_class":"Classe de dispositivo","adopted.device_class_note":"opções limitadas pela unidade do painel ({unit})","adopted.device_class_note_unitless":"opções limitadas pelo que o painel publica","adopted.no_device_class":"Sem classe de dispositivo","adopted.statistics_class":"Classe de estatísticas","adopted.statistics_note":"as estatísticas de longo prazo começam após a próxima recarga","adopted.no_statistics":"Sem estatísticas","adopted.prominence":"Proeminência","adopted.diagnostic":"Diagnóstico","adopted.standard":"Padrão","adopted.display_unit":"Unidade exibida","adopted.unit_as_published":"Como publicada","adopted.precision":"Precisão","adopted.precision_default":"Padrão","adopted.read_only":"somente leitura","adopted.settable":"editável","adopted.save":"Salvar","adopted.clear":"Limpar curadoria","adopted.reload_note":"Salvar recarrega a integração SPAN Panel","adopted.saved":"Salvo — a integração está recarregando","adopted.confirm_heading":"Confirmar classe de estatísticas","adopted.confirm_setting":"Você está definindo {name} como {value}.","adopted.confirm_clearing_subject":"Você está limpando a classe de estatísticas de {name}.","adopted.confirm_total_increasing":"Total crescente trata toda queda do valor como uma reinicialização do medidor. Se esta leitura puder diminuir por qualquer outro motivo, as estatísticas de longo prazo ficarão permanentemente corrompidas — corrigir a classe depois não repara o histórico já gravado.","adopted.confirm_clearing":"As estatísticas de longo prazo deixarão de ser compiladas para esta entidade, e o Home Assistant abrirá um reparo sobre as estatísticas já coletadas na classe que você está removendo.","adopted.save_anyway":"Salvar mesmo assim","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Salvo como total crescente — cada queda da leitura agora conta como uma reinicialização do medidor.","adopted.warn_statistics_removed":"Esta entidade não tem mais classe de estatísticas; o Home Assistant abrirá um reparo sobre as estatísticas já coletadas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configurações de monitoramento do painel","header.graph_settings":"Configurações do horizonte temporal do gráfico","header.site":"Local","header.grid":"Rede","header.upstream":"Montante","header.downstream":"Jusante","header.solar":"Solar","header.battery":"Bateria","header.toggle_units":"Alternar Watts / Amperes","header.enable_switches":"Ativar Interruptores","header.switches_enabled":"Interruptores Ativados","controls.admin_only":"Somente um administrador pode operar os controles deste painel.","controls.disabled":"O controle deste painel está desativado nas suas opções.","controls.read_only":"Sua conta do Home Assistant não pode operar os controles deste painel.","controls.entity_unauthorized":"Sua conta do Home Assistant não pode operar este controle.","controls.not_operable":"Você não pode operar os controles deste painel.","grid.unknown":"Desconhecido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Lig","grid.off":"Des","grid.shared_switch":"Liga e desliga todos os circuitos deste espaço","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Carregador VE","subdevice.battery":"Bateria","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potência","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total do local","subdevice.in_site_total":"Incluído no total do local","sidepanel.graph_settings":"Configurações de Gráficos","sidepanel.global_defaults":"Padrões globais para todos os circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Padrão Global","sidepanel.list_view_columns":"Colunas da Lista","sidepanel.columns":"Colunas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Redefinir para o padrão global","sidepanel.relay":"Relé","sidepanel.breaker":"Disjuntor","sidepanel.capacity":"capacidade de {amps} A","monitoringRating.title":"Correntes nominais dos disjuntores no app SPAN","monitoringRating.panel_rating":"O painel publica {panel} A","monitoringRating.other_breaker":"Outro disjuntor (A)","monitoringRating.other_breaker_label":"Outro disjuntor no espaço de {circuit}","monitoringRating.reset":"Remover as correntes nominais copiadas","monitoringRating.invalid_other":"Digite a corrente nominal do outro disjuntor como um número inteiro de amperes, 1 ou mais.","monitoringRating.guidance":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-20A, digite a segunda aqui. Os painéis SPAN Panel MAIN 32 informam apenas a primeira, e o monitoramento então avalia este espaço pelos dois disjuntores juntos.","monitoringRating.guidance_two_spaces":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-30A, digite a segunda aqui.","monitoringRating.averaged_legs":"Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases deste circuito, o que pode esconder uma fase sobrecarregada. Recomendamos desativar o monitoramento deste circuito.","monitoringRating.turn_off_monitoring":"Desativar o monitoramento","monitoringRating.threshold_warning":"Os limites personalizados deste circuito passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real.","monitoringRating.threshold_warning_global":"Os limites globais que este circuito usa passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real; altere-os em {settings}, na aba {tab}.","monitoringRating.use_global_thresholds":"Usar os limites globais","monitoringRating.note_title":"Disjuntores tandem no SPAN Panel MAIN 32","monitoringRating.note_problem":"Os painéis SPAN Panel MAIN 32 não informam quais disjuntores são tandem, nem a corrente nominal do segundo disjuntor de um tandem. Um tandem coloca dois disjuntores em um espaço, mas o painel o informa como um único circuito com apenas a corrente nominal do primeiro disjuntor, enquanto um único sensor lê os dois disjuntores juntos. Um tandem 20-20 mostra 20 A aqui e pode conduzir 40 A, então o monitoramento gera alertas falsos nele.","monitoringRating.note_steps":"Para corrigir isso, copie as correntes nominais do seu app SPAN:","monitoringRating.note_step_find":"No app SPAN, encontre cada circuito cujo disjuntor mostra duas correntes nominais, como 20-20A.","monitoringRating.note_step_enter":"Na tabela abaixo, digite a segunda corrente nominal no campo {column} desse circuito. Depois pressione Enter ou vá para o próximo campo.","monitoringRating.note_step_single":"Deixe o campo vazio para um circuito com um único disjuntor.","monitoringRating.note_judged":"O monitoramento então avalia esse espaço pelos dois disjuntores juntos: 40 A para um 20-20. Só o monitoramento usa a cópia, e o sensor Breaker Rating do circuito continua mostrando o que o painel informa. Para remover uma corrente nominal copiada, selecione ✕ ao lado do seu campo.","monitoringRating.note_thresholds":"Se você aumentou os limites de um tandem acima de 100% para interromper os alertas dele, selecione {reset} na linha dele. Esses limites agora se aplicam aos dois disjuntores juntos.","monitoringRating.note_two_spaces":"Para um circuito que ocupa dois espaços, digite a segunda corrente nominal da mesma forma se o seu app SPAN mostrar duas, como 20-30A. Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases de um circuito assim, o que pode esconder uma fase sobrecarregada, então a cópia não pode ser aplicada e recomendamos desativar o monitoramento desse circuito.","monitoringRating.note_guide":"Leia mais no guia de disjuntores tandem e de cargas múltiplas.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remover as correntes nominais copiadas de {circuit}","monitoringRating.table_threshold_warning":"Os limites deste circuito passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Selecione {reset} para usar os limites globais.","monitoringRating.table_threshold_warning_global":"Os limites globais passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Altere-os em {settings}, acima.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Não foi possível atualizar as correntes nominais copiadas do app SPAN","sidepanel.judged_against":"Avaliado com base em: {rating}","sidepanel.shedding_priority":"Prioridade de Desligamento","sidepanel.priority_label":"Prioridade","sidepanel.monitoring":"Monitoramento","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Contínuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duração da janela","sidepanel.cooldown":"Resfriamento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Salvar nos favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoramento","status.circuits":"circuitos","status.mains":"alimentação","status.warning":"aviso","status.warnings":"avisos","status.alert":"alerta","status.alerts":"alertas","status.override":"substituição","status.overrides":"substituições","card.no_device":"Abra o editor do cartão e selecione seu dispositivo SPAN Panel.","card.device_not_found":"Dispositivo do painel não encontrado. Verifique device_id na configuração do cartão.","card.topology_error":"A resposta de topologia não contém panel_size e nenhum circuito encontrado. Atualize a integração SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Selecione um painel...","editor.chart_window":"Janela de tempo do gráfico","editor.days":"dias","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica do gráfico","editor.visible_sections":"Seções visíveis","editor.panel_circuits":"Circuitos do painel","editor.battery_bess":"Bateria (BESS)","editor.ev_charger_evse":"Carregador VE (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"Nenhuma entidade para mostrar","editor.tab_style":"Estilo das abas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícone","metric.power":"Potência","metric.current":"Corrente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energia","shedding.always_on":"Crítico","shedding.never":"Não desligável","shedding.soc_threshold":"Limite SoC","shedding.off_grid":"Desligável","shedding.unknown":"Desconhecido","shedding.select.never":"Permanece ligado em uma queda","shedding.select.soc_threshold":"Ligado até limite da bateria","shedding.select.off_grid":"Desliga em uma queda"}};function n(n){return e[t]?.[n]??e.en?.[n]??n}function i(n,i){return(e[t]?.[n]??e.en?.[n]??n).replace(/\{(\w+)\}/g,(t,e)=>Object.prototype.hasOwnProperty.call(i,e)?i[e]:`{${e}}`)}const r="power",o="5m",a={"5m":{ms:3e5,refreshMs:1e3,useRealtime:!0},"1h":{ms:36e5,refreshMs:3e4,useRealtime:!1},"1d":{ms:864e5,refreshMs:6e4,useRealtime:!1},"1w":{ms:6048e5,refreshMs:6e4,useRealtime:!1},"1M":{ms:2592e6,refreshMs:6e4,useRealtime:!1}},s="span_panel",l="bess",c="evse",d="pv",u="sub_",h={power:{entityRole:"power",label:()=>n("metric.power"),unit:t=>Math.abs(t)>=1e3?"kW":"W",format:t=>{const e=Math.abs(t);return e>=1e3?(e/1e3).toFixed(1):e<10&&e>0?e.toFixed(1):String(Math.round(e))}},current:{entityRole:"current",label:()=>n("metric.current"),unit:()=>"A",format:t=>Math.abs(t).toFixed(1)}},p={soc:{entityRole:"soc",label:()=>n("metric.soc"),unit:()=>"%",format:t=>String(Math.round(t)),fixedMin:0,fixedMax:100},soe:{entityRole:"soe",label:()=>n("metric.soe"),unit:()=>"kWh",format:t=>t.toFixed(1)},power:h.power},f={always_on:{icon:"mdi:battery",icon2:"mdi:router-wireless",color:"#4caf50",label:()=>n("shedding.always_on")},never:{icon:"mdi:battery",color:"#4caf50",label:()=>n("shedding.never")},soc_threshold:{icon:"mdi:battery-alert-variant-outline",color:"#9c27b0",label:()=>n("shedding.soc_threshold"),textLabel:"SoC"},off_grid:{icon:"mdi:transmission-tower",color:"#ff9800",label:()=>n("shedding.off_grid")},unknown:{icon:"mdi:help-circle-outline",color:"#888",label:()=>n("shedding.unknown")}},g=Object.keys(f).filter(t=>"unknown"!==t&&"always_on"!==t);var m=function(t,e){return m=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},m(t,e)};function v(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}m(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function _(t,e,n,i){var r,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(r=t[s])&&(a=(o<3?r(a):o>3?r(e,n,a):r(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}"function"==typeof SuppressedError&&SuppressedError; /** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ -const y=globalThis,b=y.ShadowRoot&&(void 0===y.ShadyCSS||y.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,x=Symbol(),w=new WeakMap;let S=class{constructor(t,e,n){if(this._$cssResult$=!0,n!==x)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(b&&void 0===t){const n=void 0!==e&&1===e.length;n&&(t=w.get(e)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&w.set(e,t))}return t}toString(){return this.cssText}};const C=t=>new S("string"==typeof t?t:t+"",void 0,x),k=(t,...e)=>{const n=1===t.length?t[0]:e.reduce((e,n,i)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+t[i+1],t[0]);return new S(n,t,x)},M=b?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const n of t.cssRules)e+=n.cssText;return C(e)})(t):t,{is:T,defineProperty:A,getOwnPropertyDescriptor:I,getOwnPropertyNames:P,getOwnPropertySymbols:D,getPrototypeOf:L}=Object,E=globalThis,R=E.trustedTypes,N=R?R.emptyScript:"",z=E.reactiveElementPolyfillSupport,O=(t,e)=>t,$={toAttribute(t,e){switch(e){case Boolean:t=t?N:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let n=t;switch(e){case Boolean:n=null!==t;break;case Number:n=null===t?null:Number(t);break;case Object:case Array:try{n=JSON.parse(t)}catch(t){n=null}}return n}},H=(t,e)=>!T(t,e),F={attribute:!0,type:String,converter:$,reflect:!1,useDefault:!1,hasChanged:H}; +const y=globalThis,b=y.ShadowRoot&&(void 0===y.ShadyCSS||y.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,x=Symbol(),w=new WeakMap;let S=class{constructor(t,e,n){if(this._$cssResult$=!0,n!==x)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(b&&void 0===t){const n=void 0!==e&&1===e.length;n&&(t=w.get(e)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&w.set(e,t))}return t}toString(){return this.cssText}};const C=t=>new S("string"==typeof t?t:t+"",void 0,x),k=(t,...e)=>{const n=1===t.length?t[0]:e.reduce((e,n,i)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+t[i+1],t[0]);return new S(n,t,x)},M=b?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const n of t.cssRules)e+=n.cssText;return C(e)})(t):t,{is:T,defineProperty:A,getOwnPropertyDescriptor:I,getOwnPropertyNames:P,getOwnPropertySymbols:D,getPrototypeOf:L}=Object,E=globalThis,R=E.trustedTypes,N=R?R.emptyScript:"",O=E.reactiveElementPolyfillSupport,z=(t,e)=>t,$={toAttribute(t,e){switch(e){case Boolean:t=t?N:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let n=t;switch(e){case Boolean:n=null!==t;break;case Number:n=null===t?null:Number(t);break;case Object:case Array:try{n=JSON.parse(t)}catch(t){n=null}}return n}},H=(t,e)=>!T(t,e),F={attribute:!0,type:String,converter:$,reflect:!1,useDefault:!1,hasChanged:H}; /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */Symbol.metadata??=Symbol("metadata"),E.litPropertyMetadata??=new WeakMap;let B=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=F){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const n=Symbol(),i=this.getPropertyDescriptor(t,n,e);void 0!==i&&A(this.prototype,t,i)}}static getPropertyDescriptor(t,e,n){const{get:i,set:r}=I(this.prototype,t)??{get(){return this[e]},set(t){this[e]=t}};return{get:i,set(e){const o=i?.call(this);r?.call(this,e),this.requestUpdate(t,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??F}static _$Ei(){if(this.hasOwnProperty(O("elementProperties")))return;const t=L(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(O("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(O("properties"))){const t=this.properties,e=[...P(t),...D(t)];for(const n of e)this.createProperty(n,t[n])}const t=this[Symbol.metadata];if(null!==t){const e=litPropertyMetadata.get(t);if(void 0!==e)for(const[t,n]of e)this.elementProperties.set(t,n)}this._$Eh=new Map;for(const[t,e]of this.elementProperties){const n=this._$Eu(t,e);void 0!==n&&this._$Eh.set(n,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const n=new Set(t.flat(1/0).reverse());for(const t of n)e.unshift(M(t))}else void 0!==t&&e.push(M(t));return e}static _$Eu(t,e){const n=e.attribute;return!1===n?void 0:"string"==typeof n?n:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const n of e.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((t,e)=>{if(b)t.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const n of e){const e=document.createElement("style"),i=y.litNonce;void 0!==i&&e.setAttribute("nonce",i),e.textContent=n.cssText,t.appendChild(e)}})(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,n){this._$AK(t,n)}_$ET(t,e){const n=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,n);if(void 0!==i&&!0===n.reflect){const r=(void 0!==n.converter?.toAttribute?n.converter:$).toAttribute(e,n.type);this._$Em=t,null==r?this.removeAttribute(i):this.setAttribute(i,r),this._$Em=null}}_$AK(t,e){const n=this.constructor,i=n._$Eh.get(t);if(void 0!==i&&this._$Em!==i){const t=n.getPropertyOptions(i),r="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:$;this._$Em=i;const o=r.fromAttribute(e,t.type);this[i]=o??this._$Ej?.get(i)??o,this._$Em=null}}requestUpdate(t,e,n,i=!1,r){if(void 0!==t){const o=this.constructor;if(!1===i&&(r=this[t]),n??=o.getPropertyOptions(t),!((n.hasChanged??H)(r,e)||n.useDefault&&n.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,n))))return;this.C(t,e,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,e,{useDefault:n,reflect:i,wrapped:r},o){n&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??e??this[t]),!0!==r||void 0!==o)||(this._$AL.has(t)||(this.hasUpdated||n||(e=void 0),this._$AL.set(t,e)),!0===i&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,e]of this._$Ep)this[t]=e;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[e,n]of t){const{wrapped:t}=n,i=this[e];!0!==t||this._$AL.has(e)||void 0===i||this.C(e,void 0,n,i)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw t=!1,this._$EM(),e}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}};B.elementStyles=[],B.shadowRootOptions={mode:"open"},B[O("elementProperties")]=new Map,B[O("finalized")]=new Map,z?.({ReactiveElement:B}),(E.reactiveElementVersions??=[]).push("2.1.2"); + */Symbol.metadata??=Symbol("metadata"),E.litPropertyMetadata??=new WeakMap;let B=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=F){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const n=Symbol(),i=this.getPropertyDescriptor(t,n,e);void 0!==i&&A(this.prototype,t,i)}}static getPropertyDescriptor(t,e,n){const{get:i,set:r}=I(this.prototype,t)??{get(){return this[e]},set(t){this[e]=t}};return{get:i,set(e){const o=i?.call(this);r?.call(this,e),this.requestUpdate(t,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??F}static _$Ei(){if(this.hasOwnProperty(z("elementProperties")))return;const t=L(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(z("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(z("properties"))){const t=this.properties,e=[...P(t),...D(t)];for(const n of e)this.createProperty(n,t[n])}const t=this[Symbol.metadata];if(null!==t){const e=litPropertyMetadata.get(t);if(void 0!==e)for(const[t,n]of e)this.elementProperties.set(t,n)}this._$Eh=new Map;for(const[t,e]of this.elementProperties){const n=this._$Eu(t,e);void 0!==n&&this._$Eh.set(n,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const n=new Set(t.flat(1/0).reverse());for(const t of n)e.unshift(M(t))}else void 0!==t&&e.push(M(t));return e}static _$Eu(t,e){const n=e.attribute;return!1===n?void 0:"string"==typeof n?n:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const n of e.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((t,e)=>{if(b)t.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const n of e){const e=document.createElement("style"),i=y.litNonce;void 0!==i&&e.setAttribute("nonce",i),e.textContent=n.cssText,t.appendChild(e)}})(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,n){this._$AK(t,n)}_$ET(t,e){const n=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,n);if(void 0!==i&&!0===n.reflect){const r=(void 0!==n.converter?.toAttribute?n.converter:$).toAttribute(e,n.type);this._$Em=t,null==r?this.removeAttribute(i):this.setAttribute(i,r),this._$Em=null}}_$AK(t,e){const n=this.constructor,i=n._$Eh.get(t);if(void 0!==i&&this._$Em!==i){const t=n.getPropertyOptions(i),r="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:$;this._$Em=i;const o=r.fromAttribute(e,t.type);this[i]=o??this._$Ej?.get(i)??o,this._$Em=null}}requestUpdate(t,e,n,i=!1,r){if(void 0!==t){const o=this.constructor;if(!1===i&&(r=this[t]),n??=o.getPropertyOptions(t),!((n.hasChanged??H)(r,e)||n.useDefault&&n.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,n))))return;this.C(t,e,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,e,{useDefault:n,reflect:i,wrapped:r},o){n&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??e??this[t]),!0!==r||void 0!==o)||(this._$AL.has(t)||(this.hasUpdated||n||(e=void 0),this._$AL.set(t,e)),!0===i&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,e]of this._$Ep)this[t]=e;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[e,n]of t){const{wrapped:t}=n,i=this[e];!0!==t||this._$AL.has(e)||void 0===i||this.C(e,void 0,n,i)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw t=!1,this._$EM(),e}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}};B.elementStyles=[],B.shadowRootOptions={mode:"open"},B[z("elementProperties")]=new Map,B[z("finalized")]=new Map,O?.({ReactiveElement:B}),(E.reactiveElementVersions??=[]).push("2.1.2"); /** * @license * Copyright 2017 Google LLC @@ -46,7 +46,7 @@ const Pt={attribute:!0,type:String,converter:$,reflect:!1,hasChanged:H},Dt=(t=Pt * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */let zt=class extends Nt{constructor(t){if(super(t),this.it=ht,t.type!==Rt)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===ht||null==t)return this._t=void 0,this.it=t;if(t===ut)return t;if("string"!=typeof t)throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const e=[t];return e.raw=e,this._t={_$litType$:this.constructor.resultType,strings:e,values:[]}}};zt.directiveName="unsafeHTML",zt.resultType=1;const Ot=(t=>(...e)=>({_$litDirective$:t,values:e}))(zt);class $t{constructor(){this._persistent=new Map,this._transient=null,this._transientTimer=null,this._subscribers=new Set,this._watchedPanels=new Map}add(t){const e={...t,timestamp:Date.now()};if(e.persistent)this._persistent.set(e.key,e);else{this._clearTransient(),this._transient=e;const t=e.ttl??5e3;this._transientTimer=setTimeout(()=>{this._transient=null,this._transientTimer=null,this._notify()},t)}this._notify()}remove(t){if(this._persistent.has(t))return this._persistent.delete(t),void this._notify();this._transient?.key===t&&(this._clearTransient(),this._notify())}clear(t){void 0===t?(this._persistent.clear(),this._clearTransient(),this._watchedPanels.clear()):!0===t.persistent?this._persistent.clear():!1===t.persistent&&this._clearTransient(),this._notify()}get active(){const t=[...this._persistent.values()];return null!==this._transient&&t.push(this._transient),t}hasPersistent(t){return this._persistent.has(t)}hasAnyPanelOffline(){for(const t of this._persistent.keys())if("panel-offline"===t||t.startsWith("panel-offline:"))return!0;return!1}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}watchPanelStatus(t){this.watchPanelStatuses([{entityId:t,panelName:null}])}watchPanelStatuses(t){const e=this._watchedPanels,n=new Map;for(const i of t){const t=e.get(i.entityId);n.set(i.entityId,{panelName:i.panelName??null,wasOffline:t?.wasOffline??!1})}const i=this._isSingleUnnamed(e),r=this._isSingleUnnamed(n);for(const t of e.keys()){n.has(t)&&i===r||this._persistent.delete(this._offlineKey(t,i))}this._watchedPanels=n,this._notify()}clearPanelStatusWatch(){if(0===this._watchedPanels.size)return;const t=this._isSingleUnnamed(this._watchedPanels);for(const e of this._watchedPanels.keys())this._persistent.delete(this._offlineKey(e,t));this._watchedPanels.clear(),this._notify()}updateHass(t){if(0===this._watchedPanels.size)return;const e=this._isSingleUnnamed(this._watchedPanels);for(const[r,o]of this._watchedPanels){const a=t.states[r]?.state,s="on"===a,l=this._offlineKey(r,e),c=this._reconnectKey(r,e);if(s){const t=o.wasOffline;o.wasOffline=!1,this.remove(l),t&&this.add({key:c,level:"info",message:null===o.panelName?n("error.panel_reconnected"):i("error.panel_reconnected_named",{name:o.panelName}),persistent:!1})}else o.wasOffline=!0,this.hasPersistent(l)||this.add({key:l,level:"error",message:null===o.panelName?n("error.panel_offline"):i("error.panel_offline_named",{name:o.panelName}),persistent:!0})}}dispose(){this._clearTransient(),this._persistent.clear(),this._subscribers.clear(),this._watchedPanels.clear()}_isSingleUnnamed(t){if(1!==t.size)return!1;for(const e of t.values())return null===e.panelName;return!1}_offlineKey(t,e){return e?"panel-offline":`panel-offline:${t}`}_reconnectKey(t,e){return e?"panel-reconnected":`panel-reconnected:${t}`}_clearTransient(){null!==this._transientTimer&&(clearTimeout(this._transientTimer),this._transientTimer=null),this._transient=null}_notify(){for(const t of this._subscribers)try{t()}catch(t){console.warn("SPAN Panel: error-store subscriber threw",t)}}}const Ht={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ft(t){return String(t).replace(/[&<>"']/g,t=>Ht[t]??t)}const Bt="span_panel_list_columns";function Vt(){try{const t=localStorage.getItem(Bt);if(!t)return 1;const e=parseInt(t,10);return 1===e||2===e||3===e?e:1}catch{return 1}}function jt(t){try{localStorage.setItem(Bt,String(t))}catch{}}function qt(t){return(void 0===t.monitoring_rating_a?t.breaker_rating_a:t.monitoring_rating_a)??null}function Wt(t){return null!=t&&!1!==t.monitoring_enabled}function Ut(t,e){return Wt(e)?qt(t):t.breaker_rating_a??null}const Gt=["continuous_threshold_pct","spike_threshold_pct"];function Xt(t,e){return Wt(e)?function(t,e){return"averaged_legs"===t?.package_ratings_state&&Wt(e)}(t,e)?"averaged_legs":function(t,e){return t&&e&&function(t){const e=t.package_ratings_state;return"applies"===e||"pending"===e&&"one_space"===t.package_ratings_form}(t)&&Gt.some(t=>(e[t]??0)>100)?!0===e.has_override?"own":"global":null}(t,e):null}function Yt(t){return{amps:t?qt(t):void 0,panelAmps:t?.breaker_rating_a,userSet:!0===t?.monitoring_rating_user_set,packageRatings:t?.package_ratings_a??null}}function Zt(t){return t.packageRatings?.length&&t.panelAmps?i("monitoringRating.copied",{package:t.packageRatings.join("-"),panel:String(t.panelAmps)}):n("monitoringRating.copied_unnamed")}function Kt(t){if(!t.amps)return"";const e=`${Ft(t.amps)}A`;return t.userSet?`${e}${function(t){const e=Ft(Zt(t));return``}(t)}`:e}function Qt(t){const e=t.nextElementSibling;e instanceof HTMLElement&&e.classList.contains("rating-copied-note")&&(e.hidden=!e.hidden,t.setAttribute("aria-expanded",String(!e.hidden)))}function Jt(t){return t instanceof Error||"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message?t.message:String(t)}const te=new Set(["Unauthorized","UnknownUser"]);function ee(t){if("object"!=typeof t||null===t)return!1;const e="code"in t?t.code:void 0;return"unauthorized"===e||"home_assistant_error"===e&&"message"in t&&te.has(t.message)}const ne="Validation error: ",ie={translation_domain:t=>"translation_domain"in t?t.translation_domain:void 0,translation_key:t=>"translation_key"in t?t.translation_key:void 0,translation_placeholders:t=>"translation_placeholders"in t?t.translation_placeholders:void 0};function re(t,e){return"object"==typeof t&&null!==t?ie[e](t):void 0}async function oe(t,e,n,i){const r=re(e,"translation_key");if(t&&"string"==typeof r&&re(e,"translation_domain")===n){const i=`component.${n}.exceptions.${r}.message`;try{const r=t.loadBackendTranslation?await t.loadBackendTranslation("exceptions",n):t.localize,o=r?.(i,function(t){const e=re(t,"translation_placeholders");if("object"!=typeof e||null===e)return{};const n={};for(const[t,i]of Object.entries(e))"string"!=typeof i&&"number"!=typeof i||(n[t]=i);return n}(e));if(o)return o}catch{}}const o=Jt(e),a=o.startsWith(ne)?o.slice(18):o;return a&&"[object Object]"!==a?a:i}function ae(t){const e=t.getRootNode();return e instanceof Document||e instanceof ShadowRoot?e.activeElement:null}function se(t){return null!==t&&ae(t)===t}function le(t){if(!t)return!1;const e=ae(t);return null!==e&&t.contains(e)}function ce(t){if(!t)return null;const e=ae(t);return e instanceof HTMLElement&&t.contains(e)?e:null}function de(){return null===document.activeElement||document.activeElement===document.body}function ue(t,e){t.addEventListener("blur",()=>{queueMicrotask(()=>{t.isConnected&&e()})})}const he={continuous_threshold_pct:{min:1,max:200},spike_threshold_pct:{min:1,max:200},window_duration_m:{min:1,max:180},cooldown_duration_m:{min:1,max:180}},pe=["continuous_threshold_pct","spike_threshold_pct","window_duration_m","cooldown_duration_m"];function fe(t){return pe.some(e=>e===t)}function ge(t){t.addEventListener("wheel",e=>{se(t)&&e.preventDefault()},{passive:!1})}function me(t,e,n){const{min:r,max:o}=he[e];ge(t);let a=!1;const s=e=>{e?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),n.report(e)},l=()=>{const e=""===t.value.trim()?Number.NaN:Number(t.value);return Number.isSafeInteger(e)&&e>=r&&e<=o?e:(s(i("monitoring.limit_invalid",{min:String(r),max:String(o)})),null)},c=()=>{if(!a)return;const t=l();null!==t&&(a=!1,s(null),n.save(t))};return t.addEventListener("input",()=>{a=!0,s(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&c()}),ue(t,c),{get dirty(){return a},check:l}}function ve(t,e){ge(t);let i=!1,r=null;const o=n=>{n?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),e.report(n)},a=()=>{i=!1,r=null,o(null);const n=e.stored();t.value=null!==n?String(n):""},s=()=>{if(!i)return;const s=t.value.trim();if(""===s&&t.validity?.badInput)return void o(n("monitoringRating.invalid_other"));if(""===s)return void a();const l=Number(s);!Number.isSafeInteger(l)||l<1?o(n("monitoringRating.invalid_other")):(i=!1,o(null),l!==e.stored()&&(r=l,e.save(l)))};return t.addEventListener("input",()=>{i=!0,r=null,o(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&s()}),ue(t,s),{get dirty(){return i},revert:a,answerRefusal:t=>r===t&&(a(),!0)}}function _e(t,e,i){console.warn("SPAN Panel: package ratings update failed",i),oe(t,i,s,n("error.package_ratings_failed")).then(t=>{e?.add({key:"service:package-ratings",level:"error",message:t,persistent:!1})})}function ye(t){return t.members.map((e,n)=>({uuid:t.memberIds[n],circuit:e}))}function be(t){return new Map(t.flatMap(t=>t.memberIds.map(e=>[e,t])))}function xe(t,e){if(!e)return t;const{breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}=e.circuit;return{...t,breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}}function we(t){const e=t.circuits,n=new Map;for(const[t,i]of Object.entries(e)){const e=i.shared_meter_group;e&&n.set(e,[...n.get(e)??[],[t,i]])}const i=[];for(const[r,o]of Object.entries(e)){const e=o.shared_meter_group,a=e?n.get(e):void 0;if(e&&a){if(a[0][0]===r){const[n,r]=a.find(([t])=>t===e)??a[0],o=a.map(([,t])=>t),s=t.shared_meter_groups?.[e];i.push({uuid:n,circuit:{...r,tabs:Se(o),breaker_rating_a:s?s.breaker_rating_a:ke(o),monitoring_rating_a:s?.monitoring_rating_a,monitoring_rating_user_set:!0===s?.monitoring_rating_user_set},members:o,memberIds:a.map(([t])=>t)})}}else i.push({uuid:r,circuit:o,members:[o],memberIds:[r]})}return i}function Se(t){return[...new Set(t.flatMap(t=>t.tabs))].sort((t,e)=>t-e)}function Ce(t){const e=function(t){return t.some(t=>!t.breaker_rating_a)?"":t.map(t=>Math.round(t.breaker_rating_a)).join("·")}(t);return e?1===t.length?`${e}A`:`${e} A`:""}function ke(t){let e=0;for(const n of t){if(!n.breaker_rating_a)return null;e+=n.breaker_rating_a}return e}function Me(t){if(1===t.length){const e=t[0].breaker_rating_a;return e?`${e}A`:""}return Ce(t)}function Te(t){if(!t?.offered)return null;const[e,...n]=t.members;if(!e||n.length>0)return null;const i=e.circuit.package_ratings_form,r=e.circuit.breaker_rating_a;return"one_space"!==i&&"two_spaces"!==i||null==r?null:{kind:i,member:e,panelA:r}}function Ae(t){return t.circuit.package_ratings_a?.[1]??null}class Ie{constructor(t){this._host=t,this._section=null,this._field=null}get element(){return this._section}mount(t){this._field=null;const e=Te(this._host.ratingsView);this._section=e?this._build(e):null,this._section&&t.after(this._section)}sync(t){const e=Te(this._host.ratingsView),n=this._section;if(n&&e&&n.dataset.kind===e.kind&&n.dataset.uuid===e.member.uuid)return void this._patch(n,e);const i=(r=n,ce(r)?.dataset.role??null);var r;this._field=null;const o=e?this._build(e):null;if(n&&o?n.replaceWith(o):n?n.remove():o&&t.after(o),this._section=o,null===i)return;const a=o?.querySelector(`[data-role="${i}"]`)??o?.querySelector('[data-role="rating-input"]');a?a.focus():this._host.focusAfterRatingsEditor()}_build(t){const e=document.createElement("div");e.dataset.role="rating-section",e.dataset.kind=t.kind,e.dataset.uuid=t.member.uuid,e.className="rating-section";const i=document.createElement("div");i.className="section-label",i.textContent=n("monitoringRating.title"),e.appendChild(i);const r=document.createElement("div");r.className="field-label",r.id="rating-guidance",r.dataset.role="rating-guidance",r.textContent=n("one_space"===t.kind?"monitoringRating.guidance":"monitoringRating.guidance_two_spaces"),e.appendChild(r);const o=document.createElement("div");o.className="field-label rating-feedback",o.id="rating-feedback",o.dataset.role="rating-feedback",o.setAttribute("aria-live","polite"),e.appendChild(this._buildRow(t,o)),e.appendChild(o);const a=document.createElement("div");return a.dataset.role="rating-warning-region",a.setAttribute("aria-live","polite"),e.appendChild(a),this._syncWarning(e,t.member),e}_buildRow(t,e){const{member:r}=t,o=document.createElement("div");o.className="field-row rating-row",o.dataset.role="rating-row",o.dataset.uuid=r.uuid;const a=document.createElement("span");a.className="field-label",a.id="rating-panel-rating",a.dataset.role="rating-panel-rating",a.textContent=i("monitoringRating.panel_rating",{panel:String(t.panelA)});const s=document.createElement("span");s.className="field-label",s.textContent=n("monitoringRating.other_breaker");const l=document.createElement("input");l.type="number",l.min="1",l.step="1",l.inputMode="numeric";const c=Ae(r);return l.value=null!==c?String(c):"",l.setAttribute("aria-label",i("monitoringRating.other_breaker_label",{circuit:r.circuit.name})),l.setAttribute("aria-describedby","rating-panel-rating rating-guidance rating-feedback"),l.dataset.role="rating-input",this._field=ve(l,{report:t=>{e.textContent=t??""},stored:()=>this._storedInForce(),save:t=>this._save(t)}),o.append(a,s,l),null!==c&&o.appendChild(this._buildReset(r.uuid)),o}_buildReset(t){const e=document.createElement("button");return e.type="button",e.className="text-btn",e.dataset.role="rating-reset",e.textContent=n("monitoringRating.reset"),e.addEventListener("click",()=>{this._field?.revert(),this._host.clearPackageRatings(t).catch(t=>this._host.reportRatingsFailure(t))}),e}_patch(t,e){const{member:n}=e,r=Ae(n),o=t.querySelector('[data-role="rating-panel-rating"]');o&&(o.textContent=i("monitoringRating.panel_rating",{panel:String(e.panelA)}));const a=t.querySelector('[data-role="rating-input"]');this._field&&!this._field.dirty&&this._field.revert();const s=t.querySelector('[data-role="rating-row"]'),l=t.querySelector('[data-role="rating-reset"]');null===r&&l?(se(l)&&a?.focus(),l.remove()):null!==r&&!l&&s&&s.appendChild(this._buildReset(n.uuid)),this._syncWarning(t,n)}_storedInForce(){const t=Te(this._host.ratingsView);return t?Ae(t.member):null}_save(t){const e=Te(this._host.ratingsView);if(!e)return;const{member:n,panelA:i}=e;this._host.setPackageRatings(n.uuid,[i,t]).catch(e=>{this._host.reportRatingsFailure(e),this._answerRefusal(n.uuid,t)})}_answerRefusal(t,e){const n=this._section,i=n?.querySelector('[data-role="rating-input"]'),r=this._field;n&&i&&r&&n.dataset.uuid===t&&Te(this._host.ratingsView)?.member.uuid===t&&r.answerRefusal(e)&&(de()||le(n))&&i.focus()}_syncWarning(t,e){const n=t.querySelector('[data-role="rating-warning-region"]');if(!n)return;const i=Xt(e.circuit,this._host.ratingsView?.monitoringInfo??null),r=n.firstElementChild instanceof HTMLElement?n.firstElementChild:null;if(r&&r.dataset.kind===i)return;const o=le(r);r?.remove(),i&&n.appendChild("averaged_legs"===i?this._buildAveragedLegsWarning():this._buildThresholdWarning(i)),o&&this._host.focusAfterRatingsEditor()}_buildThresholdWarning(t){const e="own"===t?n("monitoringRating.threshold_warning"):i("monitoringRating.threshold_warning_global",{settings:n("monitoring.global_settings"),tab:n("tab.monitoring")}),r=this._buildWarning("rating-threshold-warning",t,e);return"own"===t&&r.appendChild(this._buildActionButton("rating-threshold-reset",n("monitoringRating.use_global_thresholds"),()=>this._host.useGlobalThresholds())),r}_buildAveragedLegsWarning(){const t=this._buildWarning("rating-averaged-legs-warning","averaged_legs",n("monitoringRating.averaged_legs"));return t.appendChild(this._buildActionButton("rating-turn-off-monitoring",n("monitoringRating.turn_off_monitoring"),()=>this._host.turnOffMonitoring())),t}_buildWarning(t,e,n){const i=document.createElement("div");i.className="field-label rating-warning",i.dataset.role=t,i.dataset.kind=e,i.setAttribute("role","note");const r=document.createElement("span");return r.textContent=n,i.appendChild(r),i}_buildActionButton(t,e,n){const i=document.createElement("button");return i.type="button",i.className="text-btn",i.dataset.role=t,i.textContent=e,i.addEventListener("click",()=>{"true"!==i.getAttribute("aria-disabled")&&(i.setAttribute("aria-disabled","true"),n().then(t=>{t||i.removeAttribute("aria-disabled")}))}),i}}function Pe(t){return new Promise(e=>setTimeout(e,t))}class De{constructor(t){this._store=t}async callWS(t,e,n){const i=n?.retries??3,r=n?.errorId??`ws:${String(e.type??"unknown")}`;return this._withRetry(()=>t.callWS(e),i,r,n?.errorMessage)}async _withRetry(t,e,i,r){if(this._store.hasAnyPanelOffline())try{const e=await t();return this._store.remove(i),e}catch(t){const e=t instanceof Error?t:new Error(Jt(t));throw this._store.add({key:i,level:"error",message:r??n("error.panel_offline"),persistent:!1}),e}let o;for(let n=0;n<=e;n++)try{const e=await t();return this._store.remove(i),e}catch(t){if(o=t instanceof Error?t:new Error(Jt(t)),n{try{const i={};e&&(i.config_entry_id=e);const o={type:"call_service",domain:s,service:"get_monitoring_status",service_data:i,return_response:!0},a=this._retry?await this._retry.callWS(t,o,{errorId:"fetch:monitoring",errorMessage:n("error.monitoring_failed")}):await t.callWS(o),l=Le(a?.response);return r===this._generation&&(this._status=l,this._lastFetch=Date.now()),l}catch(t){return console.warn("SPAN Panel: monitoring status fetch failed",t),r===this._generation&&(this._status=null),this._retry||this._errorStore?.add({key:"fetch:monitoring",level:"warning",message:n("error.monitoring_failed"),persistent:!1}),null}finally{this._inflight?.gen===r&&(this._inflight=null)}})();return this._inflight={gen:r,promise:o},o}invalidate(){this._lastFetch=0,this._generation++}get status(){return this._status}clear(){this._status=null,this._lastFetch=0,this._generation++}}class Re{constructor(){this._caches=new Map,this._errorStore=null}get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t;for(const e of this._caches.values())e.errorStore=t}async fetchOne(t,e){let n=this._caches.get(e);return n||(n=new Ee,n.errorStore=this._errorStore,this._caches.set(e,n)),n.fetch(t,e)}invalidate(){for(const t of this._caches.values())t.invalidate()}clear(){this._caches.clear()}}function Ne(t){return t.entities?.current??t.entities?.power??""}function ze(t,e){return function(t,e){return t?.circuits?t.circuits[e]??null:null}(t,Ne(e))}function Oe(t){const e=new Map;for(const n of Object.values(t?.circuits??{})){const t=Ne(n);t&&n.name&&e.set(t,n.name)}return e}function $e(t){return{continuousPct:t?.continuous_threshold_pct??80,spikePct:t?.spike_threshold_pct??100}}function He(t,e){const{continuousPct:n,spikePct:i}=$e(e);return t>=i?"alert":t>=n?"warning":"normal"}function Fe(t,e){return`utilization-${He(t,e)}`}function Be(t){return!0===t?.user?.is_admin}function Ve(){return n("monitoring.admin_only")}class je extends Error{constructor(){super(Ve()),this.name="MonitoringChangeRefused"}}function qe(t){const e=e=>n=>async function(t,e,n){if(!t||!Be(t))throw new je;try{await t.callWS({type:"call_service",domain:s,service:e,service_data:n})}catch(t){throw ee(t)?new je:t}}(t,e,n);return{setGlobalMonitoring:e("set_global_monitoring"),testNotification:e("test_notification"),setCircuitThreshold:e("set_circuit_threshold"),clearCircuitThreshold:e("clear_circuit_threshold"),setMainsThreshold:e("set_mains_threshold"),clearMainsThreshold:e("clear_mains_threshold"),setCircuitPackageRatings:e("set_circuit_package_ratings"),clearCircuitPackageRatings:e("clear_circuit_package_ratings")}}function We(t,e){return t instanceof je?t.message:e}function Ue(t,e,i){console.warn(`SPAN Panel: ${i} failed`,e),t?.add({key:"service:monitoring",level:"error",message:We(e,n("error.threshold_failed")),persistent:!1})}const Ge=new Set(["number","text"]);function Xe(t){for(let e=t;e;e=e.parentElement)if(""!==e.style.opacity&&Number(e.style.opacity)<1)return!0;return!1}function Ye(t,e){const n=Ve();for(const i of t.querySelectorAll("input, select, textarea, button, span-switch"))void 0!==e&&i.matches(e)||(i instanceof HTMLInputElement&&Ge.has(i.type)||i instanceof HTMLTextAreaElement?i.readOnly=!0:i.setAttribute("disabled",""),i.title=n,"span-switch"!==i.localName&&(Xe(i)||(i.style.opacity="0.5"),i.style.cursor="not-allowed"))}function Ze(){const t=document.createElement("p");return t.dataset.role="monitoring-read-only",t.setAttribute("role","note"),t.style.cssText="margin:8px 0 12px;font-size:0.85em;color:var(--secondary-text-color);",t.textContent=Ve(),t}const Ke=["relay_state","relay_state_target","priority","priority_target"];function Qe(t){return"_favoriteRefs"in t}const Je=Object.freeze({mayOperate:!0,reason:null}),tn=Object.freeze({mayOperate:!1,reason:null}),en=["control_disabled","admin_only","read_only"];function nn(t){const e=t?.control_access;return"object"==typeof e&&null!==e&&"may_operate"in e&&"boolean"==typeof e.may_operate?e.may_operate?Je:{mayOperate:!1,reason:"reason"in e&&(n=e.reason,en.some(t=>t===n))?e.reason:null}:Je;var n}function rn(t){return"circuit"===t?.kind}function on(t,e){if(!t||!Qe(t))return nn(t);const n=t._favoriteRefs[e];return rn(n)?n.controlAccess:tn}function an(t){if(!t||!Qe(t))return nn(t);const e=[...cn(t,sn).values()],[n]=e;return!n||e.some(t=>t.mayOperate)?Je:n}function sn(t){return!!t?.entities?.switch&&!1!==t.is_user_controllable}function ln(t){return sn(t)||!!t?.entities?.select}function cn(t,e){const n=new Map;for(const[i,r]of Object.entries(t._favoriteRefs))rn(r)&&e(t.circuits[i])&&n.set(r.panelDeviceId,r.controlAccess);return n}const dn={control_disabled:()=>n("controls.disabled"),admin_only:()=>n("controls.admin_only"),read_only:()=>n("controls.read_only")};function un(t){return t.mayOperate?"":t.reason?dn[t.reason]():n("controls.not_operable")}class hn extends Error{constructor(t){super(t),this.name="ControlChangeRefused"}}function pn(t,e){return{setRelay:(n,i)=>fn(t,e,"switch",i?"turn_on":"turn_off",n,{}),setPriority:(n,i)=>fn(t,e,"select","select_option",n,{option:i})}}async function fn(t,e,i,r,o,a){if(!e.mayOperate)throw new hn(un(e));try{await t.callWS({type:"call_service",domain:i,service:r,service_data:a,target:{entity_id:o}})}catch(t){throw ee(t)?new hn(n("controls.entity_unauthorized")):t}}const gn={relay:{key:"service:relay",fallback:()=>n("error.relay_failed")},priority:{key:"service:shedding",fallback:()=>n("error.shedding_failed")}};function mn(t,e,n,i){console.warn(`SPAN Panel: ${i} change failed`,n);const{key:r,fallback:o}=gn[i];oe(t,n,s,o()).then(t=>{e?.add({key:r,level:"error",message:t,persistent:!1})})}function vn(t,e){const n=un(e);n?t.title=n:t.removeAttribute("title")}function _n(t){const e=un(t);return e?`

${Ft(e)}

`:""}const yn="favorites-changed";async function bn(t,e,n={}){const i=await t.callWS({type:"call_service",domain:s,service:e,service_data:n,return_response:!0});return i?.response??null}class xn{get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this._retry=t?new De(t):null}constructor(){this._errorStore=null,this._retry=null,this._map=null,this._lastFetch=0,this._inflight=null,this._generation=0}async fetch(t){const e=Date.now();if(this._inflight&&this._inflight.gen===this._generation)return this._inflight.promise;if(this._map&&e-this._lastFetch<3e4)return this._map;const i=this._generation,r=(async()=>{try{const e={type:"call_service",domain:s,service:"get_favorites",service_data:{},return_response:!0},r=this._retry?await this._retry.callWS(t,e,{errorId:"fetch:favorites",errorMessage:n("error.favorites_fetch_failed")}):await t.callWS(e),o=r?.response?.favorites??{};return i===this._generation&&(this._map=o,this._lastFetch=Date.now()),o}catch(t){return console.warn("SPAN Panel: favorites fetch failed",t),this._retry||this._errorStore?.add({key:"fetch:favorites",level:"warning",message:n("error.favorites_fetch_failed"),persistent:!1}),this._map??{}}finally{this._inflight?.gen===i&&(this._inflight=null)}})();return this._inflight={gen:i,promise:r},r}invalidate(){this._lastFetch=0,this._generation++}clear(){this._map=null,this._lastFetch=0,this._generation++}get map(){return this._map??{}}}function wn(t){return Object.keys(t).some(e=>Sn(t,e))}function Sn(t,e){const n=t[e];return(n?.circuits?.length??0)>0||(n?.sub_devices?.length??0)>0}const Cn={names:["power","battery power"],suffixes:["_power"]},kn={names:["battery level","battery percentage"],suffixes:["_battery_level","_battery_percentage"]},Mn={names:["state of energy"],suffixes:["_soe_kwh"]};function Tn(t,e){if(!t.entities)return null;for(const[n,i]of Object.entries(t.entities)){if("sensor"!==i.domain)continue;const t=(i.original_name??"").toLowerCase();if(e.names.some(e=>t===e))return n;if(i.unique_id&&e.suffixes.some(t=>i.unique_id.endsWith(t)))return n}return null}function An(t){return Tn(t,kn)}function In(t){return Tn(t,Mn)}function Pn(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}function Dn(t){const e=t.solar;return e?"inverter"===e.role?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:null}:e.power_entity_id?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:e.site_power_entity_id}:{headlineEid:e.site_power_entity_id,headlineIsSiteTotal:null!==e.site_power_entity_id,siteTotalEid:null}:{headlineEid:(n=t,Tn(n,Cn)),headlineIsSiteTotal:!1,siteTotalEid:null};var n}function Ln(t){const{headlineEid:e,siteTotalEid:n}=Dn(t),i=[e,n];return t.type===l&&i.push(An(t),In(t)),new Set(i.filter(t=>null!==t))}function En(t){const e=[{role:"power",entityId:Dn(t).headlineEid}];return t.type===l&&e.push({role:"soc",entityId:An(t)},{role:"soe",entityId:In(t)}),e.filter(t=>null!==t.entityId)}function Rn(t,e){return Pn(t.states[e])}function Nn(t){if(!t)return null;let e=null;for(const[n,i]of Object.entries(t)){if("sensor"===i.domain)return n;e||(e=n)}return e}function zn(t,e){return En(t).length>0||e&&null!==Nn(t.entities)}function On(t){return"number"==typeof t&&Number.isInteger(t)&&t>0}function $n(t){return!0===t.outside_panel}function Hn(t,e){if(!t)return null;let n=null,i=null;const{first_position:r,last_position:o}=t;On(r)&&On(o)&&r<=o?(n=r,i=o):On(e)&&(n=1,i=e);for(const e of Object.values(t.circuits))if(e&&!$n(e))for(const t of e.tabs??[])On(t)&&(n=null===n?t:Math.min(n,t),i=null===i?t:Math.max(i,t));return null===n||null===i?null:{first:n,last:i}}function Fn(t){return Math.ceil(t/2)}function Bn(t){return t%2==0?1:0}function Vn(t){if(2!==t.length)return null;const[e,n]=[Math.min(...t),Math.max(...t)];return Fn(e)===Fn(n)?"row-span":Bn(e)===Bn(n)?"col-span":"row-span"}function jn(t,e,n,i){const r=[];return n||r.push("circuit-off"),i&&r.push("circuit-producer"),function(t){return!!t&&null!=t.over_threshold_since}(e)&&r.push("circuit-alert"),r.join(" ")}function qn(t,e){return $n(t)||ti(t,e)}function Wn(t,e){const n=t.entities?.power;return Pn(n?e.states[n]:void 0)}function Un(t,e){const n=t.entities?.current;return Pn(n?e.states[n]:void 0)}function Gn(t){return t.is_generation??"pv"===t.device_type}function Xn(t,e){return Gn(t)||null!==e&&e<0}function Yn(t,e,n){const i=Un(t,e);if(t.entities?.current&&null===i)return null;const r=n?.utilization_pct??null,o=Ut(t,n);return null===r&&null!==i&&o?Math.round(Math.abs(i)/o*1e3)/10:r}const Zn=new Set(g),Kn={NEVER:"never",SOC_THRESHOLD:"soc_threshold",OFF_GRID:"off_grid"};function Qn(t,e){const n=t.entities?.switch;return n?e.states[n]?.state:void 0}function Jn(t,e,n){const i=t.entities?.power,r=i?e.states[i]?.attributes?.[n]:void 0;return"string"==typeof r&&r?r:void 0}function ti(t,e){const n=Qn(t,e);return"on"===n||"off"===n?"on"===n:"CLOSED"===(Jn(t,e,"relay_state")??t.relay_state)}function ei(t,e){if(!t.entities?.switch||!1===t.is_user_controllable)return"none";const n=Qn(t,e);return void 0===n?"none":"on"===n||"off"===n?"operable":"inert"}function ni(t){return void 0===t?void 0:Kn[t]}function ii(t,e){const n=t.entities?.select;return n?e.states[n]?.state:void 0}function ri(t,e){if(t.always_on)return"always_on";if(!t.entities?.select)return"unknown";const n=ii(t,e);return void 0!==n&&Zn.has(n)?n:ni(Jn(t,e,"shed_priority"))??ni(t.priority)??"unknown"}const oi={continuous:"continuous_threshold_pct",spike:"spike_threshold_pct","window-m":"window_duration_m","cooldown-m":"cooldown_duration_m"},ai="relay-label",si="priority-label",li="controls-note";class ci{constructor(t,e){this.uuid=t,this._on=e,this._sent=0,this._from=0,this._pending=0}get on(){return this._on}get settled(){return 0===this._pending}answered(t){this._on=t}async send(t,e){const n=++this._sent;this._pending+=1;try{const i=await e();return i&&n>this._from&&(this._on=t,this._from=n),i}finally{this._pending-=1}}}class di extends HTMLElement{constructor(){super(),this.errorStore=null,this._thresholdReads=0,this._limitFields=[],this._storedMonitoring=null,this._controlAccess=tn,this.attachShadow({mode:"open"}),this._hass=null,this._config=null,this._debounceTimers={},this._ratingsEditor=new Ie(this)}set hass(t){const e=Be(this._hass)!==Be(t);this._hass=t,this.hasAttribute("open")&&this._config&&(e&&this._showsMonitoring()?this._render():this._updateLiveState())}_showsMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!0!==t.showMonitoring)}get hass(){return this._hass}open(t){this._config=t,this._storedMonitoring=t.panelMode||t.subDeviceMode||t.favoritesMode?null:new ci(t.uuid,Wt(t.monitoringInfo)),this._controlAccess=t.panelMode||t.subDeviceMode||t.favoritesMode?tn:t.controlAccess,this._render(),this.offsetHeight,this.setAttribute("open",""),this.setAttribute("data-mode",this._modeFor(t))}get openCircuit(){const t=this._config;return!t||!this.hasAttribute("open")||t.panelMode||t.subDeviceMode||t.favoritesMode?null:{uuid:t.uuid,configEntryId:t.configEntryId??null}}refreshRating(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i={...e,members:t.members,capacityA:t.capacityA,monitoringInfo:t.monitoringInfo,monitoringGlobals:t.monitoringGlobals};this._config=i,this._monitoringStoredAs(e.uuid,t.monitoringInfo);const r=n.querySelector(".subtitle");r&&(r.textContent=this._circuitSubtitle(i)),this._syncMonitoring()}close(){this.removeAttribute("open"),this.removeAttribute("data-mode"),this._config=null,this._storedMonitoring=null,this._controlAccess=tn,this.dispatchEvent(new CustomEvent("side-panel-closed",{bubbles:!0,composed:!0}))}_modeFor(t){return t.favoritesMode?"favorites":t.panelMode?"panel":t.subDeviceMode?"subDevice":"circuit"}_render(){const t=this._config;if(!t)return;const e=this.shadowRoot;if(!e)return;e.innerHTML="";const n=document.createElement("style");n.textContent='\n :host {\n display: block;\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n width: 360px;\n max-width: 90vw;\n z-index: 1000;\n transform: translateX(100%);\n transition: transform 0.3s ease;\n pointer-events: none;\n }\n :host([open]) {\n transform: translateX(0);\n pointer-events: auto;\n }\n\n .backdrop {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.3);\n z-index: -1;\n }\n :host([open]) .backdrop {\n display: block;\n }\n\n .panel {\n height: 100%;\n background: var(--card-background-color, #fff);\n border-left: 1px solid var(--divider-color, #e0e0e0);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n\n .panel-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px;\n border-bottom: 1px solid var(--divider-color, #e0e0e0);\n }\n .panel-header .title {\n font-size: 18px;\n font-weight: 500;\n color: var(--primary-text-color, #212121);\n margin: 0;\n }\n .panel-header .subtitle {\n font-size: 13px;\n color: var(--secondary-text-color, #727272);\n margin: 2px 0 0 0;\n }\n .close-btn {\n background: none;\n border: none;\n cursor: pointer;\n color: var(--secondary-text-color, #727272);\n padding: 4px;\n line-height: 1;\n font-size: 20px;\n }\n\n .panel-body {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n }\n\n .section {\n margin-bottom: 20px;\n }\n .section-label {\n font-size: 12px;\n font-weight: 600;\n text-transform: uppercase;\n color: var(--secondary-text-color, #727272);\n margin: 0 0 8px 0;\n letter-spacing: 0.5px;\n }\n\n .field-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 8px 0;\n }\n /* Why the section\'s relay or priority cannot be operated, under it. */\n .controls-note {\n margin: 4px 0 0;\n font-size: 0.85em;\n color: var(--secondary-text-color, #727272);\n }\n .field-label {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n }\n\n select {\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n }\n\n input[type="number"] {\n width: 72px;\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n text-align: right;\n }\n input[type="number"]:disabled {\n opacity: 0.5;\n }\n\n .radio-group {\n display: flex;\n gap: 16px;\n padding: 8px 0;\n }\n .radio-group label {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n cursor: pointer;\n }\n\n .horizon-bar {\n display: flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n margin-top: 4px;\n }\n .horizon-segment {\n flex: 1;\n padding: 6px 0;\n text-align: center;\n font-size: 13px;\n cursor: pointer;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n transition: background 0.15s ease, color 0.15s ease;\n user-select: none;\n line-height: 1.4;\n }\n .horizon-segment:last-child {\n border-right: none;\n }\n .horizon-segment:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .horizon-segment.active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n .horizon-segment.referenced {\n box-shadow: inset 0 -3px 0 var(--primary-color, #03a9f4);\n }\n\n .unit-toggle {\n display: inline-flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n }\n .unit-btn {\n padding: 4px 10px;\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease;\n }\n .unit-btn:last-child {\n border-right: none;\n }\n .unit-btn:hover:not(.unit-active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .unit-btn.unit-active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n\n .monitoring-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n\n .fav-heart {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--secondary-text-color, #727272);\n border-radius: 4px;\n padding: 2px 6px;\n cursor: pointer;\n font-size: 0.9em;\n margin-right: 6px;\n line-height: 1;\n display: inline-flex;\n align-items: center;\n }\n .fav-heart.active {\n color: var(--primary-color, #03a9f4);\n border-color: var(--primary-color, #03a9f4);\n }\n .fav-heart:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .fav-heart span-icon {\n --mdc-icon-size: 16px;\n }\n\n .rating-section {\n margin-bottom: 8px;\n }\n .limit-row {\n flex-wrap: wrap;\n }\n .limit-feedback {\n flex-basis: 100%;\n }\n .rating-row {\n flex-wrap: wrap;\n justify-content: flex-start;\n gap: 6px 8px;\n }\n .rating-row [data-role="rating-panel-rating"] {\n flex-basis: 100%;\n }\n .rating-feedback {\n font-size: 13px;\n color: var(--error-color, #db4437);\n }\n .rating-warning {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 6px 8px;\n margin-top: 6px;\n padding: 8px;\n border-left: 3px solid var(--warning-color, #ffa600);\n border-radius: 4px;\n background: color-mix(in srgb, var(--warning-color, #ffa600) 12%, transparent);\n font-size: 13px;\n }\n\n .text-btn {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--primary-text-color, #212121);\n border-radius: 4px;\n padding: 4px 8px;\n font: inherit;\n font-size: 13px;\n line-height: 1.3;\n cursor: pointer;\n }\n .text-btn:hover:not(:disabled):not([aria-disabled="true"]) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .text-btn:focus-visible {\n outline: 2px solid var(--primary-color, #03a9f4);\n outline-offset: 1px;\n }\n .text-btn:disabled,\n .text-btn[aria-disabled="true"] {\n opacity: 0.5;\n cursor: default;\n }\n\n .panel-mode-info {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n line-height: 1.6;\n }\n .panel-mode-info p {\n margin: 0 0 12px 0;\n }\n\n',e.appendChild(n);const i=document.createElement("div");i.className="backdrop",i.addEventListener("click",()=>this.close()),e.appendChild(i);const r=document.createElement("div");r.className="panel",e.appendChild(r),t.favoritesMode?this._renderFavoritesMode(r):t.panelMode?this._renderPanelMode(r):t.subDeviceMode?this._renderSubDeviceMode(r,t):this._renderCircuitMode(r,t)}_renderPanelMode(t){const e=this._config,i=this._createHeader(n("sidepanel.graph_settings"),n("sidepanel.global_defaults"));t.appendChild(i);const r=document.createElement("div");r.className="panel-body";const s=e.graphSettings,l=e.topology,c=s?.global_horizon??o,d=s?.circuits??{};r.appendChild(this._buildListColumnsSection());const u=document.createElement("div");u.className="section";const h=document.createElement("div");h.className="section-label",h.textContent=n("sidepanel.graph_horizon"),u.appendChild(h);const p=document.createElement("div");p.className="field-row";const f=document.createElement("span");f.className="field-label",f.textContent=n("sidepanel.global_default"),p.appendChild(f);const g=document.createElement("select");for(const t of Object.keys(a)){const e=document.createElement("option");e.value=t;const i=`horizon.${t}`,r=n(i);e.textContent=r!==i?r:t,t===c&&(e.selected=!0),g.appendChild(e)}if(g.addEventListener("change",()=>{const t={horizon:g.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_graph_time_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})}),p.appendChild(g),u.appendChild(p),r.appendChild(u),l?.circuits){const t=document.createElement("div");t.className="section";const i=document.createElement("div");i.className="section-label",i.textContent=n("sidepanel.circuit_scales"),t.appendChild(i);const o=Object.entries(l.circuits).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[n,i]of o){const r=this._buildPanelModeCircuitRow(n,i,d[n],c,e.configEntryId??null,e.showFavorites??!1,e.favoritePanelDeviceId,e.favoriteCircuitUuids);t.appendChild(r)}r.appendChild(t)}const m=s?.sub_devices??{};if(l?.sub_devices){const t=document.createElement("div");t.className="section";const i=document.createElement("div");i.className="section-label",i.textContent=n("sidepanel.subdevice_scales"),t.appendChild(i);const o=Object.entries(l.sub_devices).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[i,r]of o){const o=En(r).length>0,s=e.showFavorites&&e.favoritePanelDeviceId?this._buildSubDeviceFavoriteHeart(r.entities,e.favoriteSubDeviceIds?.has(i)??!1):null;if(!o&&!s)continue;const l=document.createElement("div");l.className="field-row";const d=document.createElement("span");if(d.className="field-label",d.textContent=r.name||i,d.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",l.appendChild(d),s&&l.appendChild(s),!o){t.appendChild(l);continue}const u=m[i]||{horizon:c,has_override:!1},h=u.has_override?u.horizon:c,p=document.createElement("select");p.dataset.subdevId=i;for(const t of Object.keys(a)){const e=document.createElement("option");e.value=t;const i=`horizon.${t}`,r=n(i);e.textContent=r!==i?r:t,t===h&&(e.selected=!0),p.appendChild(e)}if(p.addEventListener("change",()=>{this._debounce(`subdev-${e.configEntryId??""}-${i}`,500,()=>{const t={subdevice_id:i,horizon:p.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_subdevice_graph_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})})}),l.appendChild(p),u.has_override){const t=document.createElement("button");t.textContent="↺",t.title=n("sidepanel.reset_to_global"),Object.assign(t.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),t.addEventListener("click",()=>{const r={subdevice_id:i};e.configEntryId&&(r.config_entry_id=e.configEntryId),this._callDomainService("clear_subdevice_graph_horizon",r).then(()=>{p.value=c,t.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})}),l.appendChild(t)}t.appendChild(l)}t.children.length>1&&r.appendChild(t)}t.appendChild(r)}_buildPanelModeCircuitRow(t,e,i,r,o,s,l,c){const d=document.createElement("div");d.className="field-row";const u=document.createElement("span");if(u.className="field-label",u.textContent=e.name||t,u.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",d.appendChild(u),s&&l){const n=this._buildFavoriteHeart(e.entities,c?.has(t)??!1);n&&d.appendChild(n)}const h=i||{horizon:r,has_override:!1},p=h.has_override?h.horizon:r,f=document.createElement("select");f.dataset.uuid=t;for(const t of Object.keys(a)){const e=document.createElement("option");e.value=t;const i=`horizon.${t}`,r=n(i);e.textContent=r!==i?r:t,t===p&&(e.selected=!0),f.appendChild(e)}if(f.addEventListener("change",()=>{this._debounce(`circuit-${o??""}-${t}`,500,()=>{const e={circuit_id:t,horizon:f.value};o&&(e.config_entry_id=o),this._callDomainService("set_circuit_graph_horizon",e).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})})}),d.appendChild(f),h.has_override){const e=document.createElement("button");e.textContent="↺",e.title=n("sidepanel.reset_to_global"),Object.assign(e.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),e.addEventListener("click",()=>{const i={circuit_id:t};o&&(i.config_entry_id=o),this._callDomainService("clear_circuit_graph_horizon",i).then(()=>{f.value=r,e.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})}),d.appendChild(e)}return d}_renderFavoritesMode(t){const e=this._config,i=this._createHeader(n("sidepanel.graph_settings"),n("sidepanel.favorites_subtitle"));t.appendChild(i);const r=document.createElement("div");r.className="panel-body",r.appendChild(this._buildListColumnsSection());for(const t of e.perPanelSections)r.appendChild(this._buildFavoritesPanelSection(t));t.appendChild(r)}_buildFavoritesPanelSection(t){const e=document.createElement("div");e.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=t.panelName,e.appendChild(n);const i=t.graphSettings?.global_horizon??o,r=t.graphSettings?.circuits??{},a=function(t){const e=t.circuits??{};return Object.entries(e).map(([t,e])=>({uuid:t,circuit:e})).sort((t,e)=>(t.circuit.name||"").localeCompare(e.circuit.name||""))}(t.topology);for(const{uuid:n,circuit:o}of a){const a=this._buildPanelModeCircuitRow(n,o,r[n],i,t.configEntryId,!0,t.panelDeviceId,t.favoriteCircuitUuids);e.appendChild(a)}return e}_renderCircuitMode(t,e){const n=this._createHeader(e.name,this._circuitSubtitle(e));t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),this._renderRelaySection(i,e),e.showFavorites&&this._renderFavoriteSection(i,e),this._renderSheddingSection(i,e),this._placeControlNote(i),this._renderGraphHorizonSection(i,e),e.showMonitoring&&this._renderMonitoringSection(i,e)}_placeControlNote(t){t.querySelector('[data-role="controls-note"]')?.remove();const e=[...t.querySelectorAll('[data-role="relay-toggle"], [data-role="shedding-select"]')];e[0]?.closest(".section")?.insertAdjacentHTML("beforeend",_n(this._controlAccess));const n=t.querySelector('[data-role="controls-note"]');n&&(n.id=li);for(const t of e)n?t.setAttribute("aria-describedby",li):t.removeAttribute("aria-describedby")}refreshControlAccess(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i=this._controlAccess;i.mayOperate===t.mayOperate&&i.reason===t.reason||(this._controlAccess=t,this._updateLiveState(),this._placeControlNote(n))}_circuitSubtitle(t){const e=t.members.map(t=>t.circuit),n=[...new Set(e.flatMap(t=>t.voltage?[t.voltage]:[]))].sort((t,e)=>t-e);return[Me(e),e.length>1&&t.capacityA?i("sidepanel.capacity",{amps:String(t.capacityA)}):"",n.length>0?`${n.join("/")}V`:"",`Tabs [${Se(e).join(",")}]`].filter(Boolean).join(" · ")}_favoriteEntityId(t){return t?.current??t?.power??null}_buildSubDeviceFavoriteHeart(t,e){const n=Nn(t);return n?this._buildHeartButton(n,e):null}_buildListColumnsSection(){const t=document.createElement("div");t.className="section";const e=document.createElement("div");e.className="section-label",e.textContent=n("sidepanel.list_view_columns"),t.appendChild(e);const i=document.createElement("div");i.className="field-row";const r=document.createElement("span");r.className="field-label",r.textContent=n("sidepanel.columns"),i.appendChild(r);const o=Vt(),a=document.createElement("div");a.className="unit-toggle";for(const t of[1,2,3]){const e=document.createElement("button");e.type="button",e.className="unit-btn"+(t===o?" unit-active":""),e.dataset.columns=String(t),e.textContent=String(t),e.addEventListener("click",()=>{jt(t);for(const t of a.querySelectorAll(".unit-btn"))t.classList.toggle("unit-active",t===e);this.dispatchEvent(new CustomEvent("list-columns-changed",{detail:t,bubbles:!0,composed:!0}))}),a.appendChild(e)}return i.appendChild(a),t.appendChild(i),t}_buildFavoriteHeart(t,e){const n=this._favoriteEntityId(t);return n?this._buildHeartButton(n,e):(console.warn("SPAN Panel: circuit has no current/power sensor; favorite heart suppressed"),null)}_buildHeartButton(t,e){const i=document.createElement("button");i.type="button",i.className=e?"fav-heart active":"fav-heart",i.dataset.role="fav-heart",i.title=n("sidepanel.save_to_favorites"),i.setAttribute("role","switch"),i.setAttribute("aria-checked",String(e)),i.setAttribute("aria-label",n("sidepanel.save_to_favorites"));const r=document.createElement("span-icon");return r.setAttribute("icon",e?"mdi:heart":"mdi:heart-outline"),i.appendChild(r),i.addEventListener("click",e=>{e.stopPropagation(),this._toggleFavoriteEntity(i,r,t).catch(()=>{})}),i}async _toggleFavoriteEntity(t,e,i){if(!this._hass)return;const r=t.classList.contains("active"),o=!r;t.classList.toggle("active",o),e.setAttribute("icon",o?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(o));try{o?await async function(t,e){const n=await bn(t,"add_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(yn)),n?.favorites??{}}(this._hass,i):await async function(t,e){const n=await bn(t,"remove_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(yn)),n?.favorites??{}}(this._hass,i)}catch(i){throw t.classList.toggle("active",r),e.setAttribute("icon",r?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(r)),console.warn("SPAN Panel: favorite toggle failed",i),this.errorStore?.add({key:"service:favorites",level:"error",message:n("error.favorites_toggle_failed"),persistent:!1}),i}}_renderFavoriteSection(t,e){const n=this._favoriteEntityId(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_appendFavoriteHeartSection(t,e,i){const r=document.createElement("div");r.className="section",r.innerHTML=``;const o=document.createElement("div");o.className="field-row";const a=document.createElement("span");a.className="field-label",a.textContent=n("sidepanel.save_to_favorites"),o.appendChild(a),o.appendChild(this._buildHeartButton(e,i)),r.appendChild(o),t.appendChild(r)}_renderSubDeviceMode(t,e){const n=this._createHeader(e.name,e.deviceType);t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),e.showFavorites&&this._renderSubDeviceFavoriteSection(i,e),e.hasChart&&this._renderSubDeviceHorizonSection(i,e)}_renderSubDeviceFavoriteSection(t,e){const n=Nn(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_renderSubDeviceHorizonSection(t,e){const i=document.createElement("div");i.className="section";const r=document.createElement("div");r.className="section-label",r.textContent=n("sidepanel.graph_horizon"),i.appendChild(r);const s=e.graphHorizonInfo,l=!0===s?.has_override,c=s?.horizon||o,d=s?.globalHorizon||o,u=document.createElement("div");u.className="horizon-bar";const h=[{key:"global",label:n("sidepanel.global")}];for(const t of Object.keys(a))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of u.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===d)}};for(const{key:t,label:i}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=i,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===d),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const i={subdevice_id:e.subDeviceId};e.configEntryId&&(i.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_subdevice_graph_horizon",i).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_subdevice_graph_horizon",{...i,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})}))}),u.appendChild(r)}i.appendChild(u),t.appendChild(i)}_createHeader(t,e){const n=document.createElement("div");n.className="panel-header";const i=document.createElement("div"),r=document.createElement("div");if(r.className="title",r.textContent=t,i.appendChild(r),e){const t=document.createElement("div");t.className="subtitle",t.textContent=e,i.appendChild(t)}const o=document.createElement("button");return o.className="close-btn",o.innerHTML="✕",o.addEventListener("click",()=>this.close()),n.appendChild(i),n.appendChild(o),n}_renderRelaySection(t,e){if(!this._hass||"none"===ei(e,this._hass))return;const i=document.createElement("div");i.className="section",i.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=ai,o.textContent=n("sidepanel.breaker");const a=document.createElement("span-switch");a.dataset.role="relay-toggle",a.setAttribute("aria-labelledby",ai);const s=e.entities.switch;this._applyRelayToggle(a,e),a.addEventListener("change",()=>{const t=this._hass;t&&s&&"operable"===ei(e,t)&&pn(t,this._controlAccess).setRelay(s,a.checked).catch(n=>{mn(t,this.errorStore,n,"relay"),this._applyRelayToggle(a,e)})}),r.appendChild(o),r.appendChild(a),i.appendChild(r),t.appendChild(i)}_renderSheddingSection(t,e){if(!e.entities?.select)return;const i=document.createElement("div");i.className="section",i.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=si,o.textContent=n("sidepanel.priority_label");const a=document.createElement("select");a.dataset.role="shedding-select",a.setAttribute("aria-labelledby",si);const s=e.entities.select;for(const t of g){const e=f[t];if(!e)continue;const i=document.createElement("option");i.value=t,i.textContent=n(`shedding.select.${t}`)||e.label(),a.appendChild(i)}a.addEventListener("change",()=>{const t=this._hass;t&&pn(t,this._controlAccess).setPriority(s,a.value).catch(n=>{mn(t,this.errorStore,n,"priority"),this._applySheddingSelect(a,e)})}),r.appendChild(o),r.appendChild(a),i.appendChild(r),t.appendChild(i),this._applySheddingSelect(a,e)}get ratingsView(){const t=this._config;return!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!t.showMonitoring?null:{members:t.members??[],monitoringInfo:t.monitoringInfo,offered:!0===t.monitoringRatingOffered}}setPackageRatings(t,e){return qe(this._hass).setCircuitPackageRatings(this._ratingsPayload(t,{package_ratings_a:[...e]}))}clearPackageRatings(t){return qe(this._hass).clearCircuitPackageRatings(this._ratingsPayload(t,{}))}reportRatingsFailure(t){_e(this._hass,this.errorStore,t)}async useGlobalThresholds(){const t=this._config,e=this.shadowRoot;if(!t||!e||t.panelMode||t.subDeviceMode||t.favoritesMode)return!1;const n=e.querySelector('input[name="monitoring-mode"][value="global"]'),i=e.querySelector('input[name="monitoring-mode"][value="custom"]'),r=e.querySelector('[data-role="threshold-fields"]');n&&(n.checked=!0),r&&(r.style.display="none"),this._thresholdReads+=1;const o={circuit_id:t.entities?.power||t.uuid};t.configEntryId&&(o.config_entry_id=t.configEntryId);try{await qe(this._hass).clearCircuitThreshold(o)}catch(e){return Ue(this.errorStore,e,"monitoring update"),this._config===t&&(i&&(i.checked=!0),r&&(r.style.display="block")),!1}const a=this._config===t?t.monitoringGlobals??null:null;return this._monitoringChanged(t.uuid,{has_override:!1,continuous_threshold_pct:a?.continuous_threshold_pct,spike_threshold_pct:a?.spike_threshold_pct}),!0}async turnOffMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode)&&this._sendMonitoringEnabled(t,!1)}focusAfterRatingsEditor(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"]:checked')??t?.querySelector('input[name="monitoring-mode"]');e?.focus()}_ratingsPayload(t,e){const n={circuit_id:t,...e},i=this._config,r=!i||i.panelMode||i.subDeviceMode||i.favoritesMode?null:i.configEntryId;return r&&(n.config_entry_id=r),n}_monitoringChanged(t,e){const n=this._openCircuitConfig(t);n&&(this._config={...n,monitoringInfo:{...n.monitoringInfo??{},...e}},this._syncMonitoring())}_monitoringAnswered(t,e,n){const i=this._openCircuitConfig(t);i&&(this._config={...i,monitoringInfo:e,monitoringGlobals:n},this._monitoringStoredAs(t,e),!0!==e.has_override&&this._showGlobalChoice(),this._syncMonitoring())}_monitoringStoredAs(t,e){const n=this._storedMonitoring;e&&n?.uuid===t&&n.answered(Wt(e))}_showStoredMonitoring(t){if(!t||t!==this._storedMonitoring||!t.settled)return;const e=this.shadowRoot?.querySelector('[data-role="monitoring-toggle"]')?.hasAttribute("checked");e!==t.on&&this._showMonitoringEnabled(t.uuid,t.on)}_showGlobalChoice(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"][value="global"]'),n=t?.querySelector('[data-role="threshold-fields"]');e&&n&&!e.checked&&!this._limitFields.some(t=>t.dirty)&&(e.checked=!0,le(n)&&e.focus(),n.style.display="none")}_openCircuitConfig(t){const e=this._config;return!e||e.panelMode||e.subDeviceMode||e.favoritesMode||e.uuid!==t||!this.hasAttribute("open")?null:e}_syncMonitoring(){const t=this._config,e=this.shadowRoot?.querySelector('[data-role="judged-against"]');if(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!e)return;const n=this._judgedAgainstText(t.monitoringInfo);e.textContent!==n&&(e.textContent=n),this._ratingsEditor.sync(e),this._lockMonitoringIfReadOnly()}_renderGraphHorizonSection(t,e){const i=document.createElement("div");i.className="section",i.dataset.role="horizon-section";const r=document.createElement("div");r.className="section-label",r.textContent=n("sidepanel.graph_horizon"),i.appendChild(r);const s=e.graphHorizonInfo,l=!0===s?.has_override,c=s?.horizon||o,d=s?.globalHorizon||o,u=document.createElement("div");u.className="horizon-bar";const h=[{key:"global",label:n("sidepanel.global")}];for(const t of Object.keys(a))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of u.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===d)}};for(const{key:t,label:i}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=i,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===d),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const i={circuit_id:e.uuid};e.configEntryId&&(i.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_circuit_graph_horizon",i).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_circuit_graph_horizon",{...i,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})}))}),u.appendChild(r)}i.appendChild(u),t.appendChild(i)}_judgedAgainstText(t){return function(t){return t.amps?t.userSet?i("monitoringRating.judged_copied",{rating:String(t.amps),copied:Zt(t)}):i("sidepanel.judged_against",{rating:`${t.amps} A`}):i("sidepanel.judged_against",{rating:n("monitoringRating.none")})}(Yt(t))}_renderMonitoringSection(t,e){const i=document.createElement("div");i.className="section",i.dataset.role="monitoring-section";const r=document.createElement("div");r.className="monitoring-header";const o=document.createElement("div");o.className="section-label",o.textContent=n("sidepanel.monitoring"),o.style.margin="0";const a=document.createElement("span-switch");a.dataset.role="monitoring-toggle";const s=e.monitoringInfo,l=Wt(s);l&&a.setAttribute("checked",""),r.appendChild(o),r.appendChild(a),i.appendChild(r),Be(this._hass)||i.appendChild(Ze());const c=document.createElement("div");c.dataset.role="monitoring-details",c.style.display=l?"block":"none",i.appendChild(c);const d=!0===s?.has_override,u=document.createElement("div");u.className="field-label",u.dataset.role="judged-against",u.setAttribute("aria-live","polite"),u.style.marginBottom="8px",u.textContent=this._judgedAgainstText(s),c.appendChild(u),this._ratingsEditor.mount(u);const h=document.createElement("div");h.className="radio-group",h.innerHTML=`\n \n \n `,c.appendChild(h),this._limitFields=[];const p=document.createElement("div");p.dataset.role="threshold-fields",p.style.display=d?"block":"none";const f=s?.continuous_threshold_pct??80,g=s?.spike_threshold_pct??100,m=s?.window_duration_m??15,v=s?.cooldown_duration_m??15;p.appendChild(this._createLimitRow(n("sidepanel.continuous_pct"),"continuous",f,null,e)),p.appendChild(this._createLimitRow(n("sidepanel.spike_pct"),"spike",g,null,e)),p.appendChild(this._createLimitRow(n("sidepanel.window_duration"),"window-m",m,"m",e)),p.appendChild(this._createLimitRow(n("sidepanel.cooldown"),"cooldown-m",v,"m",e)),c.appendChild(p),a.addEventListener("change",()=>{const t=a.checked;this._showMonitoringEnabled(e.uuid,t),this._sendMonitoringEnabled(e,t)});const _=h.querySelectorAll('input[type="radio"]');for(const t of _)t.addEventListener("change",()=>{t.checked&&("custom"===t.value?p.style.display="block":this.useGlobalThresholds())});t.appendChild(i),this._lockMonitoringIfReadOnly()}_lockMonitoringIfReadOnly(){const t=this.shadowRoot?.querySelector('[data-role="monitoring-section"]');t&&!Be(this._hass)&&Ye(t)}async _sendMonitoringEnabled(t,e){const n={circuit_id:t.entities?.power||t.uuid,monitoring_enabled:e};t.configEntryId&&(n.config_entry_id=t.configEntryId);const i=async()=>{try{return await qe(this._hass).setCircuitThreshold(n),!0}catch(t){return Ue(this.errorStore,t,"monitoring update"),!1}},r=this._storedMonitoring;if(r?.uuid!==t.uuid)return i();const o=await r.send(e,i);return this._showStoredMonitoring(r),o}_showMonitoringEnabled(t,e){const n=this.shadowRoot;if(!this._openCircuitConfig(t)||!n)return;const i=n.querySelector('[data-role="monitoring-toggle"]');i?.toggleAttribute("checked",e);const r=n.querySelector('[data-role="monitoring-details"]');if(r){const t=!e&&le(r);r.style.display=e?"block":"none",t&&i?.focus()}this._monitoringChanged(t,{monitoring_enabled:e})}_createLimitRow(t,e,n,i,r){const o=oi[e],{min:a,max:s}=he[o],l=document.createElement("div");l.className="field-row limit-row";const c=document.createElement("span");c.className="field-label",c.id=`threshold-label-${e}`,c.textContent=t;const d=document.createElement("div"),u=document.createElement("input");if(u.type="number",u.setAttribute("aria-labelledby",c.id),u.min=String(a),u.max=String(s),u.step="1",u.value=String(n),u.dataset.role=`threshold-${e}`,u.setAttribute("aria-describedby",`threshold-feedback-${e}`),d.appendChild(u),i){const t=document.createElement("span");t.textContent=i,d.appendChild(t)}const h=document.createElement("div");h.className="field-label rating-feedback limit-feedback",h.id=`threshold-feedback-${e}`,h.dataset.role=`threshold-feedback-${e}`,h.setAttribute("aria-live","polite");const p=me(u,o,{report:t=>{h.textContent=t??""},save:t=>{const e={circuit_id:r.entities?.power||r.uuid,[o]:t};r.configEntryId&&(e.config_entry_id=r.configEntryId),this._saveThresholds(r,e)}});return this._limitFields.push(p),l.append(c,d,h),l}_saveThresholds(t,e){qe(this._hass).setCircuitThreshold(e).then(()=>this._readThresholds(t,e),t=>Ue(this.errorStore,t,"monitoring update"))}_updateLiveState(){if(!this._config||this._config.panelMode)return;const t=this._config;if(!t.subDeviceMode&&!t.favoritesMode){if(t.entities?.switch){const e=this.shadowRoot?.querySelector('[data-role="relay-toggle"]');e&&this._applyRelayToggle(e,t)}if(t.entities?.select){const e=this.shadowRoot?.querySelector('[data-role="shedding-select"]');e&&this._applySheddingSelect(e,t)}}}_applyRelayToggle(t,e){if(!this._hass)return;const n=this._controlAccess;t.disabled=!n.mayOperate||"operable"!==ei(e,this._hass),vn(t,n),ti(e,this._hass)?t.setAttribute("checked",""):t.removeAttribute("checked")}_applySheddingSelect(t,e){if(!this._hass)return;const n=this._controlAccess,i=ri(e,this._hass);g.includes(i)?t.value=i:t.selectedIndex=-1,t.disabled=!n.mayOperate||!function(t,e){const n=ii(t,e);return void 0!==n&&Zn.has(n)}(e,this._hass),vn(t,n)}async _readThresholds(t,e){const n=++this._thresholdReads;let i=null;try{i=await this._readMonitoringStatus(t.configEntryId??null)}catch(t){console.warn("SPAN Panel: monitoring status read failed",t)}if(n!==this._thresholdReads)return;const r=ze(i,t);if(r)return void this._monitoringAnswered(t.uuid,r,i?.global_settings??null);const o={has_override:!0};"number"==typeof e.continuous_threshold_pct&&(o.continuous_threshold_pct=e.continuous_threshold_pct),"number"==typeof e.spike_threshold_pct&&(o.spike_threshold_pct=e.spike_threshold_pct),this._monitoringChanged(t.uuid,o)}async _readMonitoringStatus(t){if(!this._hass)return null;const e=await this._hass.callWS({type:"call_service",domain:s,service:"get_monitoring_status",service_data:t?{config_entry_id:t}:{},return_response:!0});return Le(e?.response)}_callDomainService(t,e){return this._hass?this._hass.callWS({type:"call_service",domain:s,service:t,service_data:e}):Promise.resolve()}_debounce(t,e,n){this._debounceTimers[t]&&clearTimeout(this._debounceTimers[t]),this._debounceTimers[t]=setTimeout(()=>{delete this._debounceTimers[t],n()},e)}}try{customElements.get("span-side-panel")||customElements.define("span-side-panel",di)}catch{}class ui extends At{constructor(){super(...arguments),this._store=null,this._unsub=null,this._errors=[]}set store(t){if(this._store===t)return;this._unsub?.(),this._unsub=null,this._store=t,this._errors=t.active;const e=t;this._unsub=t.subscribe(()=>{this._errors=e.active})}connectedCallback(){if(super.connectedCallback(),this._store&&!this._unsub){const t=this._store;this._errors=t.active,this._unsub=t.subscribe(()=>{this._errors=t.active})}}disconnectedCallback(){super.disconnectedCallback(),this._unsub?.(),this._unsub=null}render(){return 0===this._errors.length?ht:ct`${this._errors.map(t=>ct` + */let Ot=class extends Nt{constructor(t){if(super(t),this.it=ht,t.type!==Rt)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===ht||null==t)return this._t=void 0,this.it=t;if(t===ut)return t;if("string"!=typeof t)throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const e=[t];return e.raw=e,this._t={_$litType$:this.constructor.resultType,strings:e,values:[]}}};Ot.directiveName="unsafeHTML",Ot.resultType=1;const zt=(t=>(...e)=>({_$litDirective$:t,values:e}))(Ot);class $t{constructor(){this._persistent=new Map,this._transient=null,this._transientTimer=null,this._subscribers=new Set,this._watchedPanels=new Map}add(t){const e={...t,timestamp:Date.now()};if(e.persistent)this._persistent.set(e.key,e);else{this._clearTransient(),this._transient=e;const t=e.ttl??5e3;this._transientTimer=setTimeout(()=>{this._transient=null,this._transientTimer=null,this._notify()},t)}this._notify()}remove(t){if(this._persistent.has(t))return this._persistent.delete(t),void this._notify();this._transient?.key===t&&(this._clearTransient(),this._notify())}clear(t){void 0===t?(this._persistent.clear(),this._clearTransient(),this._watchedPanels.clear()):!0===t.persistent?this._persistent.clear():!1===t.persistent&&this._clearTransient(),this._notify()}get active(){const t=[...this._persistent.values()];return null!==this._transient&&t.push(this._transient),t}hasPersistent(t){return this._persistent.has(t)}hasAnyPanelOffline(){for(const t of this._persistent.keys())if("panel-offline"===t||t.startsWith("panel-offline:"))return!0;return!1}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}watchPanelStatus(t){this.watchPanelStatuses([{entityId:t,panelName:null}])}watchPanelStatuses(t){const e=this._watchedPanels,n=new Map;for(const i of t){const t=e.get(i.entityId);n.set(i.entityId,{panelName:i.panelName??null,wasOffline:t?.wasOffline??!1})}const i=this._isSingleUnnamed(e),r=this._isSingleUnnamed(n);for(const t of e.keys()){n.has(t)&&i===r||this._persistent.delete(this._offlineKey(t,i))}this._watchedPanels=n,this._notify()}clearPanelStatusWatch(){if(0===this._watchedPanels.size)return;const t=this._isSingleUnnamed(this._watchedPanels);for(const e of this._watchedPanels.keys())this._persistent.delete(this._offlineKey(e,t));this._watchedPanels.clear(),this._notify()}updateHass(t){if(0===this._watchedPanels.size)return;const e=this._isSingleUnnamed(this._watchedPanels);for(const[r,o]of this._watchedPanels){const a=t.states[r]?.state,s="on"===a,l=this._offlineKey(r,e),c=this._reconnectKey(r,e);if(s){const t=o.wasOffline;o.wasOffline=!1,this.remove(l),t&&this.add({key:c,level:"info",message:null===o.panelName?n("error.panel_reconnected"):i("error.panel_reconnected_named",{name:o.panelName}),persistent:!1})}else o.wasOffline=!0,this.hasPersistent(l)||this.add({key:l,level:"error",message:null===o.panelName?n("error.panel_offline"):i("error.panel_offline_named",{name:o.panelName}),persistent:!0})}}dispose(){this._clearTransient(),this._persistent.clear(),this._subscribers.clear(),this._watchedPanels.clear()}_isSingleUnnamed(t){if(1!==t.size)return!1;for(const e of t.values())return null===e.panelName;return!1}_offlineKey(t,e){return e?"panel-offline":`panel-offline:${t}`}_reconnectKey(t,e){return e?"panel-reconnected":`panel-reconnected:${t}`}_clearTransient(){null!==this._transientTimer&&(clearTimeout(this._transientTimer),this._transientTimer=null),this._transient=null}_notify(){for(const t of this._subscribers)try{t()}catch(t){console.warn("SPAN Panel: error-store subscriber threw",t)}}}const Ht={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ft(t){return String(t).replace(/[&<>"']/g,t=>Ht[t]??t)}const Bt="span_panel_list_columns";function Vt(){try{const t=localStorage.getItem(Bt);if(!t)return 1;const e=parseInt(t,10);return 1===e||2===e||3===e?e:1}catch{return 1}}function jt(t){try{localStorage.setItem(Bt,String(t))}catch{}}function qt(t){return(void 0===t.monitoring_rating_a?t.breaker_rating_a:t.monitoring_rating_a)??null}function Wt(t){return null!=t&&!1!==t.monitoring_enabled}function Ut(t,e){return Wt(e)?qt(t):t.breaker_rating_a??null}const Gt=["continuous_threshold_pct","spike_threshold_pct"];function Xt(t,e){return Wt(e)?function(t,e){return"averaged_legs"===t?.package_ratings_state&&Wt(e)}(t,e)?"averaged_legs":function(t,e){return t&&e&&function(t){const e=t.package_ratings_state;return"applies"===e||"pending"===e&&"one_space"===t.package_ratings_form}(t)&&Gt.some(t=>(e[t]??0)>100)?!0===e.has_override?"own":"global":null}(t,e):null}function Yt(t){return{amps:t?qt(t):void 0,panelAmps:t?.breaker_rating_a,userSet:!0===t?.monitoring_rating_user_set,packageRatings:t?.package_ratings_a??null}}function Zt(t){return t.packageRatings?.length&&t.panelAmps?i("monitoringRating.copied",{package:t.packageRatings.join("-"),panel:String(t.panelAmps)}):n("monitoringRating.copied_unnamed")}function Kt(t){if(!t.amps)return"";const e=`${Ft(t.amps)}A`;return t.userSet?`${e}${function(t){const e=Ft(Zt(t));return``}(t)}`:e}function Qt(t){const e=t.nextElementSibling;e instanceof HTMLElement&&e.classList.contains("rating-copied-note")&&(e.hidden=!e.hidden,t.setAttribute("aria-expanded",String(!e.hidden)))}function Jt(t){return t instanceof Error||"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message?t.message:String(t)}const te=new Set(["Unauthorized","UnknownUser"]);function ee(t){if("object"!=typeof t||null===t)return!1;const e="code"in t?t.code:void 0;return"unauthorized"===e||"home_assistant_error"===e&&"message"in t&&te.has(t.message)}const ne="Validation error: ",ie={translation_domain:t=>"translation_domain"in t?t.translation_domain:void 0,translation_key:t=>"translation_key"in t?t.translation_key:void 0,translation_placeholders:t=>"translation_placeholders"in t?t.translation_placeholders:void 0};function re(t,e){return"object"==typeof t&&null!==t?ie[e](t):void 0}async function oe(t,e,n,i){const r=re(e,"translation_key");if(t&&"string"==typeof r&&re(e,"translation_domain")===n){const i=`component.${n}.exceptions.${r}.message`;try{const r=t.loadBackendTranslation?await t.loadBackendTranslation("exceptions",n):t.localize,o=r?.(i,function(t){const e=re(t,"translation_placeholders");if("object"!=typeof e||null===e)return{};const n={};for(const[t,i]of Object.entries(e))"string"!=typeof i&&"number"!=typeof i||(n[t]=i);return n}(e));if(o)return o}catch{}}const o=Jt(e),a=o.startsWith(ne)?o.slice(18):o;return a&&"[object Object]"!==a?a:i}function ae(t){const e=t.getRootNode();return e instanceof Document||e instanceof ShadowRoot?e.activeElement:null}function se(t){return null!==t&&ae(t)===t}function le(t){if(!t)return!1;const e=ae(t);return null!==e&&t.contains(e)}function ce(t){if(!t)return null;const e=ae(t);return e instanceof HTMLElement&&t.contains(e)?e:null}function de(){return null===document.activeElement||document.activeElement===document.body}function ue(t,e){t.addEventListener("blur",()=>{queueMicrotask(()=>{t.isConnected&&e()})})}const he={continuous_threshold_pct:{min:1,max:200},spike_threshold_pct:{min:1,max:200},window_duration_m:{min:1,max:180},cooldown_duration_m:{min:1,max:180}},pe=["continuous_threshold_pct","spike_threshold_pct","window_duration_m","cooldown_duration_m"];function fe(t){return pe.some(e=>e===t)}function ge(t){t.addEventListener("wheel",e=>{se(t)&&e.preventDefault()},{passive:!1})}function me(t,e,n){const{min:r,max:o}=he[e];ge(t);let a=!1;const s=e=>{e?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),n.report(e)},l=()=>{const e=""===t.value.trim()?Number.NaN:Number(t.value);return Number.isSafeInteger(e)&&e>=r&&e<=o?e:(s(i("monitoring.limit_invalid",{min:String(r),max:String(o)})),null)},c=()=>{if(!a)return;const t=l();null!==t&&(a=!1,s(null),n.save(t))};return t.addEventListener("input",()=>{a=!0,s(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&c()}),ue(t,c),{get dirty(){return a},check:l}}function ve(t,e){ge(t);let i=!1,r=null;const o=n=>{n?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),e.report(n)},a=()=>{i=!1,r=null,o(null);const n=e.stored();t.value=null!==n?String(n):""},s=()=>{if(!i)return;const s=t.value.trim();if(""===s&&t.validity?.badInput)return void o(n("monitoringRating.invalid_other"));if(""===s)return void a();const l=Number(s);!Number.isSafeInteger(l)||l<1?o(n("monitoringRating.invalid_other")):(i=!1,o(null),l!==e.stored()&&(r=l,e.save(l)))};return t.addEventListener("input",()=>{i=!0,r=null,o(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&s()}),ue(t,s),{get dirty(){return i},revert:a,answerRefusal:t=>r===t&&(a(),!0)}}function _e(t,e,i){console.warn("SPAN Panel: package ratings update failed",i),oe(t,i,s,n("error.package_ratings_failed")).then(t=>{e?.add({key:"service:package-ratings",level:"error",message:t,persistent:!1})})}function ye(t){return t.members.map((e,n)=>({uuid:t.memberIds[n],circuit:e}))}function be(t){return new Map(t.flatMap(t=>t.memberIds.map(e=>[e,t])))}function xe(t,e){if(!e)return t;const{breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}=e.circuit;return{...t,breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}}function we(t){const e=t.circuits,n=new Map;for(const[t,i]of Object.entries(e)){const e=i.shared_meter_group;e&&n.set(e,[...n.get(e)??[],[t,i]])}const i=[];for(const[r,o]of Object.entries(e)){const e=o.shared_meter_group,a=e?n.get(e):void 0;if(e&&a){if(a[0][0]===r){const[n,r]=a.find(([t])=>t===e)??a[0],o=a.map(([,t])=>t),s=t.shared_meter_groups?.[e];i.push({uuid:n,circuit:{...r,tabs:Se(o),breaker_rating_a:s?s.breaker_rating_a:ke(o),monitoring_rating_a:s?.monitoring_rating_a,monitoring_rating_user_set:!0===s?.monitoring_rating_user_set},members:o,memberIds:a.map(([t])=>t)})}}else i.push({uuid:r,circuit:o,members:[o],memberIds:[r]})}return i}function Se(t){return[...new Set(t.flatMap(t=>t.tabs))].sort((t,e)=>t-e)}function Ce(t){const e=function(t){return t.some(t=>!t.breaker_rating_a)?"":t.map(t=>Math.round(t.breaker_rating_a)).join("·")}(t);return e?1===t.length?`${e}A`:`${e} A`:""}function ke(t){let e=0;for(const n of t){if(!n.breaker_rating_a)return null;e+=n.breaker_rating_a}return e}function Me(t){if(1===t.length){const e=t[0].breaker_rating_a;return e?`${e}A`:""}return Ce(t)}function Te(t){if(!t?.offered)return null;const[e,...n]=t.members;if(!e||n.length>0)return null;const i=e.circuit.package_ratings_form,r=e.circuit.breaker_rating_a;return"one_space"!==i&&"two_spaces"!==i||null==r?null:{kind:i,member:e,panelA:r}}function Ae(t){return t.circuit.package_ratings_a?.[1]??null}class Ie{constructor(t){this._host=t,this._section=null,this._field=null}get element(){return this._section}mount(t){this._field=null;const e=Te(this._host.ratingsView);this._section=e?this._build(e):null,this._section&&t.after(this._section)}sync(t){const e=Te(this._host.ratingsView),n=this._section;if(n&&e&&n.dataset.kind===e.kind&&n.dataset.uuid===e.member.uuid)return void this._patch(n,e);const i=(r=n,ce(r)?.dataset.role??null);var r;this._field=null;const o=e?this._build(e):null;if(n&&o?n.replaceWith(o):n?n.remove():o&&t.after(o),this._section=o,null===i)return;const a=o?.querySelector(`[data-role="${i}"]`)??o?.querySelector('[data-role="rating-input"]');a?a.focus():this._host.focusAfterRatingsEditor()}_build(t){const e=document.createElement("div");e.dataset.role="rating-section",e.dataset.kind=t.kind,e.dataset.uuid=t.member.uuid,e.className="rating-section";const i=document.createElement("div");i.className="section-label",i.textContent=n("monitoringRating.title"),e.appendChild(i);const r=document.createElement("div");r.className="field-label",r.id="rating-guidance",r.dataset.role="rating-guidance",r.textContent=n("one_space"===t.kind?"monitoringRating.guidance":"monitoringRating.guidance_two_spaces"),e.appendChild(r);const o=document.createElement("div");o.className="field-label rating-feedback",o.id="rating-feedback",o.dataset.role="rating-feedback",o.setAttribute("aria-live","polite"),e.appendChild(this._buildRow(t,o)),e.appendChild(o);const a=document.createElement("div");return a.dataset.role="rating-warning-region",a.setAttribute("aria-live","polite"),e.appendChild(a),this._syncWarning(e,t.member),e}_buildRow(t,e){const{member:r}=t,o=document.createElement("div");o.className="field-row rating-row",o.dataset.role="rating-row",o.dataset.uuid=r.uuid;const a=document.createElement("span");a.className="field-label",a.id="rating-panel-rating",a.dataset.role="rating-panel-rating",a.textContent=i("monitoringRating.panel_rating",{panel:String(t.panelA)});const s=document.createElement("span");s.className="field-label",s.textContent=n("monitoringRating.other_breaker");const l=document.createElement("input");l.type="number",l.min="1",l.step="1",l.inputMode="numeric";const c=Ae(r);return l.value=null!==c?String(c):"",l.setAttribute("aria-label",i("monitoringRating.other_breaker_label",{circuit:r.circuit.name})),l.setAttribute("aria-describedby","rating-panel-rating rating-guidance rating-feedback"),l.dataset.role="rating-input",this._field=ve(l,{report:t=>{e.textContent=t??""},stored:()=>this._storedInForce(),save:t=>this._save(t)}),o.append(a,s,l),null!==c&&o.appendChild(this._buildReset(r.uuid)),o}_buildReset(t){const e=document.createElement("button");return e.type="button",e.className="text-btn",e.dataset.role="rating-reset",e.textContent=n("monitoringRating.reset"),e.addEventListener("click",()=>{this._field?.revert(),this._host.clearPackageRatings(t).catch(t=>this._host.reportRatingsFailure(t))}),e}_patch(t,e){const{member:n}=e,r=Ae(n),o=t.querySelector('[data-role="rating-panel-rating"]');o&&(o.textContent=i("monitoringRating.panel_rating",{panel:String(e.panelA)}));const a=t.querySelector('[data-role="rating-input"]');this._field&&!this._field.dirty&&this._field.revert();const s=t.querySelector('[data-role="rating-row"]'),l=t.querySelector('[data-role="rating-reset"]');null===r&&l?(se(l)&&a?.focus(),l.remove()):null!==r&&!l&&s&&s.appendChild(this._buildReset(n.uuid)),this._syncWarning(t,n)}_storedInForce(){const t=Te(this._host.ratingsView);return t?Ae(t.member):null}_save(t){const e=Te(this._host.ratingsView);if(!e)return;const{member:n,panelA:i}=e;this._host.setPackageRatings(n.uuid,[i,t]).catch(e=>{this._host.reportRatingsFailure(e),this._answerRefusal(n.uuid,t)})}_answerRefusal(t,e){const n=this._section,i=n?.querySelector('[data-role="rating-input"]'),r=this._field;n&&i&&r&&n.dataset.uuid===t&&Te(this._host.ratingsView)?.member.uuid===t&&r.answerRefusal(e)&&(de()||le(n))&&i.focus()}_syncWarning(t,e){const n=t.querySelector('[data-role="rating-warning-region"]');if(!n)return;const i=Xt(e.circuit,this._host.ratingsView?.monitoringInfo??null),r=n.firstElementChild instanceof HTMLElement?n.firstElementChild:null;if(r&&r.dataset.kind===i)return;const o=le(r);r?.remove(),i&&n.appendChild("averaged_legs"===i?this._buildAveragedLegsWarning():this._buildThresholdWarning(i)),o&&this._host.focusAfterRatingsEditor()}_buildThresholdWarning(t){const e="own"===t?n("monitoringRating.threshold_warning"):i("monitoringRating.threshold_warning_global",{settings:n("monitoring.global_settings"),tab:n("tab.monitoring")}),r=this._buildWarning("rating-threshold-warning",t,e);return"own"===t&&r.appendChild(this._buildActionButton("rating-threshold-reset",n("monitoringRating.use_global_thresholds"),()=>this._host.useGlobalThresholds())),r}_buildAveragedLegsWarning(){const t=this._buildWarning("rating-averaged-legs-warning","averaged_legs",n("monitoringRating.averaged_legs"));return t.appendChild(this._buildActionButton("rating-turn-off-monitoring",n("monitoringRating.turn_off_monitoring"),()=>this._host.turnOffMonitoring())),t}_buildWarning(t,e,n){const i=document.createElement("div");i.className="field-label rating-warning",i.dataset.role=t,i.dataset.kind=e,i.setAttribute("role","note");const r=document.createElement("span");return r.textContent=n,i.appendChild(r),i}_buildActionButton(t,e,n){const i=document.createElement("button");return i.type="button",i.className="text-btn",i.dataset.role=t,i.textContent=e,i.addEventListener("click",()=>{"true"!==i.getAttribute("aria-disabled")&&(i.setAttribute("aria-disabled","true"),n().then(t=>{t||i.removeAttribute("aria-disabled")}))}),i}}function Pe(t){return new Promise(e=>setTimeout(e,t))}class De{constructor(t,{passThrough:e=()=>!1}={}){this._store=t,this._passThrough=e}async callWS(t,e,n){const i=n?.retries??3,r=n?.errorId??`ws:${String(e.type??"unknown")}`;return this._withRetry(()=>t.callWS(e),i,r,n?.errorMessage)}async _withRetry(t,e,i,r){if(this._store.hasAnyPanelOffline())try{const e=await t();return this._store.remove(i),e}catch(t){if(this._passThrough(t))throw t;const e=t instanceof Error?t:new Error(Jt(t));throw this._store.add({key:i,level:"error",message:r??n("error.panel_offline"),persistent:!1}),e}let o;for(let n=0;n<=e;n++)try{const e=await t();return this._store.remove(i),e}catch(t){if(this._passThrough(t))throw t;if(o=t instanceof Error?t:new Error(Jt(t)),n{try{const i={};e&&(i.config_entry_id=e);const o={type:"call_service",domain:s,service:"get_monitoring_status",service_data:i,return_response:!0},a=this._retry?await this._retry.callWS(t,o,{errorId:"fetch:monitoring",errorMessage:n("error.monitoring_failed")}):await t.callWS(o),l=Le(a?.response);return r===this._generation&&(this._status=l,this._lastFetch=Date.now()),l}catch(t){return console.warn("SPAN Panel: monitoring status fetch failed",t),r===this._generation&&(this._status=null),this._retry||this._errorStore?.add({key:"fetch:monitoring",level:"warning",message:n("error.monitoring_failed"),persistent:!1}),null}finally{this._inflight?.gen===r&&(this._inflight=null)}})();return this._inflight={gen:r,promise:o},o}invalidate(){this._lastFetch=0,this._generation++}get status(){return this._status}clear(){this._status=null,this._lastFetch=0,this._generation++}}class Re{constructor(){this._caches=new Map,this._errorStore=null}get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t;for(const e of this._caches.values())e.errorStore=t}async fetchOne(t,e){let n=this._caches.get(e);return n||(n=new Ee,n.errorStore=this._errorStore,this._caches.set(e,n)),n.fetch(t,e)}invalidate(){for(const t of this._caches.values())t.invalidate()}clear(){this._caches.clear()}}function Ne(t){return t.entities?.current??t.entities?.power??""}function Oe(t,e){return function(t,e){return t?.circuits?t.circuits[e]??null:null}(t,Ne(e))}function ze(t){const e=new Map;for(const n of Object.values(t?.circuits??{})){const t=Ne(n);t&&n.name&&e.set(t,n.name)}return e}function $e(t){return{continuousPct:t?.continuous_threshold_pct??80,spikePct:t?.spike_threshold_pct??100}}function He(t,e){const{continuousPct:n,spikePct:i}=$e(e);return t>=i?"alert":t>=n?"warning":"normal"}function Fe(t,e){return`utilization-${He(t,e)}`}function Be(t){return!0===t?.user?.is_admin}function Ve(){return n("monitoring.admin_only")}class je extends Error{constructor(){super(Ve()),this.name="MonitoringChangeRefused"}}function qe(t){const e=e=>n=>async function(t,e,n){if(!t||!Be(t))throw new je;try{await t.callWS({type:"call_service",domain:s,service:e,service_data:n})}catch(t){throw ee(t)?new je:t}}(t,e,n);return{setGlobalMonitoring:e("set_global_monitoring"),testNotification:e("test_notification"),setCircuitThreshold:e("set_circuit_threshold"),clearCircuitThreshold:e("clear_circuit_threshold"),setMainsThreshold:e("set_mains_threshold"),clearMainsThreshold:e("clear_mains_threshold"),setCircuitPackageRatings:e("set_circuit_package_ratings"),clearCircuitPackageRatings:e("clear_circuit_package_ratings")}}function We(t,e){return t instanceof je?t.message:e}function Ue(t,e,i){console.warn(`SPAN Panel: ${i} failed`,e),t?.add({key:"service:monitoring",level:"error",message:We(e,n("error.threshold_failed")),persistent:!1})}const Ge=new Set(["number","text"]);function Xe(t){for(let e=t;e;e=e.parentElement)if(""!==e.style.opacity&&Number(e.style.opacity)<1)return!0;return!1}function Ye(t,e){const n=Ve();for(const i of t.querySelectorAll("input, select, textarea, button, span-switch"))void 0!==e&&i.matches(e)||(i instanceof HTMLInputElement&&Ge.has(i.type)||i instanceof HTMLTextAreaElement?i.readOnly=!0:i.setAttribute("disabled",""),i.title=n,"span-switch"!==i.localName&&(Xe(i)||(i.style.opacity="0.5"),i.style.cursor="not-allowed"))}function Ze(){const t=document.createElement("p");return t.dataset.role="monitoring-read-only",t.setAttribute("role","note"),t.style.cssText="margin:8px 0 12px;font-size:0.85em;color:var(--secondary-text-color);",t.textContent=Ve(),t}const Ke=["relay_state","relay_state_target","priority","priority_target"];function Qe(t){return"_favoriteRefs"in t}const Je=Object.freeze({mayOperate:!0,reason:null}),tn=Object.freeze({mayOperate:!1,reason:null}),en=["control_disabled","admin_only","read_only"];function nn(t){const e=t?.control_access;return"object"==typeof e&&null!==e&&"may_operate"in e&&"boolean"==typeof e.may_operate?e.may_operate?Je:{mayOperate:!1,reason:"reason"in e&&(n=e.reason,en.some(t=>t===n))?e.reason:null}:Je;var n}function rn(t){return"circuit"===t?.kind}function on(t,e){if(!t||!Qe(t))return nn(t);const n=t._favoriteRefs[e];return rn(n)?n.controlAccess:tn}function an(t){if(!t||!Qe(t))return nn(t);const e=[...cn(t,sn).values()],[n]=e;return!n||e.some(t=>t.mayOperate)?Je:n}function sn(t){return!!t?.entities?.switch&&!1!==t.is_user_controllable}function ln(t){return sn(t)||!!t?.entities?.select}function cn(t,e){const n=new Map;for(const[i,r]of Object.entries(t._favoriteRefs))rn(r)&&e(t.circuits[i])&&n.set(r.panelDeviceId,r.controlAccess);return n}const dn={control_disabled:()=>n("controls.disabled"),admin_only:()=>n("controls.admin_only"),read_only:()=>n("controls.read_only")};function un(t){return t.mayOperate?"":t.reason?dn[t.reason]():n("controls.not_operable")}class hn extends Error{constructor(t){super(t),this.name="ControlChangeRefused"}}function pn(t,e){return{setRelay:(n,i)=>fn(t,e,"switch",i?"turn_on":"turn_off",n,{}),setPriority:(n,i)=>fn(t,e,"select","select_option",n,{option:i})}}async function fn(t,e,i,r,o,a){if(!e.mayOperate)throw new hn(un(e));try{await t.callWS({type:"call_service",domain:i,service:r,service_data:a,target:{entity_id:o}})}catch(t){throw ee(t)?new hn(n("controls.entity_unauthorized")):t}}const gn={relay:{key:"service:relay",fallback:()=>n("error.relay_failed")},priority:{key:"service:shedding",fallback:()=>n("error.shedding_failed")}};function mn(t,e,n,i){console.warn(`SPAN Panel: ${i} change failed`,n);const{key:r,fallback:o}=gn[i];oe(t,n,s,o()).then(t=>{e?.add({key:r,level:"error",message:t,persistent:!1})})}function vn(t,e){const n=un(e);n?t.title=n:t.removeAttribute("title")}function _n(t){const e=un(t);return e?`

${Ft(e)}

`:""}const yn="favorites-changed";async function bn(t,e,n={}){const i=await t.callWS({type:"call_service",domain:s,service:e,service_data:n,return_response:!0});return i?.response??null}class xn{get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this._retry=t?new De(t):null}constructor(){this._errorStore=null,this._retry=null,this._map=null,this._lastFetch=0,this._inflight=null,this._generation=0}async fetch(t){const e=Date.now();if(this._inflight&&this._inflight.gen===this._generation)return this._inflight.promise;if(this._map&&e-this._lastFetch<3e4)return this._map;const i=this._generation,r=(async()=>{try{const e={type:"call_service",domain:s,service:"get_favorites",service_data:{},return_response:!0},r=this._retry?await this._retry.callWS(t,e,{errorId:"fetch:favorites",errorMessage:n("error.favorites_fetch_failed")}):await t.callWS(e),o=r?.response?.favorites??{};return i===this._generation&&(this._map=o,this._lastFetch=Date.now()),o}catch(t){return console.warn("SPAN Panel: favorites fetch failed",t),this._retry||this._errorStore?.add({key:"fetch:favorites",level:"warning",message:n("error.favorites_fetch_failed"),persistent:!1}),this._map??{}}finally{this._inflight?.gen===i&&(this._inflight=null)}})();return this._inflight={gen:i,promise:r},r}invalidate(){this._lastFetch=0,this._generation++}clear(){this._map=null,this._lastFetch=0,this._generation++}get map(){return this._map??{}}}function wn(t){return Object.keys(t).some(e=>Sn(t,e))}function Sn(t,e){const n=t[e];return(n?.circuits?.length??0)>0||(n?.sub_devices?.length??0)>0}const Cn={names:["power","battery power"],suffixes:["_power"]},kn={names:["battery level","battery percentage"],suffixes:["_battery_level","_battery_percentage"]},Mn={names:["state of energy"],suffixes:["_soe_kwh"]};function Tn(t,e){if(!t.entities)return null;for(const[n,i]of Object.entries(t.entities)){if("sensor"!==i.domain)continue;const t=(i.original_name??"").toLowerCase();if(e.names.some(e=>t===e))return n;if(i.unique_id&&e.suffixes.some(t=>i.unique_id.endsWith(t)))return n}return null}function An(t){return Tn(t,kn)}function In(t){return Tn(t,Mn)}function Pn(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}function Dn(t){const e=t.solar;return e?"inverter"===e.role?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:null}:e.power_entity_id?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:e.site_power_entity_id}:{headlineEid:e.site_power_entity_id,headlineIsSiteTotal:null!==e.site_power_entity_id,siteTotalEid:null}:{headlineEid:(n=t,Tn(n,Cn)),headlineIsSiteTotal:!1,siteTotalEid:null};var n}function Ln(t){const{headlineEid:e,siteTotalEid:n}=Dn(t),i=[e,n];return t.type===l&&i.push(An(t),In(t)),new Set(i.filter(t=>null!==t))}function En(t){const e=[{role:"power",entityId:Dn(t).headlineEid}];return t.type===l&&e.push({role:"soc",entityId:An(t)},{role:"soe",entityId:In(t)}),e.filter(t=>null!==t.entityId)}function Rn(t,e){return Pn(t.states[e])}function Nn(t){if(!t)return null;let e=null;for(const[n,i]of Object.entries(t)){if("sensor"===i.domain)return n;e||(e=n)}return e}function On(t,e){return En(t).length>0||e&&null!==Nn(t.entities)}function zn(t){return"number"==typeof t&&Number.isInteger(t)&&t>0}function $n(t){return!0===t.outside_panel}function Hn(t,e){if(!t)return null;let n=null,i=null;const{first_position:r,last_position:o}=t;zn(r)&&zn(o)&&r<=o?(n=r,i=o):zn(e)&&(n=1,i=e);for(const e of Object.values(t.circuits))if(e&&!$n(e))for(const t of e.tabs??[])zn(t)&&(n=null===n?t:Math.min(n,t),i=null===i?t:Math.max(i,t));return null===n||null===i?null:{first:n,last:i}}function Fn(t){return Math.ceil(t/2)}function Bn(t){return t%2==0?1:0}function Vn(t){if(2!==t.length)return null;const[e,n]=[Math.min(...t),Math.max(...t)];return Fn(e)===Fn(n)?"row-span":Bn(e)===Bn(n)?"col-span":"row-span"}function jn(t,e,n,i){const r=[];return n||r.push("circuit-off"),i&&r.push("circuit-producer"),function(t){return!!t&&null!=t.over_threshold_since}(e)&&r.push("circuit-alert"),r.join(" ")}function qn(t,e){return $n(t)||ti(t,e)}function Wn(t,e){const n=t.entities?.power;return Pn(n?e.states[n]:void 0)}function Un(t,e){const n=t.entities?.current;return Pn(n?e.states[n]:void 0)}function Gn(t){return t.is_generation??"pv"===t.device_type}function Xn(t,e){return Gn(t)||null!==e&&e<0}function Yn(t,e,n){const i=Un(t,e);if(t.entities?.current&&null===i)return null;const r=n?.utilization_pct??null,o=Ut(t,n);return null===r&&null!==i&&o?Math.round(Math.abs(i)/o*1e3)/10:r}const Zn=new Set(g),Kn={NEVER:"never",SOC_THRESHOLD:"soc_threshold",OFF_GRID:"off_grid"};function Qn(t,e){const n=t.entities?.switch;return n?e.states[n]?.state:void 0}function Jn(t,e,n){const i=t.entities?.power,r=i?e.states[i]?.attributes?.[n]:void 0;return"string"==typeof r&&r?r:void 0}function ti(t,e){const n=Qn(t,e);return"on"===n||"off"===n?"on"===n:"CLOSED"===(Jn(t,e,"relay_state")??t.relay_state)}function ei(t,e){if(!t.entities?.switch||!1===t.is_user_controllable)return"none";const n=Qn(t,e);return void 0===n?"none":"on"===n||"off"===n?"operable":"inert"}function ni(t){return void 0===t?void 0:Kn[t]}function ii(t,e){const n=t.entities?.select;return n?e.states[n]?.state:void 0}function ri(t,e){if(t.always_on)return"always_on";if(!t.entities?.select)return"unknown";const n=ii(t,e);return void 0!==n&&Zn.has(n)?n:ni(Jn(t,e,"shed_priority"))??ni(t.priority)??"unknown"}const oi={continuous:"continuous_threshold_pct",spike:"spike_threshold_pct","window-m":"window_duration_m","cooldown-m":"cooldown_duration_m"},ai="relay-label",si="priority-label",li="controls-note";class ci{constructor(t,e){this.uuid=t,this._on=e,this._sent=0,this._from=0,this._pending=0}get on(){return this._on}get settled(){return 0===this._pending}answered(t){this._on=t}async send(t,e){const n=++this._sent;this._pending+=1;try{const i=await e();return i&&n>this._from&&(this._on=t,this._from=n),i}finally{this._pending-=1}}}class di extends HTMLElement{constructor(){super(),this.errorStore=null,this._thresholdReads=0,this._limitFields=[],this._storedMonitoring=null,this._controlAccess=tn,this.attachShadow({mode:"open"}),this._hass=null,this._config=null,this._debounceTimers={},this._ratingsEditor=new Ie(this)}set hass(t){const e=Be(this._hass)!==Be(t);this._hass=t,this.hasAttribute("open")&&this._config&&(e&&this._showsMonitoring()?this._render():this._updateLiveState())}_showsMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!0!==t.showMonitoring)}get hass(){return this._hass}open(t){this._config=t,this._storedMonitoring=t.panelMode||t.subDeviceMode||t.favoritesMode?null:new ci(t.uuid,Wt(t.monitoringInfo)),this._controlAccess=t.panelMode||t.subDeviceMode||t.favoritesMode?tn:t.controlAccess,this._render(),this.offsetHeight,this.setAttribute("open",""),this.setAttribute("data-mode",this._modeFor(t))}get openCircuit(){const t=this._config;return!t||!this.hasAttribute("open")||t.panelMode||t.subDeviceMode||t.favoritesMode?null:{uuid:t.uuid,configEntryId:t.configEntryId??null}}refreshRating(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i={...e,members:t.members,capacityA:t.capacityA,monitoringInfo:t.monitoringInfo,monitoringGlobals:t.monitoringGlobals};this._config=i,this._monitoringStoredAs(e.uuid,t.monitoringInfo);const r=n.querySelector(".subtitle");r&&(r.textContent=this._circuitSubtitle(i)),this._syncMonitoring()}close(){this.removeAttribute("open"),this.removeAttribute("data-mode"),this._config=null,this._storedMonitoring=null,this._controlAccess=tn,this.dispatchEvent(new CustomEvent("side-panel-closed",{bubbles:!0,composed:!0}))}_modeFor(t){return t.favoritesMode?"favorites":t.panelMode?"panel":t.subDeviceMode?"subDevice":"circuit"}_render(){const t=this._config;if(!t)return;const e=this.shadowRoot;if(!e)return;e.innerHTML="";const n=document.createElement("style");n.textContent='\n :host {\n display: block;\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n width: 360px;\n max-width: 90vw;\n z-index: 1000;\n transform: translateX(100%);\n transition: transform 0.3s ease;\n pointer-events: none;\n }\n :host([open]) {\n transform: translateX(0);\n pointer-events: auto;\n }\n\n .backdrop {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.3);\n z-index: -1;\n }\n :host([open]) .backdrop {\n display: block;\n }\n\n .panel {\n height: 100%;\n background: var(--card-background-color, #fff);\n border-left: 1px solid var(--divider-color, #e0e0e0);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n\n .panel-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px;\n border-bottom: 1px solid var(--divider-color, #e0e0e0);\n }\n .panel-header .title {\n font-size: 18px;\n font-weight: 500;\n color: var(--primary-text-color, #212121);\n margin: 0;\n }\n .panel-header .subtitle {\n font-size: 13px;\n color: var(--secondary-text-color, #727272);\n margin: 2px 0 0 0;\n }\n .close-btn {\n background: none;\n border: none;\n cursor: pointer;\n color: var(--secondary-text-color, #727272);\n padding: 4px;\n line-height: 1;\n font-size: 20px;\n }\n\n .panel-body {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n }\n\n .section {\n margin-bottom: 20px;\n }\n .section-label {\n font-size: 12px;\n font-weight: 600;\n text-transform: uppercase;\n color: var(--secondary-text-color, #727272);\n margin: 0 0 8px 0;\n letter-spacing: 0.5px;\n }\n\n .field-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 8px 0;\n }\n /* Why the section\'s relay or priority cannot be operated, under it. */\n .controls-note {\n margin: 4px 0 0;\n font-size: 0.85em;\n color: var(--secondary-text-color, #727272);\n }\n .field-label {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n }\n\n select {\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n }\n\n input[type="number"] {\n width: 72px;\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n text-align: right;\n }\n input[type="number"]:disabled {\n opacity: 0.5;\n }\n\n .radio-group {\n display: flex;\n gap: 16px;\n padding: 8px 0;\n }\n .radio-group label {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n cursor: pointer;\n }\n\n .horizon-bar {\n display: flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n margin-top: 4px;\n }\n .horizon-segment {\n flex: 1;\n padding: 6px 0;\n text-align: center;\n font-size: 13px;\n cursor: pointer;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n transition: background 0.15s ease, color 0.15s ease;\n user-select: none;\n line-height: 1.4;\n }\n .horizon-segment:last-child {\n border-right: none;\n }\n .horizon-segment:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .horizon-segment.active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n .horizon-segment.referenced {\n box-shadow: inset 0 -3px 0 var(--primary-color, #03a9f4);\n }\n\n .unit-toggle {\n display: inline-flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n }\n .unit-btn {\n padding: 4px 10px;\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease;\n }\n .unit-btn:last-child {\n border-right: none;\n }\n .unit-btn:hover:not(.unit-active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .unit-btn.unit-active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n\n .monitoring-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n\n .fav-heart {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--secondary-text-color, #727272);\n border-radius: 4px;\n padding: 2px 6px;\n cursor: pointer;\n font-size: 0.9em;\n margin-right: 6px;\n line-height: 1;\n display: inline-flex;\n align-items: center;\n }\n .fav-heart.active {\n color: var(--primary-color, #03a9f4);\n border-color: var(--primary-color, #03a9f4);\n }\n .fav-heart:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .fav-heart span-icon {\n --mdc-icon-size: 16px;\n }\n\n .rating-section {\n margin-bottom: 8px;\n }\n .limit-row {\n flex-wrap: wrap;\n }\n .limit-feedback {\n flex-basis: 100%;\n }\n .rating-row {\n flex-wrap: wrap;\n justify-content: flex-start;\n gap: 6px 8px;\n }\n .rating-row [data-role="rating-panel-rating"] {\n flex-basis: 100%;\n }\n .rating-feedback {\n font-size: 13px;\n color: var(--error-color, #db4437);\n }\n .rating-warning {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 6px 8px;\n margin-top: 6px;\n padding: 8px;\n border-left: 3px solid var(--warning-color, #ffa600);\n border-radius: 4px;\n background: color-mix(in srgb, var(--warning-color, #ffa600) 12%, transparent);\n font-size: 13px;\n }\n\n .text-btn {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--primary-text-color, #212121);\n border-radius: 4px;\n padding: 4px 8px;\n font: inherit;\n font-size: 13px;\n line-height: 1.3;\n cursor: pointer;\n }\n .text-btn:hover:not(:disabled):not([aria-disabled="true"]) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .text-btn:focus-visible {\n outline: 2px solid var(--primary-color, #03a9f4);\n outline-offset: 1px;\n }\n .text-btn:disabled,\n .text-btn[aria-disabled="true"] {\n opacity: 0.5;\n cursor: default;\n }\n\n .panel-mode-info {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n line-height: 1.6;\n }\n .panel-mode-info p {\n margin: 0 0 12px 0;\n }\n\n',e.appendChild(n);const i=document.createElement("div");i.className="backdrop",i.addEventListener("click",()=>this.close()),e.appendChild(i);const r=document.createElement("div");r.className="panel",e.appendChild(r),t.favoritesMode?this._renderFavoritesMode(r):t.panelMode?this._renderPanelMode(r):t.subDeviceMode?this._renderSubDeviceMode(r,t):this._renderCircuitMode(r,t)}_renderPanelMode(t){const e=this._config,i=this._createHeader(n("sidepanel.graph_settings"),n("sidepanel.global_defaults"));t.appendChild(i);const r=document.createElement("div");r.className="panel-body";const s=e.graphSettings,l=e.topology,c=s?.global_horizon??o,d=s?.circuits??{};r.appendChild(this._buildListColumnsSection());const u=document.createElement("div");u.className="section";const h=document.createElement("div");h.className="section-label",h.textContent=n("sidepanel.graph_horizon"),u.appendChild(h);const p=document.createElement("div");p.className="field-row";const f=document.createElement("span");f.className="field-label",f.textContent=n("sidepanel.global_default"),p.appendChild(f);const g=document.createElement("select");for(const t of Object.keys(a)){const e=document.createElement("option");e.value=t;const i=`horizon.${t}`,r=n(i);e.textContent=r!==i?r:t,t===c&&(e.selected=!0),g.appendChild(e)}if(g.addEventListener("change",()=>{const t={horizon:g.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_graph_time_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})}),p.appendChild(g),u.appendChild(p),r.appendChild(u),l?.circuits){const t=document.createElement("div");t.className="section";const i=document.createElement("div");i.className="section-label",i.textContent=n("sidepanel.circuit_scales"),t.appendChild(i);const o=Object.entries(l.circuits).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[n,i]of o){const r=this._buildPanelModeCircuitRow(n,i,d[n],c,e.configEntryId??null,e.showFavorites??!1,e.favoritePanelDeviceId,e.favoriteCircuitUuids);t.appendChild(r)}r.appendChild(t)}const m=s?.sub_devices??{};if(l?.sub_devices){const t=document.createElement("div");t.className="section";const i=document.createElement("div");i.className="section-label",i.textContent=n("sidepanel.subdevice_scales"),t.appendChild(i);const o=Object.entries(l.sub_devices).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[i,r]of o){const o=En(r).length>0,s=e.showFavorites&&e.favoritePanelDeviceId?this._buildSubDeviceFavoriteHeart(r.entities,e.favoriteSubDeviceIds?.has(i)??!1):null;if(!o&&!s)continue;const l=document.createElement("div");l.className="field-row";const d=document.createElement("span");if(d.className="field-label",d.textContent=r.name||i,d.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",l.appendChild(d),s&&l.appendChild(s),!o){t.appendChild(l);continue}const u=m[i]||{horizon:c,has_override:!1},h=u.has_override?u.horizon:c,p=document.createElement("select");p.dataset.subdevId=i;for(const t of Object.keys(a)){const e=document.createElement("option");e.value=t;const i=`horizon.${t}`,r=n(i);e.textContent=r!==i?r:t,t===h&&(e.selected=!0),p.appendChild(e)}if(p.addEventListener("change",()=>{this._debounce(`subdev-${e.configEntryId??""}-${i}`,500,()=>{const t={subdevice_id:i,horizon:p.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_subdevice_graph_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})})}),l.appendChild(p),u.has_override){const t=document.createElement("button");t.textContent="↺",t.title=n("sidepanel.reset_to_global"),Object.assign(t.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),t.addEventListener("click",()=>{const r={subdevice_id:i};e.configEntryId&&(r.config_entry_id=e.configEntryId),this._callDomainService("clear_subdevice_graph_horizon",r).then(()=>{p.value=c,t.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})}),l.appendChild(t)}t.appendChild(l)}t.children.length>1&&r.appendChild(t)}t.appendChild(r)}_buildPanelModeCircuitRow(t,e,i,r,o,s,l,c){const d=document.createElement("div");d.className="field-row";const u=document.createElement("span");if(u.className="field-label",u.textContent=e.name||t,u.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",d.appendChild(u),s&&l){const n=this._buildFavoriteHeart(e.entities,c?.has(t)??!1);n&&d.appendChild(n)}const h=i||{horizon:r,has_override:!1},p=h.has_override?h.horizon:r,f=document.createElement("select");f.dataset.uuid=t;for(const t of Object.keys(a)){const e=document.createElement("option");e.value=t;const i=`horizon.${t}`,r=n(i);e.textContent=r!==i?r:t,t===p&&(e.selected=!0),f.appendChild(e)}if(f.addEventListener("change",()=>{this._debounce(`circuit-${o??""}-${t}`,500,()=>{const e={circuit_id:t,horizon:f.value};o&&(e.config_entry_id=o),this._callDomainService("set_circuit_graph_horizon",e).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})})}),d.appendChild(f),h.has_override){const e=document.createElement("button");e.textContent="↺",e.title=n("sidepanel.reset_to_global"),Object.assign(e.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),e.addEventListener("click",()=>{const i={circuit_id:t};o&&(i.config_entry_id=o),this._callDomainService("clear_circuit_graph_horizon",i).then(()=>{f.value=r,e.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})}),d.appendChild(e)}return d}_renderFavoritesMode(t){const e=this._config,i=this._createHeader(n("sidepanel.graph_settings"),n("sidepanel.favorites_subtitle"));t.appendChild(i);const r=document.createElement("div");r.className="panel-body",r.appendChild(this._buildListColumnsSection());for(const t of e.perPanelSections)r.appendChild(this._buildFavoritesPanelSection(t));t.appendChild(r)}_buildFavoritesPanelSection(t){const e=document.createElement("div");e.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=t.panelName,e.appendChild(n);const i=t.graphSettings?.global_horizon??o,r=t.graphSettings?.circuits??{},a=function(t){const e=t.circuits??{};return Object.entries(e).map(([t,e])=>({uuid:t,circuit:e})).sort((t,e)=>(t.circuit.name||"").localeCompare(e.circuit.name||""))}(t.topology);for(const{uuid:n,circuit:o}of a){const a=this._buildPanelModeCircuitRow(n,o,r[n],i,t.configEntryId,!0,t.panelDeviceId,t.favoriteCircuitUuids);e.appendChild(a)}return e}_renderCircuitMode(t,e){const n=this._createHeader(e.name,this._circuitSubtitle(e));t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),this._renderRelaySection(i,e),e.showFavorites&&this._renderFavoriteSection(i,e),this._renderSheddingSection(i,e),this._placeControlNote(i),this._renderGraphHorizonSection(i,e),e.showMonitoring&&this._renderMonitoringSection(i,e)}_placeControlNote(t){t.querySelector('[data-role="controls-note"]')?.remove();const e=[...t.querySelectorAll('[data-role="relay-toggle"], [data-role="shedding-select"]')];e[0]?.closest(".section")?.insertAdjacentHTML("beforeend",_n(this._controlAccess));const n=t.querySelector('[data-role="controls-note"]');n&&(n.id=li);for(const t of e)n?t.setAttribute("aria-describedby",li):t.removeAttribute("aria-describedby")}refreshControlAccess(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i=this._controlAccess;i.mayOperate===t.mayOperate&&i.reason===t.reason||(this._controlAccess=t,this._updateLiveState(),this._placeControlNote(n))}_circuitSubtitle(t){const e=t.members.map(t=>t.circuit),n=[...new Set(e.flatMap(t=>t.voltage?[t.voltage]:[]))].sort((t,e)=>t-e);return[Me(e),e.length>1&&t.capacityA?i("sidepanel.capacity",{amps:String(t.capacityA)}):"",n.length>0?`${n.join("/")}V`:"",`Tabs [${Se(e).join(",")}]`].filter(Boolean).join(" · ")}_favoriteEntityId(t){return t?.current??t?.power??null}_buildSubDeviceFavoriteHeart(t,e){const n=Nn(t);return n?this._buildHeartButton(n,e):null}_buildListColumnsSection(){const t=document.createElement("div");t.className="section";const e=document.createElement("div");e.className="section-label",e.textContent=n("sidepanel.list_view_columns"),t.appendChild(e);const i=document.createElement("div");i.className="field-row";const r=document.createElement("span");r.className="field-label",r.textContent=n("sidepanel.columns"),i.appendChild(r);const o=Vt(),a=document.createElement("div");a.className="unit-toggle";for(const t of[1,2,3]){const e=document.createElement("button");e.type="button",e.className="unit-btn"+(t===o?" unit-active":""),e.dataset.columns=String(t),e.textContent=String(t),e.addEventListener("click",()=>{jt(t);for(const t of a.querySelectorAll(".unit-btn"))t.classList.toggle("unit-active",t===e);this.dispatchEvent(new CustomEvent("list-columns-changed",{detail:t,bubbles:!0,composed:!0}))}),a.appendChild(e)}return i.appendChild(a),t.appendChild(i),t}_buildFavoriteHeart(t,e){const n=this._favoriteEntityId(t);return n?this._buildHeartButton(n,e):(console.warn("SPAN Panel: circuit has no current/power sensor; favorite heart suppressed"),null)}_buildHeartButton(t,e){const i=document.createElement("button");i.type="button",i.className=e?"fav-heart active":"fav-heart",i.dataset.role="fav-heart",i.title=n("sidepanel.save_to_favorites"),i.setAttribute("role","switch"),i.setAttribute("aria-checked",String(e)),i.setAttribute("aria-label",n("sidepanel.save_to_favorites"));const r=document.createElement("span-icon");return r.setAttribute("icon",e?"mdi:heart":"mdi:heart-outline"),i.appendChild(r),i.addEventListener("click",e=>{e.stopPropagation(),this._toggleFavoriteEntity(i,r,t).catch(()=>{})}),i}async _toggleFavoriteEntity(t,e,i){if(!this._hass)return;const r=t.classList.contains("active"),o=!r;t.classList.toggle("active",o),e.setAttribute("icon",o?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(o));try{o?await async function(t,e){const n=await bn(t,"add_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(yn)),n?.favorites??{}}(this._hass,i):await async function(t,e){const n=await bn(t,"remove_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(yn)),n?.favorites??{}}(this._hass,i)}catch(i){throw t.classList.toggle("active",r),e.setAttribute("icon",r?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(r)),console.warn("SPAN Panel: favorite toggle failed",i),this.errorStore?.add({key:"service:favorites",level:"error",message:n("error.favorites_toggle_failed"),persistent:!1}),i}}_renderFavoriteSection(t,e){const n=this._favoriteEntityId(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_appendFavoriteHeartSection(t,e,i){const r=document.createElement("div");r.className="section",r.innerHTML=``;const o=document.createElement("div");o.className="field-row";const a=document.createElement("span");a.className="field-label",a.textContent=n("sidepanel.save_to_favorites"),o.appendChild(a),o.appendChild(this._buildHeartButton(e,i)),r.appendChild(o),t.appendChild(r)}_renderSubDeviceMode(t,e){const n=this._createHeader(e.name,e.deviceType);t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),e.showFavorites&&this._renderSubDeviceFavoriteSection(i,e),e.hasChart&&this._renderSubDeviceHorizonSection(i,e)}_renderSubDeviceFavoriteSection(t,e){const n=Nn(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_renderSubDeviceHorizonSection(t,e){const i=document.createElement("div");i.className="section";const r=document.createElement("div");r.className="section-label",r.textContent=n("sidepanel.graph_horizon"),i.appendChild(r);const s=e.graphHorizonInfo,l=!0===s?.has_override,c=s?.horizon||o,d=s?.globalHorizon||o,u=document.createElement("div");u.className="horizon-bar";const h=[{key:"global",label:n("sidepanel.global")}];for(const t of Object.keys(a))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of u.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===d)}};for(const{key:t,label:i}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=i,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===d),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const i={subdevice_id:e.subDeviceId};e.configEntryId&&(i.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_subdevice_graph_horizon",i).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_subdevice_graph_horizon",{...i,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})}))}),u.appendChild(r)}i.appendChild(u),t.appendChild(i)}_createHeader(t,e){const n=document.createElement("div");n.className="panel-header";const i=document.createElement("div"),r=document.createElement("div");if(r.className="title",r.textContent=t,i.appendChild(r),e){const t=document.createElement("div");t.className="subtitle",t.textContent=e,i.appendChild(t)}const o=document.createElement("button");return o.className="close-btn",o.innerHTML="✕",o.addEventListener("click",()=>this.close()),n.appendChild(i),n.appendChild(o),n}_renderRelaySection(t,e){if(!this._hass||"none"===ei(e,this._hass))return;const i=document.createElement("div");i.className="section",i.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=ai,o.textContent=n("sidepanel.breaker");const a=document.createElement("span-switch");a.dataset.role="relay-toggle",a.setAttribute("aria-labelledby",ai);const s=e.entities.switch;this._applyRelayToggle(a,e),a.addEventListener("change",()=>{const t=this._hass;t&&s&&"operable"===ei(e,t)&&pn(t,this._controlAccess).setRelay(s,a.checked).catch(n=>{mn(t,this.errorStore,n,"relay"),this._applyRelayToggle(a,e)})}),r.appendChild(o),r.appendChild(a),i.appendChild(r),t.appendChild(i)}_renderSheddingSection(t,e){if(!e.entities?.select)return;const i=document.createElement("div");i.className="section",i.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=si,o.textContent=n("sidepanel.priority_label");const a=document.createElement("select");a.dataset.role="shedding-select",a.setAttribute("aria-labelledby",si);const s=e.entities.select;for(const t of g){const e=f[t];if(!e)continue;const i=document.createElement("option");i.value=t,i.textContent=n(`shedding.select.${t}`)||e.label(),a.appendChild(i)}a.addEventListener("change",()=>{const t=this._hass;t&&pn(t,this._controlAccess).setPriority(s,a.value).catch(n=>{mn(t,this.errorStore,n,"priority"),this._applySheddingSelect(a,e)})}),r.appendChild(o),r.appendChild(a),i.appendChild(r),t.appendChild(i),this._applySheddingSelect(a,e)}get ratingsView(){const t=this._config;return!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!t.showMonitoring?null:{members:t.members??[],monitoringInfo:t.monitoringInfo,offered:!0===t.monitoringRatingOffered}}setPackageRatings(t,e){return qe(this._hass).setCircuitPackageRatings(this._ratingsPayload(t,{package_ratings_a:[...e]}))}clearPackageRatings(t){return qe(this._hass).clearCircuitPackageRatings(this._ratingsPayload(t,{}))}reportRatingsFailure(t){_e(this._hass,this.errorStore,t)}async useGlobalThresholds(){const t=this._config,e=this.shadowRoot;if(!t||!e||t.panelMode||t.subDeviceMode||t.favoritesMode)return!1;const n=e.querySelector('input[name="monitoring-mode"][value="global"]'),i=e.querySelector('input[name="monitoring-mode"][value="custom"]'),r=e.querySelector('[data-role="threshold-fields"]');n&&(n.checked=!0),r&&(r.style.display="none"),this._thresholdReads+=1;const o={circuit_id:t.entities?.power||t.uuid};t.configEntryId&&(o.config_entry_id=t.configEntryId);try{await qe(this._hass).clearCircuitThreshold(o)}catch(e){return Ue(this.errorStore,e,"monitoring update"),this._config===t&&(i&&(i.checked=!0),r&&(r.style.display="block")),!1}const a=this._config===t?t.monitoringGlobals??null:null;return this._monitoringChanged(t.uuid,{has_override:!1,continuous_threshold_pct:a?.continuous_threshold_pct,spike_threshold_pct:a?.spike_threshold_pct}),!0}async turnOffMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode)&&this._sendMonitoringEnabled(t,!1)}focusAfterRatingsEditor(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"]:checked')??t?.querySelector('input[name="monitoring-mode"]');e?.focus()}_ratingsPayload(t,e){const n={circuit_id:t,...e},i=this._config,r=!i||i.panelMode||i.subDeviceMode||i.favoritesMode?null:i.configEntryId;return r&&(n.config_entry_id=r),n}_monitoringChanged(t,e){const n=this._openCircuitConfig(t);n&&(this._config={...n,monitoringInfo:{...n.monitoringInfo??{},...e}},this._syncMonitoring())}_monitoringAnswered(t,e,n){const i=this._openCircuitConfig(t);i&&(this._config={...i,monitoringInfo:e,monitoringGlobals:n},this._monitoringStoredAs(t,e),!0!==e.has_override&&this._showGlobalChoice(),this._syncMonitoring())}_monitoringStoredAs(t,e){const n=this._storedMonitoring;e&&n?.uuid===t&&n.answered(Wt(e))}_showStoredMonitoring(t){if(!t||t!==this._storedMonitoring||!t.settled)return;const e=this.shadowRoot?.querySelector('[data-role="monitoring-toggle"]')?.hasAttribute("checked");e!==t.on&&this._showMonitoringEnabled(t.uuid,t.on)}_showGlobalChoice(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"][value="global"]'),n=t?.querySelector('[data-role="threshold-fields"]');e&&n&&!e.checked&&!this._limitFields.some(t=>t.dirty)&&(e.checked=!0,le(n)&&e.focus(),n.style.display="none")}_openCircuitConfig(t){const e=this._config;return!e||e.panelMode||e.subDeviceMode||e.favoritesMode||e.uuid!==t||!this.hasAttribute("open")?null:e}_syncMonitoring(){const t=this._config,e=this.shadowRoot?.querySelector('[data-role="judged-against"]');if(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!e)return;const n=this._judgedAgainstText(t.monitoringInfo);e.textContent!==n&&(e.textContent=n),this._ratingsEditor.sync(e),this._lockMonitoringIfReadOnly()}_renderGraphHorizonSection(t,e){const i=document.createElement("div");i.className="section",i.dataset.role="horizon-section";const r=document.createElement("div");r.className="section-label",r.textContent=n("sidepanel.graph_horizon"),i.appendChild(r);const s=e.graphHorizonInfo,l=!0===s?.has_override,c=s?.horizon||o,d=s?.globalHorizon||o,u=document.createElement("div");u.className="horizon-bar";const h=[{key:"global",label:n("sidepanel.global")}];for(const t of Object.keys(a))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of u.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===d)}};for(const{key:t,label:i}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=i,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===d),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const i={circuit_id:e.uuid};e.configEntryId&&(i.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_circuit_graph_horizon",i).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_circuit_graph_horizon",{...i,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})}))}),u.appendChild(r)}i.appendChild(u),t.appendChild(i)}_judgedAgainstText(t){return function(t){return t.amps?t.userSet?i("monitoringRating.judged_copied",{rating:String(t.amps),copied:Zt(t)}):i("sidepanel.judged_against",{rating:`${t.amps} A`}):i("sidepanel.judged_against",{rating:n("monitoringRating.none")})}(Yt(t))}_renderMonitoringSection(t,e){const i=document.createElement("div");i.className="section",i.dataset.role="monitoring-section";const r=document.createElement("div");r.className="monitoring-header";const o=document.createElement("div");o.className="section-label",o.textContent=n("sidepanel.monitoring"),o.style.margin="0";const a=document.createElement("span-switch");a.dataset.role="monitoring-toggle";const s=e.monitoringInfo,l=Wt(s);l&&a.setAttribute("checked",""),r.appendChild(o),r.appendChild(a),i.appendChild(r),Be(this._hass)||i.appendChild(Ze());const c=document.createElement("div");c.dataset.role="monitoring-details",c.style.display=l?"block":"none",i.appendChild(c);const d=!0===s?.has_override,u=document.createElement("div");u.className="field-label",u.dataset.role="judged-against",u.setAttribute("aria-live","polite"),u.style.marginBottom="8px",u.textContent=this._judgedAgainstText(s),c.appendChild(u),this._ratingsEditor.mount(u);const h=document.createElement("div");h.className="radio-group",h.innerHTML=`\n \n \n `,c.appendChild(h),this._limitFields=[];const p=document.createElement("div");p.dataset.role="threshold-fields",p.style.display=d?"block":"none";const f=s?.continuous_threshold_pct??80,g=s?.spike_threshold_pct??100,m=s?.window_duration_m??15,v=s?.cooldown_duration_m??15;p.appendChild(this._createLimitRow(n("sidepanel.continuous_pct"),"continuous",f,null,e)),p.appendChild(this._createLimitRow(n("sidepanel.spike_pct"),"spike",g,null,e)),p.appendChild(this._createLimitRow(n("sidepanel.window_duration"),"window-m",m,"m",e)),p.appendChild(this._createLimitRow(n("sidepanel.cooldown"),"cooldown-m",v,"m",e)),c.appendChild(p),a.addEventListener("change",()=>{const t=a.checked;this._showMonitoringEnabled(e.uuid,t),this._sendMonitoringEnabled(e,t)});const _=h.querySelectorAll('input[type="radio"]');for(const t of _)t.addEventListener("change",()=>{t.checked&&("custom"===t.value?p.style.display="block":this.useGlobalThresholds())});t.appendChild(i),this._lockMonitoringIfReadOnly()}_lockMonitoringIfReadOnly(){const t=this.shadowRoot?.querySelector('[data-role="monitoring-section"]');t&&!Be(this._hass)&&Ye(t)}async _sendMonitoringEnabled(t,e){const n={circuit_id:t.entities?.power||t.uuid,monitoring_enabled:e};t.configEntryId&&(n.config_entry_id=t.configEntryId);const i=async()=>{try{return await qe(this._hass).setCircuitThreshold(n),!0}catch(t){return Ue(this.errorStore,t,"monitoring update"),!1}},r=this._storedMonitoring;if(r?.uuid!==t.uuid)return i();const o=await r.send(e,i);return this._showStoredMonitoring(r),o}_showMonitoringEnabled(t,e){const n=this.shadowRoot;if(!this._openCircuitConfig(t)||!n)return;const i=n.querySelector('[data-role="monitoring-toggle"]');i?.toggleAttribute("checked",e);const r=n.querySelector('[data-role="monitoring-details"]');if(r){const t=!e&&le(r);r.style.display=e?"block":"none",t&&i?.focus()}this._monitoringChanged(t,{monitoring_enabled:e})}_createLimitRow(t,e,n,i,r){const o=oi[e],{min:a,max:s}=he[o],l=document.createElement("div");l.className="field-row limit-row";const c=document.createElement("span");c.className="field-label",c.id=`threshold-label-${e}`,c.textContent=t;const d=document.createElement("div"),u=document.createElement("input");if(u.type="number",u.setAttribute("aria-labelledby",c.id),u.min=String(a),u.max=String(s),u.step="1",u.value=String(n),u.dataset.role=`threshold-${e}`,u.setAttribute("aria-describedby",`threshold-feedback-${e}`),d.appendChild(u),i){const t=document.createElement("span");t.textContent=i,d.appendChild(t)}const h=document.createElement("div");h.className="field-label rating-feedback limit-feedback",h.id=`threshold-feedback-${e}`,h.dataset.role=`threshold-feedback-${e}`,h.setAttribute("aria-live","polite");const p=me(u,o,{report:t=>{h.textContent=t??""},save:t=>{const e={circuit_id:r.entities?.power||r.uuid,[o]:t};r.configEntryId&&(e.config_entry_id=r.configEntryId),this._saveThresholds(r,e)}});return this._limitFields.push(p),l.append(c,d,h),l}_saveThresholds(t,e){qe(this._hass).setCircuitThreshold(e).then(()=>this._readThresholds(t,e),t=>Ue(this.errorStore,t,"monitoring update"))}_updateLiveState(){if(!this._config||this._config.panelMode)return;const t=this._config;if(!t.subDeviceMode&&!t.favoritesMode){if(t.entities?.switch){const e=this.shadowRoot?.querySelector('[data-role="relay-toggle"]');e&&this._applyRelayToggle(e,t)}if(t.entities?.select){const e=this.shadowRoot?.querySelector('[data-role="shedding-select"]');e&&this._applySheddingSelect(e,t)}}}_applyRelayToggle(t,e){if(!this._hass)return;const n=this._controlAccess;t.disabled=!n.mayOperate||"operable"!==ei(e,this._hass),vn(t,n),ti(e,this._hass)?t.setAttribute("checked",""):t.removeAttribute("checked")}_applySheddingSelect(t,e){if(!this._hass)return;const n=this._controlAccess,i=ri(e,this._hass);g.includes(i)?t.value=i:t.selectedIndex=-1,t.disabled=!n.mayOperate||!function(t,e){const n=ii(t,e);return void 0!==n&&Zn.has(n)}(e,this._hass),vn(t,n)}async _readThresholds(t,e){const n=++this._thresholdReads;let i=null;try{i=await this._readMonitoringStatus(t.configEntryId??null)}catch(t){console.warn("SPAN Panel: monitoring status read failed",t)}if(n!==this._thresholdReads)return;const r=Oe(i,t);if(r)return void this._monitoringAnswered(t.uuid,r,i?.global_settings??null);const o={has_override:!0};"number"==typeof e.continuous_threshold_pct&&(o.continuous_threshold_pct=e.continuous_threshold_pct),"number"==typeof e.spike_threshold_pct&&(o.spike_threshold_pct=e.spike_threshold_pct),this._monitoringChanged(t.uuid,o)}async _readMonitoringStatus(t){if(!this._hass)return null;const e=await this._hass.callWS({type:"call_service",domain:s,service:"get_monitoring_status",service_data:t?{config_entry_id:t}:{},return_response:!0});return Le(e?.response)}_callDomainService(t,e){return this._hass?this._hass.callWS({type:"call_service",domain:s,service:t,service_data:e}):Promise.resolve()}_debounce(t,e,n){this._debounceTimers[t]&&clearTimeout(this._debounceTimers[t]),this._debounceTimers[t]=setTimeout(()=>{delete this._debounceTimers[t],n()},e)}}try{customElements.get("span-side-panel")||customElements.define("span-side-panel",di)}catch{}class ui extends At{constructor(){super(...arguments),this._store=null,this._unsub=null,this._errors=[]}set store(t){if(this._store===t)return;this._unsub?.(),this._unsub=null,this._store=t,this._errors=t.active;const e=t;this._unsub=t.subscribe(()=>{this._errors=e.active})}connectedCallback(){if(super.connectedCallback(),this._store&&!this._unsub){const t=this._store;this._errors=t.active,this._unsub=t.subscribe(()=>{this._errors=t.active})}}disconnectedCallback(){super.disconnectedCallback(),this._unsub?.(),this._unsub=null}render(){return 0===this._errors.length?ht:ct`${this._errors.map(t=>ct` @@ -333,7 +333,7 @@ var Lc={},Ec={};var Rc,Nc=function(){function t(t,e,n){var i=this;this._sleepAft > - `}_onPanelChange(t){const e=t.target;this._selectedPanelId=e.value,localStorage.setItem("span_panel_selected",e.value),this._isFavoritesView&&SD(this._activeTab)&&(this._activeTab="activity"),this._unsubscribeAreaTab(),this._areaTopology=null}get _isFavoritesView(){return this._selectedPanelId===wD}_onTabClick(t){const e=t.target.closest(".shared-tab");if(!e)return;const n=e.dataset.tab;n&&n!==this._activeTab&&(this._activeTab=n,this._isFavoritesView&&!SD(n)&&(this._favoritesViewState.activeTab=n,_D(this._favoritesViewState)))}_onTabContentClick(t){const e=t.target.closest(".unit-btn");if(e){const t=e.dataset.unit;if(!t||t===this._chartMetric)return;return this._chartMetric=t,void localStorage.setItem("span_panel_metric",t)}}_onSidePanelClosed(){if("dashboard"===this._activeTab){const t=this._dashboardTab._ctrl;t.monitoringCache.invalidate(),t.graphSettingsCache.invalidate()}this._listDashCtrl.monitoringMultiCache.invalidate(),this._pendingTabRender&&(this._pendingTabRender=!1,this._scheduleTabRender())}_onUnitChanged(t){const e=t.detail;e&&e!==this._chartMetric&&(this._chartMetric=e,localStorage.setItem("span_panel_metric",e))}_onListColumnsChanged(t){const e=t.detail;"number"!=typeof e||1!==e&&2!==e&&3!==e||e===this._listColumns||(this._listColumns=e,jt(e))}_onGraphSettingsChanged(){if("dashboard"===this._activeTab){const t=this._root.getElementById("tab-content");if(t){this._dashboardTab._ctrl.onGraphSettingsChanged(t)}}}_onNavigateTab(t){const e=t.detail;e&&(this._activeTab=e)}_onFavoritesViewStateChangedEvent(t){if(!this._isFavoritesView)return;const e=t.detail;if(!e)return;const n=this._favoritesViewState;n.activeTab=e.view;const i=this._listDashCtrl.topology,r=i?.circuits;r&&Object.keys(r).length>0?n.expanded[e.view]=e.expanded.filter(t=>t in r):n.expanded[e.view]=e.expanded,n.searchQuery=e.searchQuery,this._persistFavoritesViewStateTimer&&clearTimeout(this._persistFavoritesViewStateTimer),this._persistFavoritesViewStateTimer=setTimeout(()=>{this._persistFavoritesViewStateTimer=null,_D(n)},250)}_subscribeDeviceRegistry(){!this._deviceRegistryUnsub&&this.hass?.connection&&(this._deviceRegistryUnsub=this.hass.connection.subscribeEvents(t=>this._onDeviceRegistryUpdated(t),"device_registry_updated"))}_onDeviceRegistryUpdated(t){this._refreshPanels();const e=function(t){if("object"!=typeof t||null===t||!("data"in t))return null;const{data:e}=t;if("object"!=typeof e||null===e)return null;if(!("action"in e)||"update"!==e.action)return null;if(!("device_id"in e)||"string"!=typeof e.device_id)return null;if(!("changes"in e))return null;const{changes:n}=e;return"object"!=typeof n||null===n?null:sD.some(t=>t in n)?e.device_id:null}(t);if(e){for(const[t,n]of this._renderedTopologies)lD(n,e)&&this._renamedPanelIds.add(t);this._renamedPanelIds.size>0&&this._renameRefresh()}}_unsubscribeDeviceRegistry(){this._deviceRegistryUnsub&&(this._deviceRegistryUnsub.then(t=>t()),this._deviceRegistryUnsub=null)}_subscribeEntryReloads(){!this._reloadSub&&this.hass?.connection&&(this._reloadSub=async function(t,e,n,{initialIsReseed:i}){const r=t.connection;if(!r)return async()=>{};const o=new Map;let a=!1;return r.subscribeMessage(t=>{if(t.every(t=>null===t.type)){const r=a||i;a=!0,o.clear();for(const{entry:i}of t)e(i)&&(o.set(i.entry_id,i.state),r&&i.state===cD&&n(i.entry_id));return}for(const{type:i,entry:r}of t){if(!e(r))continue;if("removed"===i){o.delete(r.entry_id);continue}const t=o.get(r.entry_id);o.set(r.entry_id,r.state),"updated"===i&&r.state===cD&&t!==cD&&n(r.entry_id)}},{type:"config_entries/subscribe",type_filter:["device"]})}(this.hass,t=>t.domain===s,t=>this._onEntryLoaded(t),{initialIsReseed:this._discovered}).catch(t=>(console.warn("SPAN Panel: config entry subscription failed",t),async()=>{})))}_unsubscribeEntryReloads(){const t=this._reloadSub;this._reloadSub=null,t?.then(t=>t())}_syncRatingSubscriptions(){const t=this.hass;if(!this.isConnected||!t?.connection)return;if(!function(t){return!0===t?.user?.is_admin}(t))return void this._unsubscribeRatingChanges();const e=new Set;for(const t of this._panels)t.id!==wD&&t.config_entry_id&&e.add(t.config_entry_id);for(const[t,n]of this._ratingSubs)e.has(t)||(this._ratingSubs.delete(t),n.then(t=>t()));for(const n of e)this._ratingSubs.has(n)||this._ratingSubs.set(n,hD(t,n,t=>this._onRatingChanged(n,t)).catch(t=>(console.warn("SPAN Panel: monitoring rating subscription failed",t),()=>{})))}_unsubscribeRatingChanges(){const t=[...this._ratingSubs.values()];this._ratingSubs.clear();for(const e of t)e.then(t=>t())}_onRatingChanged(t,e){const n=this._panels.find(e=>e.id!==wD&&e.config_entry_id===t);if(!n)return;this._dashboardTab.invalidateMonitoring(),this._listDashCtrl.monitoringCache.invalidate(),this._listDashCtrl.monitoringMultiCache.invalidate();if(!(this._isFavoritesView?this._renderedTopologies.has(n.id):n.id===this._selectedPanelId)||!this._isFavoritesView&&"adopted"===this._activeTab)return;const i=this._ratingChangedIds.has(n.id)?this._ratingChangedIds.get(n.id)??null:new Set;this._ratingChangedIds.set(n.id,function(t,e){return null===t||null===e?null:new Set([...t,...e])}(i,e));let r=this._ratingRefreshes.get(n.id);if(!r){const e=n.id;r=yD(()=>{const n=this._takeRatingChangedIds(e);return this._renderIfRestructured(e,e=>this._refreshOpenSidePanel(t,e,n))}),this._ratingRefreshes.set(e,r)}r()}_takeRatingChangedIds(t){const e=this._ratingChangedIds.has(t)?this._ratingChangedIds.get(t)??null:null;return this._ratingChangedIds.delete(t),e}_refreshOpenSidePanelAccess(t,e){const n=this._root.getElementById("tab-content"),i=this._panels.find(e=>e.id===t)?.config_entry_id;n&&i&&("dashboard"!==this._activeTab||this._isFavoritesView?this._listDashCtrl.refreshCircuitControlAccess(n,i,e):this._dashboardTab.refreshSidePanelControlAccess(i,e))}async _refreshOpenSidePanel(t,e,n){const i=this._root.getElementById("tab-content");i&&("dashboard"!==this._activeTab||this._isFavoritesView?await this._listDashCtrl.refreshCircuitSidePanel(i,t,e,n):await this._dashboardTab.refreshSidePanel(t,e,n))}_onEntryLoaded(t){const e=this._panels.find(e=>e.id!==wD&&e.config_entry_id===t);this._isFavoritesView||e&&e.id===this._selectedPanelId?e?(!this._isFavoritesView||this._renderedTopologies.has(e.id)||Sn(this._favorites,e.id))&&(this._isFavoritesView||"adopted"!==this._activeTab?this._renderIfRestructured(e.id):this._adoptedTab.refresh()):this._requestTabRender():this._requestPanelsRefresh()}async _renderIfRestructured(t,e){const n=this._renderedTopologies.get(t);if(!n||!this.hass)return void this._requestTabRender();let i;try{({topology:i}=await xi(this.hass,t,null))}catch(t){return void console.warn("SPAN Panel: topology refresh failed; keeping the current view:",Jt(t))}var r,o;this._renderedTopologies.get(t)===n&&(i&&this._refreshOpenSidePanelAccess(t,i),i&&e&&(await e(i),this._renderedTopologies.get(t)!==n)||i&&(r=i,null!==(o=n)&&IP(fD(r),fD(o)))||this._requestTabRender())}async _fetchBaselineTopology(){if(!this.hass||!this._selectedPanelId)return null;try{return(await xi(this.hass,this._selectedPanelId,null)).topology}catch(t){return console.warn("SPAN Panel: no topology baseline for this view:",Jt(t)),null}}_recordRenderedTopology(t){t&&this._selectedPanelId&&this._renderedTopologies.set(this._selectedPanelId,t)}_reapplyPanelStatusWatch(){if(this._isFavoritesView)return this._errorStore.watchPanelStatuses(this._favoritesWatchEntries),void(this.hass&&this._errorStore.updateHass(this.hass));this._updatePanelStatusWatch()}_subscribeAreaTab(){!this._areaSub&&this.hass&&(this._areaSub=async function(t,e,i,r){const o=t.connection;if(!o)return()=>{};const a=async()=>{const o=e();if(o)try{const e=new Map;for(const[t,n]of Object.entries(o.circuits))e.set(t,n.area);await yi(t,o);for(const[t,n]of Object.entries(o.circuits))if(n.area!==e.get(t))return void i()}catch(t){console.warn("[span-panel] area registry update failed:",t),r?.add({key:"fetch:areas",level:"warning",message:n("error.areas_failed"),persistent:!1})}},s=await Promise.all(_i.map(t=>o.subscribeEvents(a,t)));return()=>{for(const t of s)t()}}(this.hass,()=>this._areaTopology,()=>{"area"===this._activeTab&&this._scheduleTabRender()},this._errorStore).catch(t=>(console.warn("SPAN Panel: area subscription failed",t),this._errorStore.add({key:"subscribe:area",level:"warning",message:n("error.areas_failed"),persistent:!1}),()=>{})))}_unsubscribeAreaTab(){const t=this._areaSub;this._areaSub=null,t?.then(t=>t())}async _refreshPanels(){if(!this.hass||!this._discovered)return;const t=await dD(this.hass),e=this._panels.filter(t=>t.id!==wD),n=new Map(e.map(t=>[t.id,t])),i=new Set(t.map(t=>t.id)),r=n.size!==i.size||[...n.keys()].some(t=>!i.has(t)),o=!r&&t.some(t=>{const e=n.get(t.id);return!!e&&(e.name!==t.name||e.name_by_user!==t.name_by_user)});if((r||o)&&(this._panels=this._buildPanelList(t,this._favorites),!this._panels.some(t=>t.id===this._selectedPanelId)&&this._panels.length>0)){const e=t[0];e&&(this._selectedPanelId=e.id,localStorage.setItem("span_panel_selected",this._selectedPanelId))}}async _updatePanelStatusWatch(){if(!this.hass||!this._selectedPanelId)return;if(this._selectedPanelId===wD)return;if(this._watchedPanelId===this._selectedPanelId)return;const t=this._selectedPanelId;this._watchedPanelId=t;try{const e=new De(this._errorStore),n=await xi(this.hass,t,e);if(this._selectedPanelId!==t)return;const i=n.topology?.panel_entities?.panel_status;i&&(this._errorStore.watchPanelStatus(i),this._errorStore.updateHass(this.hass))}catch(e){console.warn("SPAN Panel: unable to fetch topology for panel status watching",e),this._watchedPanelId===t&&(this._watchedPanelId=null)}}async _discoverPanels(){if(!this._discovering&&this.hass){this._discovering=!0;try{let t;try{t=await dD(this.hass,new De(this._errorStore))}catch(t){return console.error("SPAN Panel: device discovery failed",t),void this._errorStore.add({key:"discovery-failed",level:"error",message:n("error.discovery_failed"),persistent:!0,retryFn:()=>{this._errorStore.remove("discovery-failed"),this._discoverPanels()}})}this._favorites=await this._loadFavorites(),this._panels=this._buildPanelList(t,this._favorites),this._favoritesViewState=function(){try{const t=localStorage.getItem(vD);if(!t)return{expanded:{activity:[],area:[]}};const e=JSON.parse(t);if(!e||"object"!=typeof e)return{expanded:{activity:[],area:[]}};const n=e.expanded??{activity:[],area:[]};return{activeTab:e.activeTab,expanded:{activity:Array.isArray(n.activity)?n.activity:[],area:Array.isArray(n.area)?n.area:[]},searchQuery:"string"==typeof e.searchQuery?e.searchQuery:void 0}}catch{return{expanded:{activity:[],area:[]}}}}(),this._discovered=!0;const e=localStorage.getItem("span_panel_selected");if(e&&this._panels.some(t=>t.id===e)?this._selectedPanelId=e:t.length>0&&(this._selectedPanelId=t[0].id),this._selectedPanelId===wD){const t=this._favoritesViewState.activeTab;"activity"===t||"area"===t||"monitoring"===t?this._activeTab=t:SD(this._activeTab)&&(this._activeTab="activity")}this._chartMetric=localStorage.getItem("span_panel_metric")||"power"}finally{this._discovering=!1}}}_buildPanelList(t,e){if(!wn(e))return t;return[{id:wD,name:n("panel.favorites"),model:"__favorites__"},...t]}async _loadFavorites(){return this.hass?this._favCache.fetch(this.hass):{}}async _refreshFavorites(){const t=++this._refreshSeq;this._favCache.invalidate();const e=await this._loadFavorites();if(t!==this._refreshSeq)return;const n=this._selectedPanelId===wD;this._favorites=e;const i=this._panels.filter(t=>t.id!==wD);if(this._panels=this._buildPanelList(i,e),n&&!wn(e)){!function(){try{localStorage.removeItem(vD)}catch{}}(),this._favoritesViewState={expanded:{activity:[],area:[]}};const t=i[0];t?(this._selectedPanelId=t.id,localStorage.setItem("span_panel_selected",t.id)):this._selectedPanelId=null}else this._isFavoritesView?this._scheduleTabRender():this._applyPanelFavorites()}_buildTabList(){const t=[];return this._isFavoritesView||t.push({id:"dashboard",label:n("tab.by_panel"),icon:"mdi:view-dashboard"}),t.push({id:"activity",label:n("tab.by_activity"),icon:"mdi:sort-descending"},{id:"area",label:n("tab.by_area"),icon:"mdi:home-group"},{id:"monitoring",label:n("tab.monitoring"),icon:"mdi:monitor-eye"}),this._isFavoritesView||!0!==this.hass?.user?.is_admin||t.push({id:"adopted",label:n("tab.adopted"),icon:"mdi:tune"}),t}_buildFavoritesSummaryHTML(t){return function(t,e){return`\n
\n \n ${Di(e,{note:!1})}\n
\n ${Li()}\n
\n \n \n
\n
\n
\n `}("current"===(this._chartMetric||"power"),an(t))}_buildFavoritesPanelStatsGridHTML(t,e,n){if(0===t.length)return"";const i=cn(e,ln);return`
${t.map(t=>`\n
\n
${Ft(t.panelName||t.topology.device_name||"")}
\n ${(t=>{const e=i.get(t);return e?_n(e):""})(t.panelDeviceId)}\n ${Ei(t.topology,n,t.panelDeviceId)}\n
\n `).join("")}
`}_updateFavoritesPanelStats(t,e){if(this.hass&&0!==this._favoritesPanelStats.length)for(const n of this._favoritesPanelStats){const i=t.querySelector(`.panel-stats[data-stats-panel-id="${Ui(n.panelDeviceId)}"]`);i&&wI(i,this.hass,n.topology,e,null)}}_buildDashboardConfig(){return{chart_metric:this._chartMetric,history_minutes:5,show_panel:!0,show_battery:!0,show_evse:!0,show_solar:!0}}async _scheduleTabRender(){await this.updateComplete,this._sidePanelOpen()?this._pendingTabRender=!0:await this._tabRenderScheduler()}_sidePanelOpen(){const t=this.shadowRoot?.getElementById("tab-content");return!!t?.querySelector("span-side-panel[open]")}async _renderTab(){const t=this._beginRender(),e=this._root.getElementById("tab-content"),n=this._renderedView,i={tab:this._activeTab,panelId:this._selectedPanelId},r=null!==e&&null!==n&&n.tab===i.tab&&n.panelId===i.panelId;if(this._dashboardTab.stop(),r||(this._monitoringTab.stop(),this._dropFavoritesMonitoring()),this._adoptedTab.stop(),this._listCtrl.stop(),this._listDashCtrl.stopIntervals(),this._favoritesPanelStats=[],this._renderedTopologies.clear(),e)if(this._renderedView=i,this._isFavoritesView)await this._renderFavoritesTab(e,t,r);else switch(this._listDashCtrl.clearFavoriteRefs(),this._listCtrl.setViewName(null),this._applyPanelFavorites(),this._activeTab){case"dashboard":{e.innerHTML="";const n=this._buildDashboardConfig(),i=this._panels.find(t=>t.id===this._selectedPanelId),r=i?.config_entry_id??null,o=await this._dashboardTab.render(e,this.hass,this._selectedPanelId??"",n,r);t()||this._recordRenderedTopology(o);break}case"activity":{e.innerHTML="";const n=this._panels.find(t=>t.id===this._selectedPanelId),i=n?.config_entry_id??null;try{const n=new De(this._errorStore),r=await xi(this.hass,this._selectedPanelId??void 0,n);if(t())return;const o=this._buildDashboardConfig();if(this._listDashCtrl.init(r.topology,o,this.hass,i),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.monitoringCache.fetch(this.hass,i),t())return;if(await this._listDashCtrl.fetchAndBuildHorizonMaps(),t())return;const a=r.topology?Ri(r.topology,o):"";if(this._listCtrl.setColumns(this._listColumns),this._listCtrl.renderActivityView(e,this.hass,r.topology,o,this._listDashCtrl.monitoringCache.status,a),await this._listDashCtrl.loadHistory(),t())return;this._listDashCtrl.updateDOM(e),this._listDashCtrl.startIntervals(e),this._recordRenderedTopology(r.topology)}catch(n){if(t())return;const i=document.createElement("p");i.style.color="var(--error-color)",i.textContent=Jt(n),e.appendChild(i)}break}case"area":{e.innerHTML="";const n=this._panels.find(t=>t.id===this._selectedPanelId),i=n?.config_entry_id??null;try{const n=new De(this._errorStore),r=await xi(this.hass,this._selectedPanelId??void 0,n);if(t())return;const o=this._buildDashboardConfig();if(this._listDashCtrl.init(r.topology,o,this.hass,i),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.monitoringCache.fetch(this.hass,i),t())return;if(await this._listDashCtrl.fetchAndBuildHorizonMaps(),t())return;const a=r.topology?Ri(r.topology,o):"";if(this._listCtrl.setColumns(this._listColumns),this._listCtrl.renderAreaView(e,this.hass,r.topology,o,this._listDashCtrl.monitoringCache.status,a),await this._listDashCtrl.loadHistory(),t())return;this._listDashCtrl.updateDOM(e),this._listDashCtrl.startIntervals(e),this._recordRenderedTopology(r.topology),this._areaTopology=r.topology,this.isConnected&&this._subscribeAreaTab()}catch(t){const n=document.createElement("p");n.style.color="var(--error-color)",n.textContent=Jt(t),e.appendChild(n)}break}case"monitoring":{r||(e.innerHTML="");const n=this._panels.find(t=>t.id===this._selectedPanelId),i=n?.config_entry_id??null,o=this._fetchBaselineTopology(),[,a]=await Promise.all([this._monitoringTab.render(e,this.hass,i??void 0,o),o]);t()||this._recordRenderedTopology(a);break}case"adopted":e.innerHTML="",await this._adoptedTab.render(e,this.hass,this._selectedPanelId??"")}}async _renderFavoritesTab(t,e,i){const r=i?this._shownFavoritesMonitoring(t):null;if(r||(this._dropFavoritesMonitoring(),t.innerHTML=""),!this.hass)return;const o=this._panels.filter(t=>t.id!==wD),a=await this._favCtrl.build(this.hass,this._favorites,o,this._errorStore);if(e())return;for(const t of a.perPanelStats)this._renderedTopologies.set(t.panelDeviceId,t.topology);const s=a.perPanelStats.map(t=>{const e=t.topology.panel_entities?.panel_status;return"string"==typeof e?{entityId:e,panelName:t.panelName}:null}).filter(t=>null!==t);this._favoritesWatchEntries=s,this._errorStore.watchPanelStatuses(s),this._errorStore.updateHass(this.hass);const l=new Map;for(const t of a.perPanelStats){const e=o.find(e=>e.id===t.panelDeviceId);l.set(t.panelDeviceId,{panelName:t.panelName,topology:t.topology,configEntryId:e?.config_entry_id??null})}this._listDashCtrl.setFavoritesPerPanelInfo(l);const c=a.topology,d=a.entryIds[0]??null,u=Object.keys(c.circuits).length>0,h=Object.keys(c.sub_devices??{}).length>0;if(!u&&!h){this._dropFavoritesMonitoring(),t.innerHTML="";const e=document.createElement("p");return e.style.color="var(--secondary-text-color)",e.style.padding="24px",e.textContent=n("list.no_results"),void t.appendChild(e)}if(this._listDashCtrl.setFavoriteRefs(c._favoriteRefs),this._listDashCtrl.setPanelFavorites(null),"monitoring"===this._activeTab){this._listCtrl.setViewName(null);const e=new Map;for(const t of l.values())t.configEntryId&&e.set(t.configEntryId,t.topology);return void await this._renderFavoritesMonitoring(t,a.entryIds,o,r,e)}const p=this._activeTab,f=new Set(Object.keys(c.circuits)),g=this._favoritesViewState.expanded[p].filter(t=>f.has(t));this._listCtrl.setViewName(p),this._listCtrl.setInitialExpansion(g),this._listCtrl.setInitialSearchQuery(this._favoritesViewState.searchQuery??""),this._listCtrl.setColumns(this._listColumns);const m=this._buildDashboardConfig();if(this._listDashCtrl.init(c,m,this.hass,d),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.fetchAndBuildHorizonMaps(),e())return;const v=await this._listDashCtrl.fetchMergedMonitoringStatus(a.entryIds);if(!e()){this._favoritesPanelStats=a.perPanelStats;try{if(await this._listDashCtrl.loadHistory(),e())return;const n=this._buildFavoritesSummaryHTML(c),i=this._buildFavoritesPanelStatsGridHTML(a.perPanelStats,c,m),r=n+i+(h?`
\n
${Ki(c,this.hass,m,{showFavorites:this._listDashCtrl.showFavorites})}
\n
`:"");"activity"===p?this._listCtrl.renderActivityView(t,this.hass,c,m,v,r):this._listCtrl.renderAreaView(t,this.hass,c,m,v,r),this._updateFavoritesPanelStats(t,m),this._listDashCtrl.setupResizeObserver(t,t),this._listDashCtrl.startIntervals(t,()=>{this._updateFavoritesPanelStats(t,m)})}catch(n){if(e())return;const i=document.createElement("p");i.style.color="var(--error-color)",i.textContent=Jt(n),t.appendChild(i)}}}async _renderFavoritesMonitoring(t,e,n,i,r){const o=this.hass;if(!o)return;const a=i??this._newFavoritesMonitoringStack(t);this._favoritesMonitoring=a;const s=new Map;for(const t of n){const e=t.config_entry_id;e&&s.set(e,t)}for(const[t,n]of a.blocks)e.includes(t)||(n.tab.stop(),n.block.remove(),a.blocks.delete(t));const l=this._detaches;for(const[t,n]of e.entries()){if(!this.isConnected)break;if(this._favoritesMonitoring!==a)return;const e=s.get(n),i=e?.name_by_user??e?.name??n,l=a.blocks.get(n)??this._newFavoritesMonitoringBlock();a.blocks.set(n,l),l.heading.textContent!==i&&(l.heading.textContent=i);const c=a.wrapper.children.item(t);c!==l.block&&a.wrapper.insertBefore(l.block,c);try{await l.tab.render(l.body,o,n,r.get(n)??null)}catch(t){console.warn("SPAN Panel: favorites monitoring render failed",n,t);const e=document.createElement("p");e.style.color="var(--error-color)",e.textContent=Jt(t),l.body.appendChild(e)}}this.isConnected&&this._detaches===l||this._renderWhenAttached()}_renderWhenAttached(){this.isConnected?this._requestTabRender():this._renderOnAttach=!0}_newFavoritesMonitoringStack(t){const e=document.createElement("div");return e.className="favorites-monitoring-stack",t.appendChild(e),{wrapper:e,blocks:new Map}}_newFavoritesMonitoringBlock(){const t=document.createElement("div");t.className="favorites-monitoring-block",t.style.marginBottom="24px";const e=document.createElement("h2");e.style.margin="8px 0 12px",e.style.fontSize="1em",t.appendChild(e);const n=document.createElement("div");t.appendChild(n);const i=new TP;return i.errorStore=this._errorStore,{tab:i,block:t,heading:e,body:n}}_shownFavoritesMonitoring(t){const e=this._favoritesMonitoring;return null!==e&&e.wrapper.parentElement===t?e:null}_stopFavoritesMonitoring(){for(const{tab:t}of this._favoritesMonitoring?.blocks.values()??[])t.stop()}_dropFavoritesMonitoring(){this._stopFavoritesMonitoring(),this._favoritesMonitoring=null}_applyPanelFavorites(){if(!this._selectedPanelId||this._isFavoritesView)return this._listDashCtrl.setPanelFavorites(null),void this._dashboardTab.setPanelFavorites(null);const t=this._favorites[this._selectedPanelId],e={panelDeviceId:this._selectedPanelId,circuitUuids:new Set(t?.circuits??[]),subDeviceIds:new Set(t?.sub_devices??[])};this._listDashCtrl.setPanelFavorites(e),this._dashboardTab.setPanelFavorites(e)}};CD._shellStyles=k` + `}_onPanelChange(t){const e=t.target;this._selectedPanelId=e.value,localStorage.setItem("span_panel_selected",e.value),this._isFavoritesView&&SD(this._activeTab)&&(this._activeTab="activity"),this._unsubscribeAreaTab(),this._areaTopology=null}get _isFavoritesView(){return this._selectedPanelId===wD}_onTabClick(t){const e=t.target.closest(".shared-tab");if(!e)return;const n=e.dataset.tab;n&&n!==this._activeTab&&(this._activeTab=n,this._isFavoritesView&&!SD(n)&&(this._favoritesViewState.activeTab=n,_D(this._favoritesViewState)))}_onTabContentClick(t){const e=t.target.closest(".unit-btn");if(e){const t=e.dataset.unit;if(!t||t===this._chartMetric)return;return this._chartMetric=t,void localStorage.setItem("span_panel_metric",t)}}_onSidePanelClosed(){if("dashboard"===this._activeTab){const t=this._dashboardTab._ctrl;t.monitoringCache.invalidate(),t.graphSettingsCache.invalidate()}this._listDashCtrl.monitoringMultiCache.invalidate(),this._pendingTabRender&&(this._pendingTabRender=!1,this._scheduleTabRender())}_onUnitChanged(t){const e=t.detail;e&&e!==this._chartMetric&&(this._chartMetric=e,localStorage.setItem("span_panel_metric",e))}_onListColumnsChanged(t){const e=t.detail;"number"!=typeof e||1!==e&&2!==e&&3!==e||e===this._listColumns||(this._listColumns=e,jt(e))}_onGraphSettingsChanged(){if("dashboard"===this._activeTab){const t=this._root.getElementById("tab-content");if(t){this._dashboardTab._ctrl.onGraphSettingsChanged(t)}}}_onNavigateTab(t){const e=t.detail;e&&(this._activeTab=e)}_onFavoritesViewStateChangedEvent(t){if(!this._isFavoritesView)return;const e=t.detail;if(!e)return;const n=this._favoritesViewState;n.activeTab=e.view;const i=this._listDashCtrl.topology,r=i?.circuits;r&&Object.keys(r).length>0?n.expanded[e.view]=e.expanded.filter(t=>t in r):n.expanded[e.view]=e.expanded,n.searchQuery=e.searchQuery,this._persistFavoritesViewStateTimer&&clearTimeout(this._persistFavoritesViewStateTimer),this._persistFavoritesViewStateTimer=setTimeout(()=>{this._persistFavoritesViewStateTimer=null,_D(n)},250)}_subscribeDeviceRegistry(){!this._deviceRegistryUnsub&&this.hass?.connection&&(this._deviceRegistryUnsub=this.hass.connection.subscribeEvents(t=>this._onDeviceRegistryUpdated(t),"device_registry_updated"))}_onDeviceRegistryUpdated(t){this._refreshPanels();const e=function(t){if("object"!=typeof t||null===t||!("data"in t))return null;const{data:e}=t;if("object"!=typeof e||null===e)return null;if(!("action"in e)||"update"!==e.action)return null;if(!("device_id"in e)||"string"!=typeof e.device_id)return null;if(!("changes"in e))return null;const{changes:n}=e;return"object"!=typeof n||null===n?null:lD.some(t=>t in n)?e.device_id:null}(t);if(e){for(const[t,n]of this._renderedTopologies)cD(n,e)&&this._renamedPanelIds.add(t);this._renamedPanelIds.size>0&&this._renameRefresh()}}_unsubscribeDeviceRegistry(){this._deviceRegistryUnsub&&(this._deviceRegistryUnsub.then(t=>t()),this._deviceRegistryUnsub=null)}_subscribeEntryReloads(){!this._reloadSub&&this.hass?.connection&&(this._reloadSub=async function(t,e,n,{initialIsReseed:i}){const r=t.connection;if(!r)return async()=>{};const o=new Map;let a=!1;return r.subscribeMessage(t=>{if(t.every(t=>null===t.type)){const r=a||i;a=!0,o.clear();for(const{entry:i}of t)e(i)&&(o.set(i.entry_id,i.state),r&&i.state===bi&&n(i.entry_id));return}for(const{type:i,entry:r}of t){if(!e(r))continue;if("removed"===i){o.delete(r.entry_id);continue}const t=o.get(r.entry_id);o.set(r.entry_id,r.state),"updated"===i&&r.state===bi&&t!==bi&&n(r.entry_id)}},{type:"config_entries/subscribe",type_filter:["device"]})}(this.hass,t=>t.domain===s,t=>this._onEntryLoaded(t),{initialIsReseed:this._discovered}).catch(t=>(console.warn("SPAN Panel: config entry subscription failed",t),async()=>{})))}_unsubscribeEntryReloads(){const t=this._reloadSub;this._reloadSub=null,t?.then(t=>t())}_syncRatingSubscriptions(){const t=this.hass;if(!this.isConnected||!t?.connection)return;if(!function(t){return!0===t?.user?.is_admin}(t))return void this._unsubscribeRatingChanges();const e=new Set;for(const t of this._panels)t.id!==wD&&t.config_entry_id&&e.add(t.config_entry_id);for(const[t,n]of this._ratingSubs)e.has(t)||(this._ratingSubs.delete(t),n.then(t=>t()));for(const n of e)this._ratingSubs.has(n)||this._ratingSubs.set(n,hD(t,n,t=>this._onRatingChanged(n,t)).catch(t=>(console.warn("SPAN Panel: monitoring rating subscription failed",t),()=>{})))}_unsubscribeRatingChanges(){const t=[...this._ratingSubs.values()];this._ratingSubs.clear();for(const e of t)e.then(t=>t())}_onRatingChanged(t,e){const n=this._panels.find(e=>e.id!==wD&&e.config_entry_id===t);if(!n)return;this._dashboardTab.invalidateMonitoring(),this._listDashCtrl.monitoringCache.invalidate(),this._listDashCtrl.monitoringMultiCache.invalidate();if(!(this._isFavoritesView?this._renderedTopologies.has(n.id):n.id===this._selectedPanelId)||!this._isFavoritesView&&"adopted"===this._activeTab)return;const i=this._ratingChangedIds.has(n.id)?this._ratingChangedIds.get(n.id)??null:new Set;this._ratingChangedIds.set(n.id,function(t,e){return null===t||null===e?null:new Set([...t,...e])}(i,e));let r=this._ratingRefreshes.get(n.id);if(!r){const e=n.id;r=yD(()=>{const n=this._takeRatingChangedIds(e);return this._renderIfRestructured(e,e=>this._refreshOpenSidePanel(t,e,n))}),this._ratingRefreshes.set(e,r)}r()}_takeRatingChangedIds(t){const e=this._ratingChangedIds.has(t)?this._ratingChangedIds.get(t)??null:null;return this._ratingChangedIds.delete(t),e}_refreshOpenSidePanelAccess(t,e){const n=this._root.getElementById("tab-content"),i=this._panels.find(e=>e.id===t)?.config_entry_id;n&&i&&("dashboard"!==this._activeTab||this._isFavoritesView?this._listDashCtrl.refreshCircuitControlAccess(n,i,e):this._dashboardTab.refreshSidePanelControlAccess(i,e))}async _refreshOpenSidePanel(t,e,n){const i=this._root.getElementById("tab-content");i&&("dashboard"!==this._activeTab||this._isFavoritesView?await this._listDashCtrl.refreshCircuitSidePanel(i,t,e,n):await this._dashboardTab.refreshSidePanel(t,e,n))}_onEntryLoaded(t){const e=this._panels.find(e=>e.id!==wD&&e.config_entry_id===t);this._isFavoritesView||e&&e.id===this._selectedPanelId?e?(!this._isFavoritesView||this._renderedTopologies.has(e.id)||Sn(this._favorites,e.id))&&(this._isFavoritesView||"adopted"!==this._activeTab?this._renderIfRestructured(e.id):this._adoptedTab.refresh()):this._requestTabRender():this._requestPanelsRefresh()}async _renderIfRestructured(t,e){const n=this._renderedTopologies.get(t);if(!n||!this.hass)return void this._requestTabRender();let i;try{({topology:i}=await wi(this.hass,t,null))}catch(t){return void console.warn("SPAN Panel: topology refresh failed; keeping the current view:",Jt(t))}var r,o;this._renderedTopologies.get(t)===n&&(this._refreshOpenSidePanelAccess(t,i),e&&(await e(i),this._renderedTopologies.get(t)!==n)||(r=i,null!==(o=n)&&PP(fD(r),fD(o))||this._requestTabRender()))}async _fetchBaselineTopology(){if(!this.hass||!this._selectedPanelId)return null;try{return(await wi(this.hass,this._selectedPanelId,null)).topology}catch(t){return console.warn("SPAN Panel: no topology baseline for this view:",Jt(t)),null}}_recordRenderedTopology(t){t&&this._selectedPanelId&&this._renderedTopologies.set(this._selectedPanelId,t)}_reapplyPanelStatusWatch(){if(this._isFavoritesView)return this._errorStore.watchPanelStatuses(this._favoritesWatchEntries),void(this.hass&&this._errorStore.updateHass(this.hass));this._updatePanelStatusWatch()}_subscribeAreaTab(){!this._areaSub&&this.hass&&(this._areaSub=async function(t,e,i,r){const o=t.connection;if(!o)return()=>{};const a=async()=>{const o=e();if(o)try{const e=new Map;for(const[t,n]of Object.entries(o.circuits))e.set(t,n.area);await yi(t,o);for(const[t,n]of Object.entries(o.circuits))if(n.area!==e.get(t))return void i()}catch(t){console.warn("[span-panel] area registry update failed:",t),r?.add({key:"fetch:areas",level:"warning",message:n("error.areas_failed"),persistent:!1})}},s=await Promise.all(_i.map(t=>o.subscribeEvents(a,t)));return()=>{for(const t of s)t()}}(this.hass,()=>this._areaTopology,()=>{"area"===this._activeTab&&this._scheduleTabRender()},this._errorStore).catch(t=>(console.warn("SPAN Panel: area subscription failed",t),this._errorStore.add({key:"subscribe:area",level:"warning",message:n("error.areas_failed"),persistent:!1}),()=>{})))}_unsubscribeAreaTab(){const t=this._areaSub;this._areaSub=null,t?.then(t=>t())}async _refreshPanels(){if(!this.hass||!this._discovered)return;const t=await dD(this.hass),e=this._panels.filter(t=>t.id!==wD),n=new Map(e.map(t=>[t.id,t])),i=new Set(t.map(t=>t.id)),r=n.size!==i.size||[...n.keys()].some(t=>!i.has(t)),o=!r&&t.some(t=>{const e=n.get(t.id);return!!e&&(e.name!==t.name||e.name_by_user!==t.name_by_user)});if((r||o)&&(this._panels=this._buildPanelList(t,this._favorites),!this._panels.some(t=>t.id===this._selectedPanelId)&&this._panels.length>0)){const e=t[0];e&&(this._selectedPanelId=e.id,localStorage.setItem("span_panel_selected",this._selectedPanelId))}}async _updatePanelStatusWatch(){if(!this.hass||!this._selectedPanelId)return;if(this._selectedPanelId===wD)return;if(this._watchedPanelId===this._selectedPanelId)return;const t=this._selectedPanelId;this._watchedPanelId=t;try{const e=new De(this._errorStore),n=await wi(this.hass,t,e);if(this._selectedPanelId!==t)return;const i=n.topology.panel_entities?.panel_status;i&&(this._errorStore.watchPanelStatus(i),this._errorStore.updateHass(this.hass))}catch(e){console.warn("SPAN Panel: unable to fetch topology for panel status watching",e),this._watchedPanelId===t&&(this._watchedPanelId=null)}}async _discoverPanels(){if(!this._discovering&&this.hass){this._discovering=!0;try{let t;try{t=await dD(this.hass,new De(this._errorStore))}catch(t){return console.error("SPAN Panel: device discovery failed",t),void this._errorStore.add({key:"discovery-failed",level:"error",message:n("error.discovery_failed"),persistent:!0,retryFn:()=>{this._errorStore.remove("discovery-failed"),this._discoverPanels()}})}this._favorites=await this._loadFavorites(),this._panels=this._buildPanelList(t,this._favorites),this._favoritesViewState=function(){try{const t=localStorage.getItem(vD);if(!t)return{expanded:{activity:[],area:[]}};const e=JSON.parse(t);if(!e||"object"!=typeof e)return{expanded:{activity:[],area:[]}};const n=e.expanded??{activity:[],area:[]};return{activeTab:e.activeTab,expanded:{activity:Array.isArray(n.activity)?n.activity:[],area:Array.isArray(n.area)?n.area:[]},searchQuery:"string"==typeof e.searchQuery?e.searchQuery:void 0}}catch{return{expanded:{activity:[],area:[]}}}}(),this._discovered=!0;const e=localStorage.getItem("span_panel_selected");if(e&&this._panels.some(t=>t.id===e)?this._selectedPanelId=e:t.length>0&&(this._selectedPanelId=t[0].id),this._selectedPanelId===wD){const t=this._favoritesViewState.activeTab;"activity"===t||"area"===t||"monitoring"===t?this._activeTab=t:SD(this._activeTab)&&(this._activeTab="activity")}this._chartMetric=localStorage.getItem("span_panel_metric")||"power"}finally{this._discovering=!1}}}_buildPanelList(t,e){if(!wn(e))return t;return[{id:wD,name:n("panel.favorites"),model:"__favorites__"},...t]}async _loadFavorites(){return this.hass?this._favCache.fetch(this.hass):{}}async _refreshFavorites(){const t=++this._refreshSeq;this._favCache.invalidate();const e=await this._loadFavorites();if(t!==this._refreshSeq)return;const n=this._selectedPanelId===wD;this._favorites=e;const i=this._panels.filter(t=>t.id!==wD);if(this._panels=this._buildPanelList(i,e),n&&!wn(e)){!function(){try{localStorage.removeItem(vD)}catch{}}(),this._favoritesViewState={expanded:{activity:[],area:[]}};const t=i[0];t?(this._selectedPanelId=t.id,localStorage.setItem("span_panel_selected",t.id)):this._selectedPanelId=null}else this._isFavoritesView?this._scheduleTabRender():this._applyPanelFavorites()}_buildTabList(){const t=[];return this._isFavoritesView||t.push({id:"dashboard",label:n("tab.by_panel"),icon:"mdi:view-dashboard"}),t.push({id:"activity",label:n("tab.by_activity"),icon:"mdi:sort-descending"},{id:"area",label:n("tab.by_area"),icon:"mdi:home-group"},{id:"monitoring",label:n("tab.monitoring"),icon:"mdi:monitor-eye"}),this._isFavoritesView||!0!==this.hass?.user?.is_admin||t.push({id:"adopted",label:n("tab.adopted"),icon:"mdi:tune"}),t}_buildFavoritesSummaryHTML(t){return function(t,e){return`\n
\n \n ${Li(e,{note:!1})}\n
\n ${Ei()}\n
\n \n \n
\n
\n
\n `}("current"===(this._chartMetric||"power"),an(t))}_buildFavoritesPanelStatsGridHTML(t,e,n){if(0===t.length)return"";const i=cn(e,ln);return`
${t.map(t=>`\n
\n
${Ft(t.panelName||t.topology.device_name||"")}
\n ${(t=>{const e=i.get(t);return e?_n(e):""})(t.panelDeviceId)}\n ${Ri(t.topology,n,t.panelDeviceId)}\n
\n `).join("")}
`}_updateFavoritesPanelStats(t,e){if(this.hass&&0!==this._favoritesPanelStats.length)for(const n of this._favoritesPanelStats){const i=t.querySelector(`.panel-stats[data-stats-panel-id="${Gi(n.panelDeviceId)}"]`);i&&SI(i,this.hass,n.topology,e,null)}}_buildDashboardConfig(){return{chart_metric:this._chartMetric,history_minutes:5,show_panel:!0,show_battery:!0,show_evse:!0,show_solar:!0}}async _scheduleTabRender(){await this.updateComplete,this._sidePanelOpen()?this._pendingTabRender=!0:await this._tabRenderScheduler()}_sidePanelOpen(){const t=this.shadowRoot?.getElementById("tab-content");return!!t?.querySelector("span-side-panel[open]")}async _renderTab(){const t=this._beginRender(),e=this._root.getElementById("tab-content"),n=this._renderedView,i={tab:this._activeTab,panelId:this._selectedPanelId},r=null!==e&&null!==n&&n.tab===i.tab&&n.panelId===i.panelId;if(this._dashboardTab.stop(),r||(this._monitoringTab.stop(),this._dropFavoritesMonitoring()),this._adoptedTab.stop(),this._listCtrl.stop(),this._listDashCtrl.stopIntervals(),this._favoritesPanelStats=[],this._renderedTopologies.clear(),e)if(this._renderedView=i,this._isFavoritesView)await this._renderFavoritesTab(e,t,r);else switch(this._listDashCtrl.clearFavoriteRefs(),this._listCtrl.setViewName(null),this._applyPanelFavorites(),this._activeTab){case"dashboard":{e.innerHTML="";const n=this._buildDashboardConfig(),i=this._panels.find(t=>t.id===this._selectedPanelId),r=i?.config_entry_id??null,o=await this._dashboardTab.render(e,this.hass,this._selectedPanelId??"",n,r);t()||this._recordRenderedTopology(o);break}case"activity":{e.innerHTML="";const n=this._panels.find(t=>t.id===this._selectedPanelId),i=n?.config_entry_id??null;try{const n=new De(this._errorStore),r=await wi(this.hass,this._selectedPanelId??void 0,n);if(t())return;const o=this._buildDashboardConfig();if(this._listDashCtrl.init(r.topology,o,this.hass,i),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.monitoringCache.fetch(this.hass,i),t())return;if(await this._listDashCtrl.fetchAndBuildHorizonMaps(),t())return;const a=Ni(r.topology,o);if(this._listCtrl.setColumns(this._listColumns),this._listCtrl.renderActivityView(e,this.hass,r.topology,o,this._listDashCtrl.monitoringCache.status,a),await this._listDashCtrl.loadHistory(),t())return;this._listDashCtrl.updateDOM(e),this._listDashCtrl.startIntervals(e),this._recordRenderedTopology(r.topology)}catch(n){if(t())return;const i=document.createElement("p");i.style.color="var(--error-color)",i.textContent=Jt(n),e.appendChild(i)}break}case"area":{e.innerHTML="";const n=this._panels.find(t=>t.id===this._selectedPanelId),i=n?.config_entry_id??null;try{const n=new De(this._errorStore),r=await wi(this.hass,this._selectedPanelId??void 0,n);if(t())return;const o=this._buildDashboardConfig();if(this._listDashCtrl.init(r.topology,o,this.hass,i),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.monitoringCache.fetch(this.hass,i),t())return;if(await this._listDashCtrl.fetchAndBuildHorizonMaps(),t())return;const a=Ni(r.topology,o);if(this._listCtrl.setColumns(this._listColumns),this._listCtrl.renderAreaView(e,this.hass,r.topology,o,this._listDashCtrl.monitoringCache.status,a),await this._listDashCtrl.loadHistory(),t())return;this._listDashCtrl.updateDOM(e),this._listDashCtrl.startIntervals(e),this._recordRenderedTopology(r.topology),this._areaTopology=r.topology,this.isConnected&&this._subscribeAreaTab()}catch(t){const n=document.createElement("p");n.style.color="var(--error-color)",n.textContent=Jt(t),e.appendChild(n)}break}case"monitoring":{r||(e.innerHTML="");const n=this._panels.find(t=>t.id===this._selectedPanelId),i=n?.config_entry_id??null,o=this._fetchBaselineTopology(),[,a]=await Promise.all([this._monitoringTab.render(e,this.hass,i??void 0,o),o]);t()||this._recordRenderedTopology(a);break}case"adopted":e.innerHTML="",await this._adoptedTab.render(e,this.hass,this._selectedPanelId??"")}}async _renderFavoritesTab(t,e,i){const r=i?this._shownFavoritesMonitoring(t):null;if(r||(this._dropFavoritesMonitoring(),t.innerHTML=""),!this.hass)return;const o=this._panels.filter(t=>t.id!==wD),a=await this._favCtrl.build(this.hass,this._favorites,o,this._errorStore);if(e())return;for(const t of a.perPanelStats)this._renderedTopologies.set(t.panelDeviceId,t.topology);const s=a.perPanelStats.map(t=>{const e=t.topology.panel_entities?.panel_status;return"string"==typeof e?{entityId:e,panelName:t.panelName}:null}).filter(t=>null!==t);this._favoritesWatchEntries=s,this._errorStore.watchPanelStatuses(s),this._errorStore.updateHass(this.hass);const l=new Map;for(const t of a.perPanelStats){const e=o.find(e=>e.id===t.panelDeviceId);l.set(t.panelDeviceId,{panelName:t.panelName,topology:t.topology,configEntryId:e?.config_entry_id??null})}this._listDashCtrl.setFavoritesPerPanelInfo(l);const c=a.topology,d=a.entryIds[0]??null,u=Object.keys(c.circuits).length>0,h=Object.keys(c.sub_devices??{}).length>0;if(!u&&!h){this._dropFavoritesMonitoring(),t.innerHTML="";const e=document.createElement("p");return e.style.color="var(--secondary-text-color)",e.style.padding="24px",e.textContent=n("list.no_results"),void t.appendChild(e)}if(this._listDashCtrl.setFavoriteRefs(c._favoriteRefs),this._listDashCtrl.setPanelFavorites(null),"monitoring"===this._activeTab){this._listCtrl.setViewName(null);const e=new Map;for(const t of l.values())t.configEntryId&&e.set(t.configEntryId,t.topology);return void await this._renderFavoritesMonitoring(t,a.entryIds,o,r,e)}const p=this._activeTab,f=new Set(Object.keys(c.circuits)),g=this._favoritesViewState.expanded[p].filter(t=>f.has(t));this._listCtrl.setViewName(p),this._listCtrl.setInitialExpansion(g),this._listCtrl.setInitialSearchQuery(this._favoritesViewState.searchQuery??""),this._listCtrl.setColumns(this._listColumns);const m=this._buildDashboardConfig();if(this._listDashCtrl.init(c,m,this.hass,d),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.fetchAndBuildHorizonMaps(),e())return;const v=await this._listDashCtrl.fetchMergedMonitoringStatus(a.entryIds);if(!e()){this._favoritesPanelStats=a.perPanelStats;try{if(await this._listDashCtrl.loadHistory(),e())return;const n=this._buildFavoritesSummaryHTML(c),i=this._buildFavoritesPanelStatsGridHTML(a.perPanelStats,c,m),r=n+i+(h?`
\n
${Qi(c,this.hass,m,{showFavorites:this._listDashCtrl.showFavorites})}
\n
`:"");"activity"===p?this._listCtrl.renderActivityView(t,this.hass,c,m,v,r):this._listCtrl.renderAreaView(t,this.hass,c,m,v,r),this._updateFavoritesPanelStats(t,m),this._listDashCtrl.setupResizeObserver(t,t),this._listDashCtrl.startIntervals(t,()=>{this._updateFavoritesPanelStats(t,m)})}catch(n){if(e())return;const i=document.createElement("p");i.style.color="var(--error-color)",i.textContent=Jt(n),t.appendChild(i)}}}async _renderFavoritesMonitoring(t,e,n,i,r){const o=this.hass;if(!o)return;const a=i??this._newFavoritesMonitoringStack(t);this._favoritesMonitoring=a;const s=new Map;for(const t of n){const e=t.config_entry_id;e&&s.set(e,t)}for(const[t,n]of a.blocks)e.includes(t)||(n.tab.stop(),n.block.remove(),a.blocks.delete(t));const l=this._detaches;for(const[t,n]of e.entries()){if(!this.isConnected)break;if(this._favoritesMonitoring!==a)return;const e=s.get(n),i=e?.name_by_user??e?.name??n,l=a.blocks.get(n)??this._newFavoritesMonitoringBlock();a.blocks.set(n,l),l.heading.textContent!==i&&(l.heading.textContent=i);const c=a.wrapper.children.item(t);c!==l.block&&a.wrapper.insertBefore(l.block,c);try{await l.tab.render(l.body,o,n,r.get(n)??null)}catch(t){console.warn("SPAN Panel: favorites monitoring render failed",n,t);const e=document.createElement("p");e.style.color="var(--error-color)",e.textContent=Jt(t),l.body.appendChild(e)}}this.isConnected&&this._detaches===l||this._renderWhenAttached()}_renderWhenAttached(){this.isConnected?this._requestTabRender():this._renderOnAttach=!0}_newFavoritesMonitoringStack(t){const e=document.createElement("div");return e.className="favorites-monitoring-stack",t.appendChild(e),{wrapper:e,blocks:new Map}}_newFavoritesMonitoringBlock(){const t=document.createElement("div");t.className="favorites-monitoring-block",t.style.marginBottom="24px";const e=document.createElement("h2");e.style.margin="8px 0 12px",e.style.fontSize="1em",t.appendChild(e);const n=document.createElement("div");t.appendChild(n);const i=new AP;return i.errorStore=this._errorStore,{tab:i,block:t,heading:e,body:n}}_shownFavoritesMonitoring(t){const e=this._favoritesMonitoring;return null!==e&&e.wrapper.parentElement===t?e:null}_stopFavoritesMonitoring(){for(const{tab:t}of this._favoritesMonitoring?.blocks.values()??[])t.stop()}_dropFavoritesMonitoring(){this._stopFavoritesMonitoring(),this._favoritesMonitoring=null}_applyPanelFavorites(){if(!this._selectedPanelId||this._isFavoritesView)return this._listDashCtrl.setPanelFavorites(null),void this._dashboardTab.setPanelFavorites(null);const t=this._favorites[this._selectedPanelId],e={panelDeviceId:this._selectedPanelId,circuitUuids:new Set(t?.circuits??[]),subDeviceIds:new Set(t?.sub_devices??[])};this._listDashCtrl.setPanelFavorites(e),this._dashboardTab.setPanelFavorites(e)}};CD._shellStyles=k` :host { color: var(--primary-text-color); } @@ -430,4 +430,4 @@ var Lc={},Ec={};var Rc,Nc=function(){function t(t,e,n){var i=this;this._sleepAft opacity: 1; border-bottom-color: var(--app-header-text-color, white); } - `,CD.styles=[xD._shellStyles,C(DI)],_([Lt({attribute:!1})],CD.prototype,"hass",void 0),_([Lt({type:Boolean,reflect:!0})],CD.prototype,"narrow",void 0),_([Et()],CD.prototype,"_panels",void 0),_([Et()],CD.prototype,"_selectedPanelId",void 0),_([Et()],CD.prototype,"_activeTab",void 0),_([Et()],CD.prototype,"_discovered",void 0),_([Et()],CD.prototype,"_chartMetric",void 0),_([Et()],CD.prototype,"_listColumns",void 0),_([Et()],CD.prototype,"_favorites",void 0),CD=xD=_([(t=>(e,n)=>{void 0!==n?n.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)})("span-panel")],CD),console.warn("%c SPAN-PANEL %c v0.12.0 ","background: var(--primary-color, #4dd9af); color: #000; font-weight: 700; padding: 2px 6px; border-radius: 4px 0 0 4px;","background: var(--secondary-background-color, #333); color: var(--primary-text-color, #fff); padding: 2px 6px; border-radius: 0 4px 4px 0;"); + `,CD.styles=[xD._shellStyles,C(LI)],_([Lt({attribute:!1})],CD.prototype,"hass",void 0),_([Lt({type:Boolean,reflect:!0})],CD.prototype,"narrow",void 0),_([Et()],CD.prototype,"_panels",void 0),_([Et()],CD.prototype,"_selectedPanelId",void 0),_([Et()],CD.prototype,"_activeTab",void 0),_([Et()],CD.prototype,"_discovered",void 0),_([Et()],CD.prototype,"_chartMetric",void 0),_([Et()],CD.prototype,"_listColumns",void 0),_([Et()],CD.prototype,"_favorites",void 0),CD=xD=_([(t=>(e,n)=>{void 0!==n?n.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)})("span-panel")],CD),console.warn("%c SPAN-PANEL %c v0.12.1-beta.1 ","background: var(--primary-color, #4dd9af); color: #000; font-weight: 700; padding: 2px 6px; border-radius: 4px 0 0 4px;","background: var(--secondary-background-color, #333); color: var(--primary-text-color, #fff); padding: 2px 6px; border-radius: 0 4px 4px 0;"); diff --git a/custom_components/span_panel/manifest.json b/custom_components/span_panel/manifest.json index 0f60b3f4..2698f158 100644 --- a/custom_components/span_panel/manifest.json +++ b/custom_components/span_panel/manifest.json @@ -31,7 +31,7 @@ "span-panel-api-schema-1==1.5.0", "span-panel-api==3.9.1" ], - "version": "2.3.3", + "version": "2.3.4b1", "zeroconf": [ { "type": "_span._tcp.local." diff --git a/custom_components/span_panel/util.py b/custom_components/span_panel/util.py index 58df696a..9c419e49 100644 --- a/custom_components/span_panel/util.py +++ b/custom_components/span_panel/util.py @@ -5,6 +5,7 @@ from typing import Final from homeassistant.helpers.device_registry import ( + AnyDeviceEntry, ChildDeviceEntry, ChildDeviceInfo, DeviceInfo, @@ -551,6 +552,23 @@ def circuit_id_of_device(serial: str, device: ChildDeviceEntry) -> str | None: return None +def device_display_name(device: AnyDeviceEntry) -> str | None: + """Return the name Home Assistant shows for a device: the user's, else the integration's. + + A rename in Home Assistant is stored in `name_by_user`, and `name` stays the + name the integration registered the device under. Core shows the user's + wherever there is one, so anything that names a device to a person asks + here rather than reading `name` -- which is how the card's title kept a + panel's default name after the user renamed it. + + Empty or None only for a device with neither, which each caller answers in + its own way. A circuit's entities are named by `effective_circuit_device_name` + instead, which falls back to the name the device is about to be given + rather than the one the registry holds. + """ + return device.name_by_user or device.name + + def effective_circuit_device_name( device_registry: DeviceRegistry, serial: str, diff --git a/custom_components/span_panel/websocket.py b/custom_components/span_panel/websocket.py index a5de01f8..b0952f17 100644 --- a/custom_components/span_panel/websocket.py +++ b/custom_components/span_panel/websocket.py @@ -34,7 +34,7 @@ ) from .runtime import SpanPanelRuntimeData, loaded_runtime_data from .solar_topology import SolarTopology, solar_topology -from .util import circuit_device, classify_sub_device_identifier, pv_device_ref +from .util import circuit_device, classify_sub_device_identifier, device_display_name, pv_device_ref from .websocket_adopted import handle_adopted_curate, handle_adopted_list from .websocket_panel import resolve_panel_device @@ -287,7 +287,8 @@ async def handle_panel_topology( sub_device_type = _classify_sub_device(dev) record: dict[str, Any] = { - "name": dev.name, + # The name Home Assistant shows for the device, a rename included. + "name": device_display_name(dev), "type": sub_device_type, "manufacturer": dev.manufacturer, "model": dev.model, @@ -326,7 +327,9 @@ async def handle_panel_topology( # the panel's identity from here rather than looking up the id it has. "panel_device_id": device_entry.id, "config_entry_id": config_entry_id, - "device_name": device_entry.name, + # The name Home Assistant shows for the panel's device: the user's + # where they renamed it, else the one the entry was set up with. + "device_name": device_display_name(device_entry), "panel_entities": panel_entities, # Whether `set_circuit_package_ratings` takes ratings on this panel at # all. False where the panel describes its multi-load breakers: current diff --git a/custom_components/span_panel/websocket_adopted.py b/custom_components/span_panel/websocket_adopted.py index e601e889..1976c7ad 100644 --- a/custom_components/span_panel/websocket_adopted.py +++ b/custom_components/span_panel/websocket_adopted.py @@ -59,6 +59,7 @@ from .entry_reloads import async_request_reload from .extension import adoptable, extension_curation_key, resolve_platform from .runtime import SpanPanelRuntimeData, loaded_runtime_data +from .util import device_display_name from .websocket_panel import resolve_panel_device if TYPE_CHECKING: @@ -457,7 +458,7 @@ def _device_label(card: dr.DeviceEntry | None, fallback: str) -> str: """ if card is None: return fallback - return card.name_by_user or card.name or fallback + return device_display_name(card) or fallback def _resolve_panel_entry( diff --git a/pyproject.toml b/pyproject.toml index 77588f6d..65b0098b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "span" -version = "2.3.3" +version = "2.3.4b1" description = "Span Panel Custom Integration for Home Assistant" authors = [{name = "SpanPanel"}] license = {text = "MIT"} diff --git a/tests/test_websocket.py b/tests/test_websocket.py index 82576e40..7aba4ae5 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -37,6 +37,7 @@ pv_binding_for, ) from .helpers import ( + PANEL_NAME, count_panel_describes_breakers, register_circuit_device, register_panel_device, @@ -139,8 +140,8 @@ async def _panel_holding( return panel_device_id -async def _ask_topology(hass: HomeAssistant, device_id: str) -> dict[str, dict[str, object]]: - """Answer the topology for the panel whose device registry ID is `device_id`, and return its circuits.""" +async def _topology_result(hass: HomeAssistant, device_id: str) -> dict[str, object]: + """Answer the topology for the panel whose device registry ID is `device_id`, and return it.""" connection = _make_mock_connection() await _handle_panel_topology_inner( @@ -148,7 +149,15 @@ async def _ask_topology(hass: HomeAssistant, device_id: str) -> dict[str, dict[s ) connection.send_error.assert_not_called() - circuits: dict[str, dict[str, object]] = connection.send_result.call_args.args[1]["circuits"] + result: object = connection.send_result.call_args.args[1] + assert isinstance(result, dict) + return result + + +async def _ask_topology(hass: HomeAssistant, device_id: str) -> dict[str, dict[str, object]]: + """Answer the topology for the panel whose device registry ID is `device_id`, and return its circuits.""" + circuits = (await _topology_result(hass, device_id))["circuits"] + assert isinstance(circuits, dict) return circuits @@ -684,6 +693,58 @@ async def test_sub_devices_included(self, hass: HomeAssistant): bess_entities = result["sub_devices"][bess_device.id]["entities"] assert "sensor.span_panel_battery_level" in bess_entities + @pytest.mark.parametrize( + ("name_by_user", "expected"), + [(None, PANEL_NAME), ("Garage Panel", "Garage Panel")], + ids=["not_renamed", "renamed"], + ) + async def test_topology_names_the_panel_as_home_assistant_does( + self, hass: HomeAssistant, name_by_user: str | None, expected: str + ) -> None: + """`device_name` is the name the user gave the panel's device, else the integration's. + + A rename in Home Assistant is stored in `name_by_user` and leaves `name` + as the integration registered it. The card titles itself from + `device_name`, so reading `name` alone kept the default title after a + rename, and two panels the user had told apart showed the same one. + """ + snapshot = SpanPanelSnapshotFactory.create(serial_number="sp3-242424-001") + panel_device_id = await _panel_holding(hass, snapshot, {}) + dr.async_get(hass).async_update_device(panel_device_id, name_by_user=name_by_user) + + result = await _topology_result(hass, panel_device_id) + + assert result["device_name"] == expected + + @pytest.mark.parametrize( + ("name_by_user", "expected"), + [(None, "SPAN Panel Battery"), ("Backup Battery", "Backup Battery")], + ids=["not_renamed", "renamed"], + ) + async def test_topology_names_each_sub_device_as_home_assistant_does( + self, hass: HomeAssistant, name_by_user: str | None, expected: str + ) -> None: + """A sub-device's record carries the name the user gave its device, else the integration's. + + The card names each sub-device's tile from its record, so a rename in + Home Assistant reaches the tile the way it reaches the device list. + """ + serial = "sp3-242424-001" + snapshot = SpanPanelSnapshotFactory.create( + serial_number=serial, + battery=SpanBatterySnapshotFactory.create(soe_percentage=85.0), + ) + panel_device_id = await _panel_holding(hass, snapshot, {}) + battery = _register_sub_device( + hass, "span_entry", f"{serial}_bess", "SPAN Panel Battery", panel_device_id + ) + dr.async_get(hass).async_update_device(battery.id, name_by_user=name_by_user) + + sub_devices = (await _topology_result(hass, panel_device_id))["sub_devices"] + + assert isinstance(sub_devices, dict) + assert sub_devices[battery.id]["name"] == expected + @pytest.mark.asyncio async def test_evse_feed_circuit_entities_found(self, hass: HomeAssistant): """EVSE feed circuit sensor entities are found even though they live on the EVSE device.""" diff --git a/uv.lock b/uv.lock index e3095c50..0830b9ed 100644 --- a/uv.lock +++ b/uv.lock @@ -2380,7 +2380,7 @@ wheels = [ [[package]] name = "span" -version = "2.3.3" +version = "2.3.4b1" source = { virtual = "." } dependencies = [ { name = "homeassistant" },